sandboxgamemaker-2.7.1+dfsg/0000775000175000017500000000000011660750521015655 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/linux/0000775000175000017500000000000011660234322017010 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/linux/sandbox_krs.png0000664000175000017500000005235011654260374022051 0ustar showardshowardPNG  IHDR>agAMA asRGB cHRMz&u0`:pQ<bKGD pHYsgRSIDATxw$Y=TUgZj@*#&x_`0H6I2#^$@q@iNs󽝻+TUW3Jq{vwp8tlmoJt#"R3F6euhF76-" %$ 9kmZ["XmE;DQo?iWt/}ST?8В$F))}uS6Z״ mtCk0ڴsZ96fhZ7uuCSZ%PDQ #N"a$IZn=9~5J+ցֺmZ4 ژfz65mLEk]ZFkOhz4Zʟ^B)"2Ek"#Wx #nd=VJk0J)OSZW1)![fAKAd&%%,aV⪣_7J{FAQu rX!&>uo78qbDW=Ol$=Ɣ֥Tֵ1 u3-|9rf5uE)UJ!@Aϼ6 maɡ j& $I`𝷜o{x_ll1iO)o=o\̗J?Lɹ>"`Hץns>6 ß{$~Ix.~ _1v7Z/RJ=Wi"Pñ$|=z\cAX]Gᓹh3c x:% Rn%w$ qh`0z=z]0 Fc($ C(zx4zCZwT?.䞗}_xmX%$2I&Ƥ z]~J% x19WyZ8b3}Ă``0`80RBnjc("b$"8` ` bŢFgw6K_r$7&I m@Ї.'ތU,"q|4fg>7ƸKϤN&yL*ePN&qx4$ Cƣ`Ƞw1#abTUdbIzOVࡵdפ۔6dZ#a[G'^WRRoHQ8^N3Ylc(X4O{k±ZA`V ?v?㧜q38Ga!#og~Qk~[Wv!I( ,\F&]&q1f&'ocxJͤܝx%)q@ +VUN X>>Ɗ~cg#`{çHAo^K~w~i!/bZq?C3ޔԯ>AY|c8SڤR4$8PD.2 ![/|w:N]|35JҘg=l\ 5I(ޤIHsVQ'^ SZk0ŋ YLL:蔾X vqr@08 e9 r erh])fgk"ꍘ-=ظTfb~׻^ ⧕_4tFM"23f\?KL"\Ot:6$AuA;LOEC*\2 76VX=]T9q.{ge?1VBkꍘo뱼~׼gem>o|?0 JR+Iv~YG9OHsu~[[<."( Q4br_4'.Qvwϼkj͐ʍC"(ҧq@RIE!8# 6 m_Fkw9rĞGr~QLw{=>avwZq}z7V1ڽ?!@XvOLI9oPG7{>x?)O}i@<㡵*I9z+`=ϛ?c/2ZF]\+) uIt x/}1|8ffʽu_L;."9HU QjS$8%2 JnZ+o/}kzF:D(I\E2Pz`UZ1I9,TQr48i$c^^KjzJOsQ4Gə<g L2tZDvMM ~8'_O1?Zso)"n?;Jk6? Qce4HZf/Sϳŋ=8br9!tP!'TfcZ"w-3#*~`{8.|G$ VDPtT1>}.]D$hTZO4(=D"^U [kuE ~IyYI ě}-.'8N"d9T]pDYӜU*<%yjD 08| ш8bm]13msC!|k)3>mgϋw T/coĽJR"8 %<5ȔDkg_[-#ڭ1Y;3ochpu}= EBOyw=o/EZ ?%~)pg(_jB( ZM^ח/,r hAϋ7E,Pt1C2ZjZ?J4PO.&a`>0d@>r]&rIc|/^ZSvQ:lo+{nK} Q.e.f"fn置7(pE-}}6'iAwQwjbߝ{s_&^AǻE<*D/cR|7 }IinNk}oAxw* adwgQDߟeuu? R _X0fFgiDJLLJbS\G |bah3 U@fZBOO8\YTwM<( A)z.a nCQ<'hm(WʔJ{^,,XKkIAUM~ox(g'WdWϢٷMLg? s-3@Kκf L!kzfhw4{R }KKMjFd<}t *rTPP]Zo6X $TJM_0ߩ ǁurrpG.Fs+ϙbܾzA\-3\ODYIM=\a~5 E)0m/Lɣ~VS^5XC~'~fr©Skk\Nm9T.UJ,>õ_3BSLN[|>Q#Z4J+.NQI( GU._ iw{DgUKopuF+:-@)^o~h$ZOEݟllʶ `ss͍ Pl#M#Ƨ=(*B4[-*UsƔ ʺk,VIYrg;NZ@ȉbVt^|: <"8(80H"C!I\=EjXY9vL!QNQE+B&=z@S#FupK_t]ǐ(B"BFO,H5K#J~/> _ STzYD$@۷?>`gk XJi9#l} jF5G곶6Bi?m08˨gcǰӛpebI,ˬ N{Lhv #tjjj #Ƕ(ek̵< 5`m!I: <[P?6cmb)K(xiXkbow'&5I83I,A0??OP2ZшhM-u;+<*GTFgRI9ybfs\-\41S'*hr3QTFhL~% hZIӨ{4B‡?v!hI$(e]jAfPA[v;<\|t>e<* <0W"Vvl_>OQ3;dȃM,FZAlԄ8\CBS xFr`F#0dFd9TvgʐT~KuIIQ*D,h @";lb" `L7ժ4.,Y)-rp`8C49ZfyQ37i4adRm<|j0-֚&WG!c+/Efəgr ~6*e5GRRHhJcY]@y(r]IC8Y:(:aT39uKdQZQ*{ WYqƦeݠ ktno5,/:B6[>'l9{17IM2\B3=m5B"` 묈:@cjY.Lk-zx}$ٸNu-\86tO&g6'|S*(W\<zX11xhpk=Mn8h'nw@WF9PrF(K&q$I $3(vw\gu&B,8Y/V9|ߧTVhTZ(Gdv!de.vђ+ GaZ{<8qRK9IT)5qژNBĖ!#zy$܍';DbR1x<[[}j1K 56klƄlw gBbB*p:O AfIy4 z!.<Z>$BDD #-DKiZC_-6mʪ%P㣽*qz2en a$|wzaխZ8u8wXFӉb+<%qPlnlnﱷTxK~*/}qre@l=4+' e1K[ anrжG %Vobiyag2ANu '"4MvvvG?Bqƣ&m|Ӭ? $EXJzF{h.|4ү,_B='C z=ǶK\;ï ^ l@lr{>2hDϺ}>K I]>@, 1ZO 5G a% :_s0/]rZ벏}@ADڤLD|)\%YeϦP.T&S'/߯0@ɟlN'$'\xtxx~^o귖fS!8/1 <OQT K[w2Z+(vSDĨt8uN<(4-Zhm= MeXN(-j5'g4+s,-ڝ1[}p,.oyˎs(Q I" F!^UDa4JQs׻W~ |K1zx\H0}\"'* ZjNZZR 0.,.Q#u/ՆT%NJ cpܽp_M$)~lBgk{7%%s,ETTkU0%/˜lUn9 _ТqUh|uDW7x٫,i.*/{Qju@ڂ~?b{G^`R) ,sTyt:w jjFZ:M6ʕJXT*Od.a8; z. qmX%H¿EQ{AhCN03U8! tڼʭlCJ*~PE%m0S:_rGiРhw=f4&o{G{zR咋>%enJ~A午NKMJ1 U$)IG?l] äITrArT&ȳ!k cN>1 GQH$ea~%CDam'aX~PF{uD<^w< 'Vvvlruӣ\2iˁ\q D$=WmT||Ch } pyeoV`^?ϠfƣQ>QQy)<>Ep0 Ie;)zlY=S"J*xh0(jBKBTTg׸CCNF݋Gp 8qŅZqHvu駫I.h:`~jL[w8yk{ؾHR櫾yϨ\.fЮ(EE Ch0%c4r)QZxR fB Iƥ> ̨l2BlZTmxT+Qfoyrgxj`JiϾ8Ϻ]B$0C;DE& uְ? 8[JÌrl7-?rYuy/_f{k=8 GTUF_]E܃w-U'巬@3쇴͘Vlx+ufbR-#ew2lӧRsTjđqu l!-7-+($l\P+[1Q4Q˄Y,/ QX^lr< bf.Rpr{߻Ǡ?@@k$I^z~A__ʡĉ}[7?~s ZVzjhmyHh8$Q^r* {=a~^6-D!+, Ø *)5;n4w}9>lqE.]f:C|VRwF Gt:Ϝ_Xw󒑧^?\ڢ%BZ͋Asi&=tMdU?%G{ri!*WVٔ:u TUO a8/* Ưio|d*ǖl|M^LPޜA {1=ͷ,<5oXZYb{* -MԪ%ˮx9$' HStIb%Ҳ=fOӉ }6y);vHV`Њ(_;<~ ox]غ֞ Xr9(YIPtz.ɓrJd6*JPoX^8y<g||aG<*0gkn3tYZry=" ?ΝwZ5H{DYbsg{.\d{+ZĶGYZMl,,3737WZ+Jc"ʵ(X/FFHzJlҝTS\>exI4[sAx4 `ѕ+W|n_+B!#(W*iAG1c ;ۛyR`GW*2 W1z''RZ2Zp(§c,u`졛377Oz5ަV tSE!/r3ԛ4׈,Sh,-X[a J$ %TmF$f=!!Qbb"}*go<-6j+CRaiykka#3שJxjդ\u7 NodmWxֳwP5H * 5Z ]yVL;({7F#JϞeʘ_DF\kDqq8OF*Ħ\ ֈ$N닚Hѣh`4 .VY^^^hr7}#ሏ|{8*uqLjeX1̵j,-/qley | Zw}7Ib;?Zt imvʺiU])ǬjS?5 KT .+.A&@+ŕ˗Yιs稖*;8IBS6[!X-Q(=|S7"z k597OF ]NZ*s,.9ï\Ba)ySAL3ު|=I_{ ZlbR׈UD)ĦUʆVNZssfIw>sh;czu}>QJtBAJC%ghkq&70ٜ\&(/E"Ul$Iy2t%YI!Kvkӡ"%vq;&& IG$&MVVQM#3A&DIWEةt s,בIm%֞w(Q ~]c @$35JY:wWWY\Z"vך~K.LERFCys <7:NtK:&+7TE tTN<}*(]]SM`&e^v` ĩh&:.-I>$&,yT:r+=>CaEM7REZ/*9S?elƑړ?^B<XD|kqMN8#tmR*\TUqdzi1({37@]HZ>\Zi ZHPhhQy/JSȮ Fl,R)`u IB<XR ZiVs\Lp}s%a>xֳx~.+VyO90Orck]tUqĉWPqv`_I9>71<4x'ԙhxظ >1T=*{Nꚦ,d.xOmEuP\w:џ }$ I,D%C4RġDtU\^l6T+DQ6x\r0l6Y9vӧOs gתjM2EU%⺺%1&HDjgarOi`(nom_\RZw!!"^籸%S*:+F[j;ಉ P98 0H&&1Qh !0"$Ѥ1+/Wj5:A) cv7yظzNp8tjkkk={3gNs|u:{;C B:QvwwX|>^Wb" @Rɨ&`ȄY`)]rβp2ۉrW=A@Gpe._6^xf(>}n3gNDpZg%#paE6~3#Q3IB']+vC'D ȁeT-Lf33A)>~٤6*f w[oKKŔ\BdUR`*;ߺM1aH8q;G)2rٵk/_fƔ>(Ngz+7;<~O>7=d )Ƀ>5$gEfܨɠ/k}+YU^Z7@@xͱ-DS.T)@ȤCYtHMcVVEP*Qya~a￟ݼU&qz )5rQ+:Zb-(s\!kffJjť%VguucǏj5)"p4È}sS*=֌Ð0 S,ɬ+DIFdiLbM4X$BEZ{UD8D"C i KZPh'u4nшť% J%3 }ʫ Ff7+lAk0t>mB0i7SZJZKL1,=yq1‰5yDq:|K/jwΦB.27n:>[aXKiT2Xqbve3 0&VIEJܢW¡Ӑ픊H%m; NKAh=d8rzRRmf>#w2G$!}4"I[3/zNV%|U lS76I (aaT0h68s )@&/)dnqvaM1JeE埪lUDQZk/UxƵozKD1*2$IOܷE#ډ~Qn펓c7gx83 (h4r1PtDDŽ``0 üH+ FfAZu ]/ODY,kLL.STgcvvvi1KҘi4]|'gN& JcSUna6ߦK<ؤ0 D+U+ ʚzXk3* {[ בmղOr{Ӈ$N{ 뀰6nr20Ix<뱷GE2}^VT#g =A{^ xTdάرc8yҹgER][\V!8(D F1jq^xQX)"mUbͣtUARqF=sYP8阼0M4N\Rx&-zG͞tjec(K:lL8RoecJT'(\t|[n1N^XN]g FMfÐ(1~q@kDk?n€(v]Dpr]E"/-C)T,CaIi: RʅHijյ5;F|xFc|>`\ *.*?5sWX5c-`%^Jrhbjj|)ŷ/ K_ӢWw$ٙXEQ .<#ONRj`H$IVTT0#bS ̪OQ٢7gN̍,8u-ً ]`K) P th8J- 'p8 qh: `ŅmLGᅛ {s|HJpeuv!>?ųkק8? kZբIf0w=no߶bA/xrGlÊ=r+*sW=-)Qg=׸n&keow͍ Z/%喩U͊V5^qjH8?xBvc\/G1S=N4)2/A&X$"wyg?_Px8Z/*VۜNA]d잁CpdzZVP$zr97Ed{(T\WnS'Bgp=ih:FxX{5_ww菓J{ x}RyZA?3fAG("RJ"=$INF]M8zQ NɓHdѳ up-0%-܏1 ֺstQU*~ܟ@"].%2_=(ݓë j__SɟHzR߉s'R㪄>qW(!HpSoDxR}+ % :=ayǣ㯫pN*ЊE*gU7-0ݠ>KB/~xPPGy^ 2Z||mPe-]QTĉiU͵$4aP bfqc taZB;>}C@|XO[d HEQq [xG죁m[7op']"ٟC)/^/")"zapY#p<l6))`TaTÏrJd1"׎=[Rπ7xϠ?TU}BOxRswND>ODn Jc׉ήƬK7ޡ?9 X)((@1ϛD~J?cJpwgz2S:T~n 0|+m"TQT׿@Tn& SD';;"L 0TJ}] o'{iI@v"RQJ}|pڵNk&r t:DQt 8&tMk${{RoL)u MT-rm__~vZ׶Z-/ۏhqq>ŋ#'^͈TCR(R)[J$ t/S~|Z:}(OU[\\fY1l5K+ FU+^끗덫W9:@Ok~hXk}QD}wkN/F9wʕvW+No=o#IOO;qFĝhMqh8 j1%tEXtdate:create2011-10-13T18:23:38+08:00.J%tEXtdate:modify2011-10-13T18:23:38+08:00ۆIENDB`sandboxgamemaker-2.7.1+dfsg/linux/sandbox_moviecube.png0000664000175000017500000005164111654260374023232 0ustar showardshowardPNG  IHDR>agAMA asRGB cHRMz&u0`:pQ<bKGD pHYsgRRIDATxw,U]{Wu<}s;A%I$!l0 6 <  `#pď J ^];#Ssvr=WVlnmYTb1YcYcf59Uu;r/{K~{S{>#UP+ܫ<ߋl=7֍ފHd1mcLX۷ 5c;g7[c5֘9c̬1f&1kL[H`Uժx^ Oū U*?չ'םs_s`2֔9cc֚97o],Ĝ 7}cm1ƴ15&2Xc Ƕ|,^3k"x}*0xj^? oEvu<θγz>xˏb .M kƘ9Sr3gY4c "JczMtkA"~NHX}JA$uS'oKWr??PU^_+WVoXikؾ1f,cL|əƘoJ-cLdDc gAӽi@axLs)%" TAգ9p=Ν{YY|W9q7bN8>tb՚h.\0 .gi[cWF+& }"Ozq(lIh[?ky dscM鏷Zso~>4o~_ÑV+K8~1KD"rXN$wdiJEDqFکꅖSzVRSZk6""*"1}AL9<'MS$a<1 -vw߽!ш$IHGTAot^$հ0Y`x-l<-ZFqDDqL\< Cvq΁F!(z<K4IȲ97E1Ʃj柛M>@J[; x\tm5:~+RB>X,prq.3툶5X#` bLoS~?BŽ3a5 s{)UA 5ǚgo<Ŀ)oY>k{/I_[7^gue%X λ"fkA{)QP{Z K%KnZ3G' Q AL"~n@Znybв$2ۨwW%_1zjwk>iE`ʥK(1;He?PSb>2$aqe9.-+j)D$Q>X- c܋XI9N'(=o?9yfjNo/%ATs_<).\ M8.9>uvȯe潷w'Vo~d2+W#"sYyMGQmIeIƍ<#U%KSKT+JId0#|KOpj&%"p}B@ۄdFG¿ksm zIhZ<1i ]?} EYy|-Ā|A$qkss''%@7m}a,C2PՉԆ*gH/8_(p\SElֻNtAȗt2N~2p7u~9@+Sy~NDj_|\ZꜽLpo/ÈaPmm#ӌ4,gc}/8_|2[ZSz)#M ^b_o~4q Ry oD0|"* Ƚ{9ۣq8 C1!kgHCgwlnl೔/(_~ZZRv%cb,UaBo:,D{!Ιߵzhx:yj5Qz~Az_~81EDR-|D}qazL@p571Ɛ$ɩϘ_~po/(_y!fc*t|IZi,xʹ!ᧁ0 )an8f#H&0Y a ?o#677zJUȯ,2QTI!K3W>2_C, q&&:HevLd?J0 0w 2   |< 0ZLW0܃js_=@ )ʱe<sE<Lj0q(2[b)ߵĉ%D7AH A ؟]AS}n>WpB]0)=$F~* S1ɥz\P@idW{t{{'d\T6k uzшL:sQMrQZ͸%2&ISJӐ(⊤e6s"Y{?wߋ7lĘ7LS` ?SY[]+~.W1,qFQDC-bc4O\ӆZ[2LƵ!nn3€l Fr;?_@Ǟ%11rh_BL[TZ|25o;*ӬP ?G6w,t tL[D\}Mub&Dwi4Uv+Iv3F$1L(.噷9s"(2S?8&"B QdI.CZ46$(şZ:.DŽcm "5n 3qt) 6ߌ xLVB73)E- w&DGEQt;#$iDꮛZAۣ|Ԟ O] XT-NjfPf8 6|4ikJȩHgtĨ2nsdu`f3,T lҺubgB%_ _g -8eKWA_g(̰6+ܸC2 o*jFXJզ7g[>s1oA,E R 8Il ʾFSQlgmZ6O ̅K6BP4q-~ {;H=cLَR?jpҥyscsqCv|) g }#AOqi6j8,Ϲp<67 GDqT|gRzPuv,3ABJ5'rCk˕XB7@n=]&9|ZLK6^]K̽'o77Nk)@H˂xA{ _%" 5vZl.`-OnUKlmmaaow04_ː1t/nj}VD^qဈA!=nlI2s7S& ̝syO[{HU ǘ͑IQJW ʕ|f@d]3G_rvׯqZPGiRf|%Af ShZkǼб 9zKi򹧒:IL+s5#9+3^edi)1/_;J]c|M ͡(i^2v厇i5q/%_IY C0vYU{eO? {{{\<]q$IhuSg!:qz }D3m b8ԏ'q?a ֯5{iƍd6ݭ6Cv7o}WΈ~G'G|srC[a6Rk\|sK1',J *GP3sHU[q7+} _B[Bs GCDU*UaBDUj XXXjq[{l  R$|n8 3ܠ7qۃ=FPV50m!sin&'C&?Hh*1ۍy,1~6W.hUrJU?-|ʛ2T5*}([]Z<#"lmmrFЧ.S&W m:{Oq0֢jUl/^? H,B76m ?zWgj8] ~4)sﹰ+_+;2?Cp ~ Nj 3 ^]}$=콏f8i\s0vYYKޓG\t M]TZ:?,D9ÉA*0LHKx:e+G׷&!?C8 h WqdsE:'&}a8^nimeQ0r JV`h){`xO !σ777*GҔ4I~2x\t{G霣n333C["QXrp&yq:cŒ!Ua}Џ{cjSޑueYD51n*;fSL[Ypl SN4Q"6\oXQDC=r(XZ06BLAc@Ɍ>0/x9xbc5PnkxjDPXODDQd,n=ECGﯯ1{;Ѳ:f 1~W-B4W+?t:DQ!gڂ\t v1gs x :d>G|!'78A/hsfEqGLe{ TolH[߄~#6oF LSp=/{z:NC޻Y:= YE^Xit:mz!zs$1ׯFIWY3`zhh k ke6N~Gf gϞiCEb' ,lvSGF`@҈) /av*;4ЇPD.AHq5F 4,,cŴ-.~?>^vC"*DV "Xd RB7R`Bz) E8@*)ڏD716hҩ3?Ⱏ#iêI w;I6eC!)bbBEcU(]#6нV,K bD@1vnKۭF!)5:4ag{hwuw}7z` k ܱ洭ڪGHdynYTۼ[~w:)]B-U#5Tq 4pvwXǼhf^Dzcf+ 7i/fn&mD\*?9x{?QOPnii;;mZq [ Cwa4IXqxFbF@(w^!qu}*Df"pao^ʙmnH(H}-ԴAޘ |6qE$-Z.)L&}^+W8+'v!2ƥ b3QgfO^36'鋾O}k QjWA5C,z/=Ŝ0˲0HAM<[0$B˜u()4l;Y!/ȞcZe^ei(oi# [h ErErp }ӦAW n/(^ SNqmE>Hy!ߕ)pC:^]:KKg;Gy~/iе_ONfg'jF#$a<1  Ga#"tS՞B9C,KALv&.S/$.Ie$2h;IL܎9tgLfjw,-N@#alq/6Hl,6!6G%2IHO礒YDYndۡ`28{DxկQOܽke#ygeܥC|&}|~mv{LA2K^KH "%JB+kw8%h1O>ѵM'c,eɈl<%l|1({@nzmF `B @mcXk",<*}r}אDggm,r=Cwgb0/[bG~/ bλn ˇX\\w{@Qկ>.WWW@lom)VLHXYu_J*d #tyDE8 :c,c䈹Ԁ95.дFe<$~_#tB&zZ:㛏p-fVnrS9Pޱpoea#T_XSET; looCŴ|AP @(cN 8sXq D18,/rM*tc1w}ԴR3'st BBGq(S3&9~x9Xv,|Q6nj6#Dxj F9I yY'N(bueׯr7J$(^ F^EQt ]و<9@ z{ڝ6;`n?Ni%d(too5t:]Tʩaۇ@VEIqcvnVEk<~0ֵK.e/_)&yxUvvv󜥥eN{1=v`?ƍqݺ݊@2sTvf+IsGKQB8"׷c2e ,Ng~0) O1*-+=bŅyO=~S>RO' Y,|j-QkDΣxImn/:mY~5~WDu,Zcr/^=@EG#<;=Ykoj,^)R׮|53p avn O>h4l$e@<iJ-L49:(&Q,A/p<'V8Y4ˑvyE4톸~O`Glf\vMXq+Wxu R'UX9A!ނeFas LDugًz8=ޅ~ϡe=efffB4ؒ[|cOd$ѣvMU:_j λ5s1V4IpcS?kS7xަjw'I]!Rn䂪#uY8IcP_J03;iFIyQϹ#5!Q9vҔnh7D0BMUW_]t]t1JȉfJ{~1m.8mԃ-Ie0j2] Da?Gfaa^\J(Nsss9K^>nGƘ5rTK s޳M$;~ٹY1.cX\Zןqb(..ψp%^slooʘ]6r8SDQmx4 u;C|(eQ'h ֚T3 2F;x!jVRul| c%uGc%#ZW ;O-rHgƭQLÞCa\y-/1??GݩؑVaiF;w.Z/ݬJ-iO|O܂0x n;z <#DR`xCn큘FC}qm}x^@0Q3 $vHeINq.v.*!/ꫡ!xq(Ćh6ZKD2g=R /=fgg t;qL6V 4 rJW0:?p9ϳHJa\W7n`o8̙[Y\Zfg{,ϰp[#sULiG>a^A& =4hQ:틌bT)A e]JEnyQQcM1fPlQX9hFL^晴LpMD$8.D%V~`0cB[n `n\_c4U9hsu>L (ʲ0"y$u- lu5 /ªZ-t/GskP)8$ʻڈȢiD]"*)#Bݡ1vEY.GrM▨ _e%?tW>UW_56St54bmUBRTRdnlmnrifgg+TBvs<Ѓ"\rKt:w8Tp"~wSs >+J#2P6 %sl $Ń\t #dކ 1xOQPSzjqK%b,-"\)Jk n~OEYKj {+VTUV+0$ @UXYu@R~P5~xA  xǎLaWp#:|}O"x<K?UPrik2)8oVNd3GOߺ;,!y}p< ޔ^s}.CBDBL5 C{.;<£>zn~W_ciA7ԲۈRuVmxQSU=!2EEsmEkUZH5GKlomq1Zv8{^"> 5}c\xIN9C"ˋGiq#6@0 FlŮOO)_>(.\d}}p4M=/z_#+/`mrp ~m7yuujs2U XS/<Uq1ܰ7H|q_(Jc,'OfvnG|kW-UamuwGnjL8Aˑ.mu`5-`h%@2, !tCDE@#S 9T!q++F1t:avvnGe|{+/h4"KCqvvGp)Μ9L6,Lh.V؎dl\潿("NUkk?@RY-x :"Z-a7_gwwť%nz/}<?U|%KKD6"B|5Oo=2"Ir{c\临NyS0Uwj;G=3rܓ: yQk >33SI5.Or5^0??ǹ[9}TPKgX][gskTnZ/5T->y+Re¦!䵮Q)ZqzŋDc _+a4x`vٹ@jq]w3C\ﻏzҳVV" (˿ 5KPUUR84yZ^^G+nA_tK..8!/sIn,Obyy9HnT641kLLIX)urմԩsܻ5;l))8-8@M9ss t!4;#=~w-7 $.1,w'w,KaԇKqX BIhHY51P)C,EZ/Z~ [WEA@2I҄]昛^Oaaq||_m(Mcl;la0>9E"N摼1:KQ< i h8b4k!nMAV(ytht zse.?[nzᆎ=q7}H˽jhrS eâ5)ZMN^G۝ jM"g9! ѣ8vGannVEl2fg{__$I3[bJ@$im4H)*i~r 8,Y~!Ue.t󧟫)zAMpM 1wdYfxl){Ts^ǻ.N:U-ߧ3 |٢x+<)T<^$Q.zﯔXQL@mK*O!!Kgoy<U_n4Mq_C{_B}qITS唪.(=^d 9P]d@HM($IBBb#˸݇]dscMN>ٳ_X`vv`nKt:q cJM[Pf=R0:. q5\ Ri8q *~B_e^u:mL FHU[]SaӬl4ޯ{ '|?|#:Tѹ˨J(yk^T4ח#EZŕT?;Hk#pAY__;x<&M2E9 /{٧pJ/cBEC JWs oFnPh:rxē?G??^r=s9‰[nSn[zi2'T-WSMeֶMe.[h}JkRp<)þ^|wA^C$ZkR%DqE1`R^!+P}J]Δ:(_6Gݢ0muK76k-)þRt`c(tZ׮Qݸz(HyD+W9VT#^:C)µpEHcP|W4A2}_30`jCv`v4Z]w`vC]Zj&Ь+2Z4PfvM;gav)MUZeY^n4K&Tk^5~4w6 f.dyFvi߿;|?e3Qdq˔s"DrbS}z:6E^?yz%Y>uFZ_U `E\-G`/zOk4]2KWU.KC ApKVz%DUHYSa>axW*.akk{;Poe%>s>k+/cV4ջTt"D)L&SY\ɍ깥e^iFӭDdS\:}_`n V.(o_1?8*V5˼QWↆ*%Y`;4#uo;LU1<C?1y]*vg':O*-H.zEm}UIYeNT\],Tf]PFr+2.UU<%T.amԏZ@ fB-߄A65]|8[gF~&{W.ask͗slomyv.~DTI@P忀W!/K7?S玳uQn6AqtPh}'9^2OgϞرc7.%{L{,uTY;6Yfr 9FaorHߖ$~LZ5)_?!"˿/?(-7[sϊ+o.'yS…H:jۤ?^$K?)+R5ug=Nn%єV=*V+V+_&P?OU|wR 2wD`/- *s1NGX MneN:UtdF @74?3o<à_oQD|R ӀyGzEoT2 pӀؿ"*|@?+^#(Ϡ0#7T~qUgETy]Tc/Eqp7+Pd2j6+Q :lU?,Q`Ewo} _S⭈>GTTUzEP Ei0 PfM&K|}>%Y)N0 '9y{F^7o}x=ϼ{RտAo5Pއֱn7:ڔ*4>.½ Q_x{s_;>h[3~_-(s|6# ʚ=87Q}')pFsvS79kmҞ AWHք7~}"dz _egg`v;Tu>yf]@io~;Mݿ_tHݾ0 8o[>#dzmtk(* %J7KϪkx{wȲLMpgxNv"η~sg6P~!CؗDQ5)g GP;u q~})_??o۷isoF~_‹{[:􆹹O<Ʌ X__ætd@U#"E8^q?KTx~edů Zfz:.\duuh4y3SuSA?/"WEoȻ8|}I" vfgc0,(g++\~;mG?v?[[[4=ND_ca|pץ{Q~oy?O+}gq#Mںeg'pOyX][g}}*$a"_1u7~=߷Is|RJ/ ef8̍MsbBk|1???_[i3b޴/_n{D̻1o7F~j]soKs_1֛]v{g[ݙx7}G#ב%tEXtdate:create2011-10-13T18:23:38+08:00.J%tEXtdate:modify2011-10-13T18:23:38+08:00ۆIENDB`sandboxgamemaker-2.7.1+dfsg/linux/sandbox_ssp.png0000664000175000017500000005272011654260374022060 0ustar showardshowardPNG  IHDR>agAMA asRGB cHRMz&u0`:pQ<bKGD pHYsgRTIDATxyeUY>=w5WuuWzLCƄ@DEP`D ((2 *DE @LPӭ;gû~{:@;w}޵wq踹F`ooϢ"&Vئ5m3k"2ιEcs.3疜sι9\۩&ܺsTI[c|Wy>j6S+B` #Ҵv1=cM۳1֘yc삱fω޵cMӰƄb$ZUmNũKԹmU}X_REͲgwݗ>O4"H+BhMcM511yc̢fZ/%ؘ5cmc>&kA5ck&aC؍$ុo \(F#&441-S Yti{Ƙv]:1xJI#N{} RVDj.;1/w;{޸S'0sy^'6M11Ұclí+iY0,k֘y%31e4ĘX1Sn} CC""9:xP!Yg<KwΛO<oxqӊZ#s1 Vkh,Q4AAߖ]kMcPk&"VqOQO{C6mk!Rsd.#MR)`]vwfgg%I(,o{^R~/ FKF?." 8Y ڃP-Z%=hrk9BP>N֟ɉhtYYFeiJL'S&1шpp0d003?!шxd:%ƤIL$=N~j[/)O 7~ή7׀Pu=U1+jT˅)h(>^H8roNPkD5a!aQEDp?h8̉9f8e0yGcɄdt:%NI4MH,\s^3涀18y#kkoOG1K)ҋ.<\*Miii))F@=7*i`%,A6G:OӄdD'L'1шKp8d8:a:1ZN=O\ILUũ9qգR`:W3+(^g.vC;>KN|І 98^v.˥+%!l.e6%&^2=\:$!IOp;ZlOD1*i$1.sYJ$$qt:e:0LN=!)q<%c$!K3, Y?D1;8ںDfyƩ1Cl4M]qw~\Q-oLTՈ/vY-tUp^XlPc p[~oqK)݂1!Q`2ҧ W~ve1kk4%KS4!Msb'jí˼UXه:Ka@0# hc (KK?yk,N) 8:SVp)_s? p>3?5 Y}sTL ?@a nQ#b2~fMruAjEPчȬmr 7SX09?Aj}RjFf22JWucpN1t-Aa4pν96Je ιoHsWK1L&SobowN>/HAg\*OԃO}5F)E!V,Kg5\knC+hِޟGX$TT26f̔0֘%)G5q) f<\v}^r'|~"ƠK8̬fRv "|2uXv=p-qXbuIW])TEe|VVXl/ [D&3M= J~ǘ=;b sC.9ɉ8nW2]J?wn `{T"N !?@x)]5a-66v,JO4nO{%*uPhGx hIW0L0֐e*[w_݈W#=q7{gqqX11Db $xO,9HU'32}"e_//x+"!˲úvgX7o`ggc}4M2 dk aBuH(Bel'Yw Xxb3B`LуPSƬVa)o&20|X? AR^Kk!皹G,_͸3 —Xk0֞{<Ax85\}í74e:>+ \1wF!|'񦋟?' N3|ԞYJBގnsAg/}bDD?3~DXnkA@[aJlscu5rx*WXf>Iq{y˝o1uS^' r2H0Q CP1 Y_"k_Z&0Z=čgK⇕/6nd2ꕫisYV("`d*H !y<3y7})F|Hݎ*Z5QL>3p*Oc"|s|/%F }*ԡn>÷qƣBUh8oxqRңyVH37(!XkF{_? '}(ߨW x9ouC!aX]ndccc I0(o_A`iD j!WM2g pG1c7pɋQgumV_^t U/bsu35^OCX)W\&aOǾ,͌ePZK$ "\ާ.~#|5HSwd4`ϡϩ)APFra4cC糢.%!95)bl`^U_0B7yUv*{#>I3TVįK_J EVMiεO /`!Z#^C9$ud uuX~PhqU2GN.I*r>z*#; ᅔ4A悤bK0Y{)$ڀ#FNxwvJ5hw;&w.0a^U*FQ%T5c­cUAWR>D\(-o[0ogh8FZSLK1aH_k1ڷ$SA wbύw_n_n `)™ pƯHAׯ];[iJerjV1t{=&'X*Nђ @lRALse֣*S> /qѸ疙 gHA|f_O!p0.j((_'v h4\|9-0j`ӽ&/CgۣiӳeK.mR. 30 G2apS&vnhΒjhvHzRz)tpC=I:ю Bk&̛kɠpw^*>z7.Q%[Z{LEEN Bo#̷67 TW.?x[^#9bPkW@ȉ[tPe$_."j 296n9s_UԒ9GF I+ [> *'E"DА-=vGa O57#18(Ð(??hZqU\1LqYEZ%p=Y|3@ߧnӖmmV55*..əHƨ֤r˽,0.2M>Gx&b#}iVk ~`dסXT钥aFD);= S4=A2f MȒyG^(c̲֔dUj3y駙Ni 3I%^<<O/[\\""zM  55`Al>y+NEH\ HMu ӻE_'mc#f(`7zW Ddn F_KKB/3h^G KsA~#ttlQ1er:b;l.t*[M}P}a`]Pԏ@i4O?${[y) _fTm i0OF<'~|K:-#5Ceb6:HH81E ޔv2oҐ2Cg8t-&Ysw%t40ɔpk}TCyti#G=nj `hfSb8:x 0޹N^$}+%(FV^з#vʅAG8_jxqㆯu^1l1TqlDF8X)#&)b*{9hڙOeJ\u: 4D^@ ({l ]\I:e_~+ 8GEQDՓ<emaڬ>zWf_U S@ dK.5N{MĄQRfh\%.S&K3f ^eVPG鴮gL)tχLs-a.b񤉊C]g@ݽ,M K'v8*eaTY/|xCrS/UUWESV7w*ap̔f{BM96ox_ fƂG4O=wqiSDj蜾A2 qIK4 ,@CʕV.BRgIQ1l4vAaj⽾Nj{YDy6,N8}nB:n1Yg5gNn, '(B$b d=-A^L'D H$<iaN[q)9 +]viLr/"l,CQ8Ņ|̓&ؠuɒ~lbWx0u~ 5T| R&V HP%hݕDHͽU:s;*{EŻcȒVNKcD!ndK5@Z-f}fp7e+4F1)sƌnH&R9|r4>;G؜_IM{Q@BkDFIݿ.n({;lmlZ.Z>QŜ:6f$8)3E4fn7}ZPژS"E[ C~6l5Ye40KoSKQThgUʓm.0ɨCǦVv!;ʇ]έyoKL1`N!XZi4"?8=(YXaFس |n1Q ¨A٢ivu.&8ʴe4Kp2Ayjqt kZW%Ȟc5? GZCE!Tχ50`oowoK QT!93e!8ivәK!YFS !!*i@J‚yTU(.1Tݳe3}^?|m1O$s_3NusDV7s5i-PE-~"yp"Da LY[0Bs>Nb1N=x [LO<:<>adJ;`gŭ4[S<'4pi^/xkcka-i+Ř J -vnvnַMe#` 168Rαc8~!ֻ%^@]1Yr`PCLNĭ'f<ǎgaq-??7nck%iw:\|H#BcOp fTvnf GCz v8MDZdPu6*,}W?txʾ48,x]t x fL1peE6G҃`\ 66(j a#C' )Y Wy$y E, rα?O9A`v{,-/ ,2,#NۻOI _|%, %MSvwvȲA`~hp%z>y~M&$k!Xkhe [ZZ]& di7GEg>6FmnbCtO9.B`yVo:JȻ3l(I~a 9y6cւ: ~wAb\B!ve^ny|~~)xX_EfDQD4<atڵkCvo~k,-/l621'z<ӬߺI*'~4a/:m70}D "$I͛2lq tύe*t|P]ILxѝYfAF3AN`Vif]Un6RGj^{xeI{.dh,[S9}W#`xL,K4{<֮jmkɘ[7o|ܳeHBis1ͦ7K e8`2qހea‑YB嵅9Yv'ܱH1ְr^G};Q4f *3i~˽Q4]!M0Vƛ VFt;e.‡:%v_)#=H~d \1ֳ̗w:-/s ǎ-v}[jd2G}AL x*nHUj̷~M'VN$\Mqs><$[[5}KTg}}:ftϨ`DD;?qhJm2wc,mn~ 2!'/2]dn>`ina2ןjI BI˥s!iFE3ݘb){uL,|52hKpIǡs&`gyyYXXjaNDeW=NُXopRt~:.锓NO&6/˴;].?4ׯ^ ۹}#X]]ҥK vw7t}a:h(#7F7חWY' Ap]\ruCUWk쮪nz}#<✔!c\̱c8u sGC\l5y=џ_dooI' looOpEڭfu)hnތy,vtv %p"}UN_jK@E2s1|-+t毲rit-!j ;A94&Uv$L;{. j^x7@wS5oˆN\o^G" #ZM?X9ВWE_Od30֎JpyAhyCZp1p,.-Cpx'u󆗎C9>c~CDFqE ŎQT c2̸H֙ aUؙWE)Ҵ1Bץվ8>O0)56q.ʍ)e>Sj=qsrbK 2H(HD%'Јt:z.N0n$W v+n4Rc6ηN`&Jis:'W .qF#1N9Sn8?s#J-R>d2akk c>X>vPŃ]F< 5 GR&l?YcDMiDƗFc;4ayU %LRo`<˜>d(eF62MP v,[t!?8ɇ~4h=ţzaAޘS &J):u$qiSUHܐXME$e\4 +o(3ˉ'eYFة[G`}=Щ.iQ|å"&Or.RͫeĕDhčɄs}@ {_X<:׮O[FHas)UB-T*{(b)bbW1\=b|qOOFL&CdS?11ԽբnEIɵkWv )I>9sY.Ο?2|D^irEoe&7!/Vqd.BHieپMWIgʎ;W4'"&p9x׳ncelo3 Vk,'N77Ǔ?g=z'wK˹Scy^ gI|90R2/{hSH$0LF ssͦh>5][7ܬy8hwڜ>}{K* bmotyM#IRrE!~MMiVVf^ͷA(U˲m^]#Uv|V.i#:#TGn4JAǩd2ۼ}yFD^"O<(3gX)[Jj^6e7ME'g2dd:f22I\pk}Ethj6iZDaXBddY{>}MYcOs9'VNB]x3D2 - IW|Gy$7k a%nQÇ\q2gEbiy'NrIVVV"_t2Lď3<>Q#6cq-_ux$IL&%kpeXU7^ ET0N+ͭk1qިa2ꕥeF4tb~a0 ejXͨarI4L&C_OK4`gnvFܼ\^U~6INqx8z*w%8 :+N&qnW3IC+wY8!IS$ɜs7-s7PRQ]BIJ%hr]SW1X:d5f<q|enGD6ڛnD"<\P4aČcFZg6h6]߾Vx/x@ȣQK2L eZtYFo bqqENrUa8e]QXdm*7IW;G.Ԙ\Xt žs&"5yMHlTffi޲:N̥? s4R˪)c0!|kLS(Ch2'1Ǐ!{{창6Ολ.0\am>l6q7 "WFKhghZ,,,͛7Y]];Hx>}?@-lk4)^b .s[ιz,9G;"HUZzqRfʓ !<4zL,O)kDT%a;(ʪ3>bOHa:*2K32s YΫ_j.]T&}I٤hX[O-OusPcm(8v8ɘ<Ç~SNk/'_Y31diPu}a'1ɴbj1jqq} x$InIFPXÂl+rDJW^Bjb0l,^jƘ<`bIpX"0 /Yˋ-mK#ᣨK xSI׺Rʁ5@K5 ꧬ6-N>C<}%T_s{ȭx._=$A^]5-hmZoN$I[Uq}b?Ԡo0E/Or$pE޾@C -Gy=zߧD N&c$hb$yH i>nq)N077 * ]W}_-_ٴ)-<~b<si>7o`ii|+졢>2ڗ)|b{1Ty}ɑ3w~w,u]wbS+!c۶O! Etw2J?bjAդ ƢnfE~$jW^-6q;yk_ h)VA *D"hȕ**ma~~!6h4"?^dG9^[iq D~>*#)]< ]@pfǔ*A7&KKKlll2Cf2$R Sx 3*vj*9,tR2gG$|iI䵯{o|>CCT|::ՙ#@ *Y)GxOSFqbq2c}!($>\'K^+ %w"52o\ie,V˿e!ь^k>x׻~ \Ȅ5ΔPtyeLaQTD(I+LJh":ۛLs@ҩ׼|ʧ~j7O* D^>~3Jg WF;>#N9 ̣~5-_g X Ti{QA&M8Y9no~2Eft\jlHr%32#H0UB!e!7֑RH-4]npx:-#kw]zOη( 7*bR#~Q8YI0k[G\d@2OZk2L*$O[6zK`-Ls# InኩTh>d{Vo̲lfmGz|kDQX~,sy`!ϳbda!lZYt-FsJѠ77>e{ennGDo+`ș,ž3@a,mAH9Ed0hPޫ(zgRsL^2p_l4֒4 s8,;ׯC5ם8]{! #S'42#QabDD iU^oOgP:<_>Uv5ô摸:5s>>H^>aec P6ESڠ ikQ٬3Zy[TvMQu S?9~${snsOF[WUVT`VjLP\sAk 3aY&?OT >oe 3Au.!pv_|c 4T3wWZ\?_ś@"j QCGռel閪ιVuN}c:7o۾ez y~s3%ˠ=]aks[7oyĥW]sTRM--2[XfRV!Da0@.Jk u[__U;قvd=|w}7.salj݊<=gv!nqxg#P^ N0UR$^*$QZޟR?0Ĭȡj9 (nG, RU}J_9܇z_EvG;ƉDa}gX3Al =d|;hvk7f>_Զ3@0y*n:fAAxW`RQhZ0Uei35%sjI)R՟wN >6)2w}0k??oo4g ,%MjieSBA۪u][DSZg=g:x c[ #UQCu%0c0#: ۰,fe_ގ[h8ܝe_/*_0|?>pY:;T-jw t;Ξ=[ǩ G>D*OuyaUd=zJF%@/vǼ%!9Yp'E8ʐ3vo/Y>}z蓲HU?E,I`jʷFk1d"‡gU}$s_g^R ?)poU:w[E<*It8qO`Lk98;G1T3@yQe?7M^OoEU=q$ ^#e7;~F(),f(,R{W{i]!4F/|K w }_ߦw?U̦,f@ iHѨ>2+y_'GHQ~AeF o$I~şQ~cd{)*9锹9ѳ>5FSUܷs Expn/Wd/ |KFya4Q L#Zv>*r~[@aBp a70Y ,q|Wj?%c?L2ߤʟUv "ƛ?LAw-D39>&ެXi=Qsfbϋƛ7}O~'}y뀿eᛣrݕ5^DE#êxDprJN |gE H/K/9ߢʹuV?ཽ|q 혠{"샼G^|W}E9>n /~G,1UEeL53j*FaĻד~ORy["A9'k"}/B_пʷKul|gE1y9E{f]I^ 0fF|7-5y1f9}WE=> 9xeF#f368ׯ(ckk+̈́ᎈ~S9b70mo"N7Awuu48s}׼K/  l`Q+֚l /M25HރQRצS"!Teb$տr-Krl P??v5j܉FX TA ?Jf7O&_i? G<"ϋ,"k_r/Kv sQ_n޶pjSuyWF#VWo0 pYV /궀 HD>("?+F~шa~G|+?#vǎ-NhKagAMA asRGB cHRMz&u0`:pQ<bKGD pHYsgRU-IDATxweY}{~nG2,ɒmɆm -@ |KB J6J BfIZkvTɞϙ{=%ccc( j"h% tS)VJV}Ec̢Jf̲ɲEc̒f7&kck1 k-Z$I6\؋|GZ-;;ZE$P)Z7RTOiSJsJyԼVj)JZwRMTC)HVk1~_$kǬzf9%b >e(IMQh*"TSiVJVSJiRJyRo=TGiRiJ ݴRHuqj-oga Z1a,~9zsqd=_TCi)+TQ(JDv͉o91w:BJ*!9z a е4J ZiD Ńx0\'%~CS'5?Z+x@6]IVҺ!{Tsrbv=JIBЎR)UTuxՈ1|(< tăC>+!`-XkJ)9 dYh={ok_:LAG:%cVkj-Fa4\RulW+VJ7 _y6486CG<lX?=|Ph,q(u7|]tN(c y(UDyZO`uCi2hJ}GGr5Oør/'r=)uDY\t0I}~0N3 o=+k;oMk#@V=/ /AQVEj,ݟUjr P<.ldQOwlL_8O+%gL6wkZfk.^$ J ԋO)W,HA||{ixcs~)gl[+X`'T)wBj-=b~ Vrw5ۂmZ tE/PZyF#\W4ZdYŋFhIb+jt*TMܗF(d;$+oz}tUH(B$E wkQ"hE<qLD\" }._=Z ƒH"B4 n;DWwU(Sd*V=WQ uqU H` 5# GgLg.D/(x>= !OY˜(!Pon? 55锋.$1"I ]PU`^c])uݢ#8ic€\PV("N(@eOw)^ۥP** +EKdɐq{tq$%In̷[,!s_/>%k3Ϥ"Zi}? j/N\zMD)1;;X ( #q3Aۥ4x-#8\NL[#naՎ!Wy[JB֍jT ɱW}xL45t'lMRL> 9r+_q !]kU CB=g0̉y8q, C/]*H0 Ѫ,)U"r mA)zV"=j_ >" fG돊/{g[śI R$4TbS]#YӃ5vN\d?QIV=Zvy?"—X~Qns#u8PJ*s6FaH\xtlo3q~%좃PR4Mݠ+6zg`!qwgs X+6#L$$GᔑČIlENA#K6/X˓LD 6t iqix? QcAU"GѶo`yrRzXv j> K?+@/_fooQ=v]%q %Jib8tZ꼑Ft`ȕolg0!O&ehd1Ic42VS&`?Hؿr2:H2`jWwQ?">Y?H& rj7'&َf?{.{L9{ #Qyk_;=[ds?h˲ E5 L6ױƢyDWo>jzD(ӊ$Ye"dRUݛna%c32IHULMj.w *eڄ^dL Y>+'w԰q~߿6&b n: xx9,Bft{R`#T^{``J7q)jZ΃3*fp4 d֘N'Q:p mKhwڬHSijTP,O ))$$$0&L #5 r0IIy^yQ.H0ܛ.ee@љhu4`l'dI(!Oȃ9-t:ZS7= 0h0bL` 0Fm)l:,J\ )_)[3`kc2@TUyWR(⦬OWG.[5y]MLinc5e`L 6R{ QF2HG3bJ$CAo{{_2R HtzÕ)6B @$|죛}u 6U^XD%m9mZعo^k\? C-c3Ϝs"@^%rViivyaStQZW&3'&634)){ ) %ddfD,}7KaBD,JKrpm|kob4e4D{qN⩏NeӋ=/tBu3d_;p.+s! )M ii}B&HQyTQlh|Aj;g-֫֘ Oc]Kf2f͍O\2~QԘ)\:;i[,`1i`E:G&,p{F)qF:u֭TՐ NG:4.h06ʲRz{}Nߵw bI/F@AT)V[s\_!ucm/A wvq ҄ M)|j8h1*7eV g ԲQaX:Xkiی#~)qL\x`@hl>wWs5(+I(Ax;h xzQZ[j|BH!XkL3vwb9N66 fWYRt;!2 1SX|rF@&sq3<}-Wx"6/kyO&)~VkpE}G9YV|XJqkW? [^0M0F⩧bo:>O&dJ7ks;`aaF6\yN308+\ue-z#ujŬK8jT$sdJפyckc=j߲$<+\A+;>,wџhrM`} /c6k'mNb%~MHc7c4'tY)0-_Ug_hE a"27i#Z&O=kkWְ˗RCT2eG9B>NdnGۣCdlrK {]~A>_qwd:[«.Ӗ~|hy=&3MFi$vY)!8q@Jk~f6xg fb&iFf㔽kM0a&AI1|y{Y@iWX׵tK/"t:]677xHӌx:҅qLE"?~bu2cj1 dځRVTi*!l4〨pH 7qori}/ ,(VpCGiaڈ)-$v^d@3|E"+@5KΑ FXa6bu. 84c\oӝ{^G>[(U'Xk270NxGdiʕKa9,dssm!Jj!ӂՂ`8((5V kmZKgmgQK0Pa F+bȄat@2?3lhtC+KzcFjSK\;zGkkc?IBka\H{iINMXޭ'Y<[lf)M +NQȽ>͛>Ucy&WW=cy#WLX<LҘ]'? MVp.ucMZlY@Y=n4M?(k^) F{7O ljT5ze)նy鴄<ÈR3u^?3cC6/1) I%lwlhwZ՛tBqઁMgx]?bTzBKxȕgv9yE#i ac-fgmBg~mܵQ I[+,gff>\]6mzAEȡsRn NfIBYU(TBzctWhDUN;֯ PqFҖ vc,vDX`!eO3wԲu7WMD1LA袏.a#i=Go ufRwټW*FE.|4^Jv$"O<=osm*i}|hu D9 {"#MZ&n^G嶳gi6h+gg݌nyoh:(xy:ltC}˄YLX+ ٥KjFk-.N0u Enss|}ec.L)/A#n{׿GΓ4E˨C 0ҥK|tc[`o-,=w(6vvCۡni6DQDKKK.Z2%I^-}щstCFSC@Q : 8}/y GWh6! A;XPtwiB-tZ,uۘ66TSkVZ\69o 9[W''-Uhw#VOtw\We͡~s> =akͧ7thw:BA0h6Z-Z6vfE Lf1{{Gc;;raV ]p`@I\o՘7X a3_t zmt0A<,4B{+4Loo/.MTӱ|O|vFQT|4NLSxx8b<1N=JJEPIB$~ f@"Ĝ!7٠]ekՈXP710ksk-Nq ,OLˆ.ʛ^pV?ӗWL<lnlv:ݞs5|EֻJW\҅ өuz B_gF@hLƿ_ EV Qk.s&\}4 أ)6qu|b_R*WγtSOԽf<%n;s |\/E3'p:] Q`PE o[W7yσORj#=گSJ?-‡64M7{~!o&'Kބ>}ꦷM4.j1DE)`0 I.U\-*0 /?caox:%ZX@7BRhP".V{0'QEsV"LClU'v"#Z\'.s꥖~JqLӷ.p ˭#V(fYPF U6M`<(zIl45{&G[o0x.ZoYXc/qc\.Ʉ'N07?t2uBY^Yq'x!bJK/q~f-!NJI̫|v[X{cw% XH]hz;9SHxezVIm;uP5F^ANwJE[g N`J#aT4D i P*yl4 O7sFҔ8In /nZkZ=kω豈*C<3rIi02Cλf~a'xLd[ ;;;|'[il*}0|g a0iR'^ȭ/$lEEm5b Ο2["!8/}W8#J])R H3m(& 5$"/sm>nfE4a1jA<)7Qh/'i(Fֲ|aDkA|:ᐛo% ip)ss|XzW8uoxQ$IKSӼI| p⦛_t-w hUyG|:(Jw&;gA) r'8q>bȴK}ǡ0i4DYR[5h;t]W6E"?պ>.q6I +˛z]}}/%fQro^YEV7s)[VVWQ"$ekXY=BF a5?_HfWv'LSr@υ2A8`"}1sR#\y_k`PSRF7VQ`⠧8*-aRƚ& s󬬬f Q5YZ  sey ג7Fā9' D%{z%.T {RJ*jET",e>tQ\5J·WJivi;[-7pKQDf iӰ~Ρ;-die@VK:b k.~2yBD$/,AQ\]VP΋P3~9)!X5J Q KuN[ bmEa#c&aąջKKt<<{xIҔVMEgQUA@LX/ޗbm5Il4{b*4ڰ֦bmXLXq MNP2`Kq1ͦWs,,.Wᑇ3pә3DQ@:N]<8ߚ %_&{.%q刷 {h!"bɈuBBFb3uJFAӡl6IS7I'⥋nhd2C s_%1Nf\nYOJ\WE_dYf\TM,&,~ZH!_b<C>0~z2 ń5Ϝan~8W\v677?ȱ ]T%1S *ʖQ !R :} ]Q-}L,ĒR'z٤hۤI{i\ޞʼn˽tr->uΜq JLEp3PHYZ36csz,31梈dP` NKjŭM. xa2õuiC8_*~)|qWj xUbyy@+4+yh68-f)x#':%+TRC} ,%Md4g1M fIӡ5n6=ϟgmm}&1Is;v3gp;z%ew*#熲Qͼ'˲1Jܸ vh]"Eε){0'.]bnn9ͦb .yᏱK?M^VG٬W RTRJy~ފ*D$bq ZcO*@&_l_ PPb8Пj6Q%>?(~A.W(/Շ}a"ukM:(n[լ\ep ɈdDO1&󖷛y@٠pJ)666|2l{}1I`27ǹ۹[YXXp3Yʾӭ1$iZ)>3_yEJ˴c{ auVoyoriP 85`1gY,xd2a88`n~9^,.-#{/oz ( 3BT[Jn@OƀO&1шtD&"F5ffIEn_Y}g9GË| N̙8zve'S]ˍSd'qq]ω i:snY:hoh>+++}tpm17?ϕ˗38u e\MnTR=`%Kb8fwsgu TF4~wc"(d7&!`%yQIndFHҔ$M3ceEsBAjkRdm 7tI(LE.XvJt9XS{f5#ЙZmnqDUQ UпV1O8;4ܤܽ325c}At:l1W+?NN WØ$bVEsm䚋 P:p?( _myl ~W O׫%[Bq:b uċq#Bb{5]r&4n+q5O x+^g`Z;6Q. Majc܀AtxԁH8~sho/?L#0gowvvvZn:sΞe~޹^VUnq5al6h6^{s#+jpW 1&W^ʕ+vmDZ8;q$~8^5440z$iaXmWSh{8YݥG'1Ƙmkf}?C?|ر֎seUj<@l1BG9R(5q㧉*rNI廻;L'vw\dM]D鐙M^sm|VEЋɥE)^rͱP^ ÊQd<駞=źZsNjW[nh ui9\֎#'V4N͸ʧzz̹fHs֞K)_8e.o91b%ixP[I .* tsZ6ǎcuu~>.XJs)TM90}Gfx<ɓϳ2 EZK$APq3(D}fE+}bL! 7ƒYjl2JT@No@5–7L5dЋe:?ə>N" B"KSןnX?|Oc4aq˭psӴ;b R=y-SI.La#xNSnlͮ5ш *~" qJO1VLVlA\D/\L 7,bkl6,..UL ͇z@J!/ɨN1R>D+xr۠O04MzsscS-/.*;3%˲/**% ʠ luVy 0 -Lh<ڗOM~ˉK3y^ş˂hD4Ms4?4oo|Zs,3gg(RNEV Ҩ*O\tUU!k_J)$egkp{>_73uXŢVZrjD_Wo揳W].b75|z6֣UݵfYfY'koyY@/|ӛ J&cRwFQz s3"4jq_:J.& [e>կ˩/`e 2[ft}Ngy>K"okmYVnbTc*.aT@PH[\6Ͳܠ61懍18 ~W]R4Mk4]om5[} Ȥzy&d<{ /̦affZ&VHs tf®ƸلIe TLJZkݮM5yɖ/RZ\{>'p*YN2bŭg߱=hl%םp`jf7Z1)*^4%M3ݻӚ\MEʁ5, v+s;(\rurq?7UPNFx/ +(5j:gܕ[ﱨK.Q *i+h+_{|/!~cLW6mw*q5h)Yf)I' A²5BXn?W(C_Ⲳ9-~(iJE7W+%e)\l-գ75 /B#i AMTl"峅ȮҬf>>`TR}l Zk?k$/c~GFkA@}R*Ȳ*ۍ1T¡@8<[nG}xԚ#o *<ngUvz,Z#2?xIګh*!T@!uL ?=QZs"d+"#$YZ( Ai$I%mp(o\:u'N 7r)Wa:GZkɩ'UAiT_9࿧izE)e3" ?Oy_ " ˲!⽺Oc-Gɓ5{.zj%U*̪+( !o:{)U7&?_3PZ'#g T"_>LOP!rUT%AQXj>52'O*L}A-BVH9{ r9ϨRu Vb;VU+fɟSܰ{O?ZE䋁g-//|O0| RXKԩSEJS2'fZPTYp;8+dXWÍN8>k̟~N Yǩ_ MZekbu7AS(_U7;UcRazBD^*!+Z|RǫRE|!~ g?oƯ^ k[kQӣfƭ$ x6)58~VUsbԚX 3ș _[  R 0¿O۾_xpZ׀h׉g6m'wku,:zhy:oY@3bbFjgS0> ࿚"do׼`N_@Z>JJa|eeFQlfX{YVY?~+@u?Y9gxeNlMkeSs ? Zk ;;^@=7|Qؘ4X\\h\GZv+]rjg[oƷ?sDRƘZZ.wc jݞ1_h6k!\a\J1W P}0eUypks5>yOO=n{XǬLA_ǂxx4v`̅U3j׹eu@fgdA!]r!#mlr!uӬOY}]#LH-d c_q@~l; xLD#G6?|.gu<_%oZXMR̽zT`0Zً:4)Sst1[O 7ӟ99wOo8-6r M888(?%ȳ>k"WE7-\̷~7PK/@DSJݧ|A5Z :8/:nS_?T2̼/""_~W\`/~ _!`ya|AJ|qRy?cJf]sk;X_6[^%|N?3*׿)5lFyӄֵc n Dq;2_%w( nx("ED|p2 &/닱t~gw5oiw:R`iT\ """D /XK/g~XkJonZ0Tf5Q>WvA3 $ [)Dǁۿ/:cLW0p.>4M\zp!WpXµKF"ޕu}w|ۋ49wj7\ZZ^$N?ʕ+!ѹ ;fBQb1b/ v|g~|_sܽvVWڟ&XZZܹgx"0j2_ZǦR?% 64wKSٟ9tTŅz-5ss}ֹtJcf9_g_rw1žcD fw{pӮ677vǎoJW("7ȿUJ}d2NNڋ}/|?mw;4=w%It:r)^v}lmmC(5Z4>R?&?zEeAom6?l6L&\n:˗\W1$J}Z~/|Nwh(N0vwv âԿQJ(uZk??w"QCYFï|r%J=D~U);RKOCwPZPJ;kki3Zۭl2{_Cuh7I/%tEXtdate:create2011-10-13T18:23:37+08:00\^%tEXtdate:modify2011-10-13T18:23:37+08:00-IENDB`sandboxgamemaker-2.7.1+dfsg/linux/sandbox_rpg.png0000664000175000017500000005275311654260376022053 0ustar showardshowardPNG  IHDR>agAMA asRGB cHRMz&u0`:pQ<bKGD pHYsgRTIDATxwdYyϹbWusy^$diSVVuҁ;բjQ)=nW)ՑBԪkSDEOBLuk?>}ו9p:5c-ƘwS_$&5J"8כzT(:T)=DtNJ)S.:3,~*A=t9D*Dc Y1L G=ewg]鿭k,G嗾em[qE/P"wȪFL"kJ(?GJOТ˳:zD5͉7+rV5H{. DTbZg1k 1,#I& p`0`{{y00FL&IB&idfmoo?ޚL>E)πW9g;Ɓ*'b0&_$1,БFa}+I>s-ZGqDZ,c8b cApXp42$'he)iyn o-y;Yuъ19~umn||x%8Jt=d7c<wxD \0~ yz2 \ODUK.SJ@̘(hy AL#ϭqAp9áI34m5ιgE#ˉδhv&:yvXx+_ PcNdZSA:_d=KDY4%MSD$|GXBkA@!ı's,i5ddiJDd9s2'1I$ ib21F W"9fPJq t* e]6I݊6VBeطmC~pJ^gwByQU+S PJG#!Ez>sޟ6&H, NS4#3u޴TnBt2c.X^9M瞃UZMa3*kd'"rI$}gK1ߛ$#ιܞ!'QAJ@ W|˟rP'HIus 6cJ-th_vlhn5 <% F4IxO2꽄xwM Pv xX?O׷?q_Z)@n7}muQꠡ? b? _Tqf _WR `\*=B-]q1"s{fdY4ky jVQSR*PyHE"MHu:R#!NYSXkS? zh7 kQJikߟdZO5}.]9R,3 a;_wGN1W)?'|$TA;wx:TvR~`J*RU.)zt>9G}cDꀨ7z(FCFDYk_''|{V'I¥ <Ƙ̯csD\AsqY1pΝ7}JUA2UP<\RN#Ck}Arњd*˨w:$k1: ~"'|W.Rk 00C:5_y+Y.tXYF upD&e[iXA)|*܌/ΡbzRr2-JaJKyUL"jާiA2Un _׮# i HXuܔ^.I C5s+ wވnTu eIX Õ*WT{8;Ohx˿uy5- 2吝Zp{=z CH& };QݶOpϧ}7c.\_UǡvwᏀAam(BQ$> Qch*> Q/0QZa2_~EUns9 }!?Y(q,DıG=(*'XG$(-AraZaQ2r#ِGDG10}?4B>*K1ӆ^UQ_ ^~*Q#\].J+,ӫC)`awq2'M}79"=CHЁq$ᡨE%s Di Ub] ẵJM 'Dx#k|#|d2)^S Q쉯f ᷹#4Ͱ2ae]y,*׹҄m2g8;9еh r>NwwxuR s^UCg/梨8`c-όJ"ёDg|iSR0M .]1O ³'ܬ,ؓ" =7ְM;9ۨ58VDQZK(ܔ C?ދ{j{̨'}vCM|w o=3@y甈;x @еWAk W6ҡXbɴc`冗ͯz.VL)vs+`i-SΉ3K\%b00 @L B|oDj97Jȷh~|?vVhn!vD,8 eT|y]1hs_P _īS/s<Zq\>HyP(9|qT|Zz RpVwC=`h+E|o?@iVNk%UUǔ:V!\<tOĄ0\G]*|O'i4 RZn9emݴGQU~GpEJ+F!8P\ABaXQkqncByաFj\FXTjX+Gg(]-̞+lxvN z*_#eh9Oo/ۀQ+OT(^PJ @/:nmm"JӪg ?ft뜸 GX4[H)Ns(#|ꯗ6R*b8r>єC * wy _.yzqQrd㩈M<~E{{]Z5e~SZxEeNs 늨RK}^%Tn ``Z5U$0 hqP9TՈ R'3Lsϼ)J"Dz%x(Tܞ͋H? Pە7:$ /'I& :Bm>sFIT9v  e*@!1x/FB@%PJ0F=̪ (UE%SV'qw܁kcŌDIhH*YXm~ga`6sqxqHVCGŋQJ )_lQ8A-8 ]_MTzwR~`ȿ[MuTE` vX{zƅqq$tu^}n[3t");Jp gC7s& ˬK5&?I\aDaD[E>K |Z6Qf GQ\}XKǤYƅh8$0rB,V+z:NY{K]մ3&!TBߋHBiR&qW(ex-ybG7"r>;x>1fw {tK G fxrJkZWy?DrBKC)ݭyTLt]&sh6CN[Հ͓Jh/;IAjYB:0 U"|\ %Y=Xç^3O/•9b/718BI"*o~j$RzܼV" (XA 7eT%Lya~wdw/ 1u5&-ItM&ìVL|SV4/|c}K*6 8w8}M/`s@I8_O V+R+zBw].-$ qVtf?1n-hvB4| 9o|IaMpF!YݻYK'lDьH\vquru2,(▥y^trc7ia2K6]Z3W{: wv)|Ue2"M#f•Iʥa aw2|g^x8u^r zB!OcvnO8q{Ns~Ƹ*FRlʈҘ R$ƺWf,ҫ`#'zJf:.]ZdTq#講E X"£<:[!s}_En>6ڃƟZ j1Q'Y)$ UtU3rPe).܄NbAEu&4]'ZdH}dV{Ngiu>KeV~ZdbHvv O F\yG1NT1>Q vurՌ /^4{\(J>Vzeǡf?ZCE4M}\=^\,RڭNs⃟7+sљnjJ@ .<<etKHC>#3d+M؜d cyǖY/Εj9z v[$@O>uϽulismӊ#' h5wj zcXXiXm׸:=Ȋ?ULd 7h'W,{}h3 tQ.o ̝(~lк+ 5@cssG},H&.]$Mj-72).uqoƟ kQQ=1J mH*VŶ׃x ;~4%KS]f2V5W\LC߃Uk"Icҁ8 E+V/;̍"`kH:%T Rv-E1;}k 6_x:6B΂L GfmQE ތ}Y]xG\E {CC[X+1Υ="3IS=ots>=ηA+`ch44M(e*·tQx3|gG9R0dWw}?hD1 :~z`d 3v_xrܻ#N~7,pm-c ӧNqk(s-&1mk" *X05ՌEs2B |Rz\Y[9e{s3/&:mNp[-y9WբhbJC,6I9mrs̗ܲ^0áMsؑRQ,o^y2G!Z.v_pJiq%;︼;m$cs2ɲI< Y(] !&;x6u|~Gy{}{Z+ ^QBj袢OJ xG`UX7&uz : IHiԱumKeû}7|oΣ虣x-")'8(^z_rǍDqxX%ONU*:s4OG7ck8`sXȆ"3 />yta((sҼuE~m+4h_{Js wFwݩygFCɄhh4d41HI )ܼԻ @e~~/DbdZhe2j3.4费?2VCfO={_dgf%BJYg6SνY1mi/Y9b$}Alom6[\ ~9Õ\|dRLV]9ey#ἤD*B\:ł5}1|$z &i :~GqyYMлPb,4|mghN˺TZ5e^K,tnC|.o{P64Xh4/9JcabP\7[6x2++,.-Ɲ w:^~ xfeh4~[-y瞃>sW&ɉ/}ݞ e=_F'3H\2x+i6l2J@0sooq/RiH}h丵s5Dь" nYGU`U i.^ YvhGQx|h4h98w;ޙ|^>DcwQĵupfs֡Sgv9cloWL9HZL=J %<8WF햆RU J)>Yc`[0v88*EvFLJ+W[6w-:G5ZfddL"qy씥RT;:H YPk|=znVMߓp4=i3LF)u>⿊+ݩ' ox{8h͡uҡ Km.?KiB#L=MC "ߧq*:E( Hvsw.ёqWXX(6=\ ]Ʀ-AOFiBN|aְY(mR*VШ7e+,2D dQ*6gйw6EYʂVxf>"\ +++(bss]&1$z"EQ]pBf2G:"2vw10@EEqh^ssGz^@s`0`{s 5F#t݄rgg]lw<:fRoX\#R],ڷKLDyn`@?;3߲dVCEç*_幵B8cBp$#˹]>_{-i6M k5,.rd:žFY8:9»n6]tV1vҥK˗cB:G#2i4EVcǏ3cq7dUO/ɘk}iP$˔w⪔"MVpqN<ŋyxef<iםssƊ F\zBŐuN۟{' \xqFQQt92x $YIjY޺sWV73N rdplŹnm{ᄇGѲHкAlH)&pi@$ ZilD nOl)Lq~qSC.% P(A^.5ML-29w#Q\͑;ʑ|46 oF1~]DQ4tHr s օ>Pt„֯dcljk5I1(8sty%xh}6ZI] Lٳ:2Obc?&qiH!h'FD(<ѭ95 -:.NzAhkh]) EL+w+jux9ҭHi= &"8,+4X__g0p 7Bo4KQJq):yy!֯\0)[!* I&wx+^N^#4I^0;)"ʱ91ࣻР1 }dA(Zq^_7:qɑyOQ+-LQb3~آY9>9t"#DVghĀ5NVn|tM\ ;W9UFʉ_zR+sy)d8Y>գGFDE@屣3v3 ,312a8l\9>?++,,,Rgҝ?+k>!M}?qZC(֊VkXnT9NYPI7 :$Ū|&R6 A*y5MR 8Հ6Ƥڋ D~`c윴@W _v~2f@Y"/x1{ᰏ/z+G&|w7ܾb3s8['ɛSu.PKe\dU.$|)z~ d4las綀R4 69:YŅO<+Wc4R,,,p nFΞ=Y^^bnnmvzTՊDffJwϋX m ؑuvG(Tܲu^+EW)(*[;)h8dm<ҙA Dkuv; K\~*BvUKڽιj»{n:>pZ 8Jaqc&Ʉ i2|oU)) D\%Ĕj(T:c'LFcј,MqPWDjufZTlgedw{zË~ב#9soǎ .$aaaVIϿ$I*!jY*$Ts{^0^E\s`* s }R$EZj!_?%'JJ~x4rN#nfz2?SPV!O*ʋa|kATu,^Ҕt0 }1Lnic%jh6군 f4ަjc9~8Ge~KV*q42IR>>;︃zVk$ I]E$4YBfrUpΑ^q0](Ms\D l+bNiE0"MTXKAsīeW+l6o6Ia&**cBJ{9&)%4գG0jccnu3;><.;L1%>4=ɲ +YGzVܜ/T^c _2"!k5_o-(Ɛ`V:.go-pxbJu8YKmBV21[Pz$KaTPNz9s =))m?g<Qa,dш#,/jC,e2iN,s,ph4d8z<׉1fNj[~"Z #~\ڢ۸0&Z&YV܋/ƐrDRdJtx^6Ξ9STZ߳֫ ByzK>@%B&ЕNWOM&dCkބHە7.ui"pR"g-9b u7 ثL4MINtȳdLg{{,͘tVnCӡjǑBJzƒu~wfD ڿ/{jDqL0իt|I Pa jT 8#]YZf!pOSG,Or+Aa^yI`wEw5R2qs#ИPNuU:MB\RuL&o8YBJVW}ht0.;;;pYn t]N@ME4u WW*'>׷d&3ZDl6Y\Zb{kkW7)E{.YNeZY5A^oIC8 YKpJu~IbݶnVu߿B:q*\_W@EWwD!_o.sZ$L*L&DZݝ]& XcCll0ư]wŹsT2}8Dz=XGͱsJ M-S6jG28c8qqWB'=zN!J0)ʆ؄Re9O|Qkg)Gu #O&i.RMD5#ELew Xݿ_yaWRYΰ;`TY/-6bDELnQ93@Bp^yݖV!V N< N@\C}P+&7Myыx^"@λhC0-=9/nCk}Ex8&)qNI:;EWOZc%Mܩ k=;ZE`(%>$/ij)]CU:6:ss}'o^EYQXe-LU}>) ΅B%Ė%hNX)smv7 *cE|'}2/PAD)<`+aQsBդ0s$ύe}^\r-LAF#(ʻ: r*J1h^Pڲ1%SYDW}gƙLk^pQMHR`B(AL"vx&nP)J FuD:bL&EPs/~w'cbSŅWK纱 djZCB~ =2$R7?GnQ"W\X wTu /Ѱ0(ڕ-cT*8s$ߜ?nu@-Z¬y<) rW M%SvʵŸ^3ם2Zqv1GR1⚃ ?S^ 99W&j"Gt0(Hf~J C@7U@>$V J3Cֳ,ϫC[韎D=֚H5Tb!'ӜaGe[ty?Ū9ȧ3hꯨ os n߀+ߒ7x>*t5+E}TTYս5ư_ AW 5cYkҷq-OOJɔs%2Bu*.@ng{WVx'FI^GݜVoeNUqoCcFįpaϩQJ1 C|wE,XvT@z]ŅH1&7(jq8 ȏW!;F 877nu' qX"*ž:V * It4~aNNKE>y_ܹK$Ai扊T9YoUm}jܢp~*jgnݽi@{'e~bڊ+HbR[_isלsoqp;n498BN?XHmqMY9,mLFfd)q{xSٯ0??K_r=ְieS꠪xn;پ04|59Kٗs+L&666po)B-Lo]eP5\!\rg=/:-k;o/Ͻ.r8gc/?j5ourDMՠ?)N ;|N83faA;%o//PeMU#Dnx1+=UѝWl=2F\Dj(s=wvZۼ˿uȇ¿KR^j?l6^*r":Ðqd|n ;`uOn*m$Ӣ%vQ2B`F95dưOe1ö󟧈_%X?Ro~ZDc?,5=7ZG 7JC&*{ y -ǃ-KCuc. &9Oz(Րde38bc.r. *c  q7{q1_ ;)?PZLYFܪ]`?Μ=ɓ'}ahQ3RJ2#׹۪}9U•F[w y|WzjfFq~ןt9-O֔RK?bǏ9Vߪu"]\*Q 4?;~ӧOPjֵVo4ޠ 6c 1SO)z @׺ _-po#ŗ}~Lo!"_!J} )ۥ| a ~t gΜ!>ia0 (k,2"sE9gR:wʆѝr̙"RY<3! 0 `溘 ׳QS!4+ao_=?iʰ6~#ιW;0>P 0cDIVӧ|?0+`*Ոae W B瞵ާ R`տ?~)OR s|sH 2x]Ǭ N',:Mι=JQqq?8ijAp(8 shğgoUA} 1#;x ?0r;ܭm!rb ]VWWS]rسj&\UyS&wU+q_5_S:S  1/~9w!4 YfXZZѨϸb9'R;Ig 4AVR<~ڃ;\y,(e8ajG_j~3?7~.:hp./m6E; i6[4 DC׽P??}DxoyOQd|7~ӵg~F99ת5/9x1ON.;]d"nFO3@+Oђl&t>V^`6:疪a2?[t1~iߞf3_\ꉮ@$"C=}7>Su<ȏ_h:W>*:gLFoh"z]}C9+xHxoc.[%}Jg ~ VJWZZ 5]I8u8!?-")o-L.Sv<ٟ%D4f/V"?+kX P3j Ykr^1 g#Z [D"Jmk-L/Sz<ٟEܢzFw򪪂\)loo CJCTi[( 3 ӂ""KD~[D]O6ogcY/jh~c\V;s9LO^#"u΍g?[K~?㜛Z}CnXV+l4a2\8;_Q/"gl/v<_%HG_j~hqq\BTnf2Cf2!kkW6i8ӷPDFD$"("O8g{i?DQjOt;(TcX[[cww,˦oBo(V"o%Zsl/3v|o:~VGy|dA)=.\`{k$I?xcS@}o\n+o_73|wg{ AItu;֚.W^…lnn2J\Q*iuv]lv|'1i`2XoԿmNg MS666v^'sM7gooJJ͢ԛ{dНo/[}֏c?So_ϿL[K{g0n7>sOlnmH*EJwVϲlr 5_lq)/eYT^h_h6?Y_?~/R(%C)sd}پ+o`<K8T;;+>]_)n䷕RS)}9k_} ʯ:q#"Ks"]|nR&JQ)yK\]5q?w_~O^z4KIk'Vks<C?e:AN0x%%tEXtdate:create2011-10-13T18:23:38+08:00.J%tEXtdate:modify2011-10-13T18:23:38+08:00ۆIENDB`sandboxgamemaker-2.7.1+dfsg/linux/Sandbox_RPG.desktop0000664000175000017500000000027011654260376022523 0ustar showardshoward[Desktop Entry] Comment=RolePlaying Game GenericName=Sandbox RPG Name=Sandbox RPG Icon=sandbox_rpg Exec=sandbox -grpg Type=Application Categories=Applications;Game; StartupNotify=falsesandboxgamemaker-2.7.1+dfsg/linux/sandbox_SSP.desktop0000664000175000017500000000030111654260376022573 0ustar showardshoward[Desktop Entry] Comment=Side Scrolling Platformer GenericName=Sandbox SSP Name=Sandbox SSP Icon=sandbox_ssp Exec=sandbox -gssp Type=Application Categories=Applications;Game; StartupNotify=falsesandboxgamemaker-2.7.1+dfsg/linux/Sandbox_FPS.desktop0000664000175000017500000000027511654260376022530 0ustar showardshoward[Desktop Entry] Comment=First Person Shooter GenericName=Sandbox FPS Name=Sandbox FPS Icon=sandbox_fps Exec=sandbox -gfps Type=Application Categories=Applications;Game; StartupNotify=false sandboxgamemaker-2.7.1+dfsg/launcher0000664000175000017500000042016011374237464017414 0ustar showardshowardELF44 (444  TTT   #@@hhhDDPtd__QtdRtdll/lib/ld-linux.so.2GNUGNU>qcUoS%%г]|`0)<L#0!"VAnK(U(wE3RlL}B=vWrvTb]a_OG% =Z4fs_46TY;D[Mer-.RQAmpeg"I`,5-6d9N@+OMc?'k7iF%jH5>+Dg&aF2\9:d*7W* jXt k <#{ow)xqx$$|/VSX~yP/IJJGiy1& z>?!28'nBCU ZComuK l3Ehu^ Q,S [{:P p.Y;sb1qHc8^t zN}~h \@ff@ / L H Pv"_BAB"DEP@AQdD A<$"UNra"00>R@28 , RF>" HJL$5RD 4X (@@-4Q$CXx p,1ABmbc'"i NB,6 @BXDJ3*@PDx"jN[[CAT,5쌰$-< ҩY&BsvguCpˆceC55ep+muIF;TQ=1ӾoH6NafyIk&Y!l. 7~h1oY~[R=NRjE]t{94ʿ. Ym$Y˾7վ+|vd.}UgCUHvzX˷WCTyBV *Na}l;HRg3P`䫣u)N{S%Ѓvcũ(GsoA'1ƙV$ߒLC۳j|rBˆj1e6ܢ>]S7͵s)ݿm^ݸhZb g~LYgCc&'U55ȁ (@CE1C>NjDZ#B3qM> Nbn9`lP(MړtF>E\"j{]{@7Y"a-%B{9Pu)&+b~&ddNyP} aXYf}`H.ڗd2+(O* >ئ?#vz c԰po'+­\xʈi)0.=A\&R-Fdi e NXme4 0J˅ 3GI ,&6ڂbxZޗ$,t_aa2[u`S2ckVa:BQKgRnφ/o}.|%N[ WMN$ O|w{edm8Cvb"beȠoIܤ5Ws w'BqK }U[%vi̶T;j9Y)[jraGh9E/U"qXh{Y1ȳM:3j_Ueg,VWj64u+2R#bT+Jf\+Գ@Q6)PiWX1x%Mzut$` p jԷO mE\V(*9N떏;"uK:.]D"|rP}:`br7Xx~ n@Aej9Եj楋Tl6xxƆ@',S5VzPԃ 鳎˻ re"z$8y"}m]'[[t?u FO,#h1ąT(EL+,__d6{<|xI2Sc<&E?%9QzVd"RqS<3{rv9ؿám6ړlbif,;JО`o CQε͟}? cJ\gc+n V#A6.Tŏ$=;P#i?ec7y>x%5<,#a?<*<6 (.J8*4 :=7|9D-8u2>m"%<J>KO:= <;~:?. x8<5;3">;,[5f)<T?{?:=_*7#$|7'9D;90N91=B#>@9:$63N%.:f0&/F+4a989M/"EG"Y ! 4"~  " "8P!.p R4706c[`",]$"o$$ !7` +% "@!Z$!+ "$L*@,!> -* .0" ".O "i# *"m1[!0. !03,!H"v@"80"p ]<@`/#P  "4?0 #"+5  "@ P)"pF"hp " Y!2 ' 3 ,p^; "J@ 3""{*M&""P>,!+P&"&D0=Pi#P C'0% p 08 P\P"J`"% 0@p& "" "4&""= M#p)>@,!<d50?|!* 3&" ,!< "/d"\ "x)"; 0 970"9!# d!/P{` 5  <" &"~$~ #  j&2 " &  ,! "g(8-d! (2@!@ " \,<\ !;5 ,!3`s T \!&Y!   "., " ! A" `\@ i3  "@/`x ";" "=r"O" (@ (.@!J"#  "m8> -p*p+ :!B "7,(14"9!!p!7"E?d(9!5 P3"a";P8(p% " !:, P/"4@ !@Z!- !p-~!9p8D !Ȫ0j"p@ "w6 Y"f #"'- )P pP5<a !i.t/ p "">85' $@)@`"P?|:1 ,= "p n9!% "@"I2 P;" _ $" 9!+'p "&1"$6`U=P4(!.,!  " / X /")` "P0 `&""S9p!x`";0g"29 !P >"y7P 1`%$=3 ' 1:,`L&0 @90!@"c"1`Y9@ !0&"|@&1 @" <!w"mp"X`9"d"  p9! #"~/ @">@) 0Z!;"{P !w'U'X20`y0t.0 3!/"=  "#   "|""s"6 `' ,4`  %@Xp"b: 840 \60C(g "?"]'@ < 9 ! $Z !libwx_gtk2u_richtext-2.8.so.0__gmon_start___Jv_RegisterClasses_ZN13wxTransform2DD1Ev_ZNK12wxWindowBase9IsEnabledEv_ZN12wxButtonBase15SetImageMarginsEii_ZNK8wxWindow21IsTransparentForMouseEv_ZN12wxWindowBase16DissociateHandleEv_ZN14wxComboBoxBaseD1Ev_ZN12wxWindowBase31GetMainWindowOfCompositeControlEv_ZNK12wxWindowBase20ShouldInheritColoursEv_ZN12wxWindowBase24HasTransparentBackgroundEv_ZNK19wxTopLevelWindowGTK8GetTitleEv_ZN9wxControlD2Ev_ZNK12wxWindowBase10GetMaxSizeEv_ZTV17wxStringTokenizer_init_ZTS13wxTransform2D_ZN12wxButtonBase10SetDefaultEv_ZN12wxObjectList10CreateNodeEP10wxNodeBaseS1_PvRK9wxListKey_ZN12wxWindowBase12SetSizeHintsEiiiiii_ZNK12wxWindowBase7GetNameEv_ZNK12wxWindowBase24AcceptsFocusFromKeyboardEv_ZNK12wxButtonBase20ShouldInheritColoursEv_ZN8wxWindow15FixUpMouseEventEP10_GtkWidgetRiS2__ZN8wxThread6OnExitEv_ZNK24wxItemContainerImmutable10FindStringERK8wxStringb_ZN12wxButtonBaseD0Ev_ZN12wxWindowBase14SetTransparentEh_ZNK13wxTransform2D16InverseTransformERK12wxPoint2DInt_ZNK13wxTransform2D16InverseTransformERK11wxRect2DInt_ZTI12wxButtonBase_ZNK12wxWindowBase18GetBestVirtualSizeEv_ZN12wxButtonBaseD1Ev_ZNK9wxControl15UseGTKStyleBaseEv_ZTI20wxThreadHelperThread_ZNK8wxWindow8GetLabelEv_ZN12wxWindowBase12GetValidatorEv_ZTS17wxStringTokenizer_ZNK14wxComboBoxBase19GetCurrentSelectionEv_ZNK13wxTransform2D9TransformEP11wxRect2DInt_ZNK12wxWindowBase8IsFrozenEv_ZNK12wxWindowBase27GetWindowSizeForVirtualSizeERK6wxSize_ZNK12wxWindowBase20GetDefaultAttributesEv_ZTS20wxThreadHelperThread_ZN20wxThreadHelperThread5EntryEv_fini_ZN17wxStringTokenizerD0Ev_ZN12wxWindowBase6FreezeEv_ZNK12wxWindowBase16HasMultiplePagesEv_ZTV12wxObjectList_ZTI14wxComboBoxBase_ZNK20wxTopLevelWindowBase9IsVisibleEv_ZN12wxObjectListD0Ev_ZTV12wxButtonBase_ZNK19wxTopLevelWindowGTK12IsFullScreenEv_ZN12wxWindowBase10SetMaxSizeERK6wxSize_ZN8wxWindow14OnParentEnableEb_ZNK12wxWindowBase7IsShownEv_ZN17wxStringTokenizerD1Ev_ZNK19wxTopLevelWindowGTK9IsGrabbedEv_ZN12wxWindowBase9PrepareDCER4wxDC_ZN12wxObjectListD1Ev_ZNK12wxWindowBase10HasCaptureEv_ZN12wxWindowBase7SetNameERK8wxString_ZN8wxWindow8SetLabelERK8wxString_ZTS14wxComboBoxBase_ZNK12wxWindowBase10GetMinSizeEv_ZN12wxWindowBase4ThawEv_ZTV13wxTransform2D_ZNK8wxWindow9GetHandleEv_ZN12wxWindowBase15SetThemeEnabledEb_ZNK20wxTopLevelWindowBase20ShouldPreventAppExitEv_ZNK13wxTransform2D9TransformERK12wxPoint2DInt_ZNK20wxTopLevelWindowBase10IsTopLevelEv_ZNK8wxWindow13IsRadioButtonEv_ZNK13wxTransform2D9TransformERK11wxRect2DInt_ZN14wxComboBoxBase20SetInsertionPointEndEv_ZTS12wxObjectList_ZTI17wxStringTokenizer_ZTS12wxButtonBase_ZN12wxButtonBase13SetImageLabelERK8wxBitmap_ZTV14wxComboBoxBase_ZN12wxWindowBase15AssociateHandleEP10_GtkWidget_ZTI13wxTransform2D_ZTV20wxThreadHelperThread_ZNK12wxWindowBase15GetThemeEnabledEv_ZN12wxWindowBase18SetInitialBestSizeERK6wxSize_ZN12wxWindowBase19SetAcceleratorTableERK18wxAcceleratorTable_ZN14wxCommandEventD1Ev_ZN20wxThreadHelperThreadD0Ev_ZNK12wxWindowBase18GetWindowStyleFlagEv_ZNK13wxTransform2D16InverseTransformEP11wxRect2DInt_ZN14wxComboBoxBase6RemoveEll_ZNK20wxTopLevelWindowBase19DoGetScreenPositionEPiS0__ZNK12wxWindowBase13GetDropTargetEv_ZTI12wxObjectList_ZN20wxThreadHelperThreadD1Ev_ZN12wxWindowBase17CanSetTransparentEv_ZN13wxTransform2DD0Ev_ZN12wxWindowBase15SetFocusFromKbdEv_ZNK12wxWindowBase18GetBackgroundStyleEv_ZN14wxComboBoxBaseD0Ev_ZNK12wxObjectList4FindERK9wxListKey_ZN12wxWindowBase13SetExtraStyleEl_ZN12wxWindowBase10SetMinSizeERK6wxSize_ZN8wxStringD1Evlibwx_gtk2u_aui-2.8.so.0_ZNK7wxFrame19GetClientAreaOriginEv_ZNK11wxFrameBase10GetToolBarEv_ZNK11wxFrameBase10GetMenuBarEv_ZN11wxFrameBase15PositionToolBarEv_ZN11wxFrameBase15PositionMenuBarEv_ZN12wxEvtHandler12TryValidatorER7wxEvent_ZNK11wxFrameBase12GetStatusBarEvlibwx_gtk2u_xrc-2.8.so.0libwx_gtk2u_qa-2.8.so.0libwx_gtk2u_html-2.8.so.0_ZN7wxImageD1Evlibwx_gtk2u_adv-2.8.so.0libwx_gtk2u_core-2.8.so.0_ZNK8wxBitmap14ConvertToImageEv_ZN12wxWindowBase10InitDialogEv_ZNK12wxWindowBase19DoGetScreenPositionEPiS0__ZN11wxFrameBase13SendSizeEventEv_ZN8wxWindow12ScrollWindowEiiPK6wxRect_ZNK19wxTopLevelWindowGTK11IsMaximizedEv_ZN13wxControlBase7CommandER14wxCommandEvent_ZN8wxWindow18SetLayoutDirectionE17wxLayoutDirection_ZN19wxTopLevelWindowGTK8SetTitleERK8wxString_ZN12wxWindowBase17InheritAttributesEv_ZNK7wxFrame15DoGetClientSizeEPiS0__ZNK8wxWindow16IsDoubleBufferedEv_ZNK8wxWindow14GetScrollRangeEi_ZN7wxFrame13AttachMenuBarEP9wxMenuBar_ZNK12wxWindowBase13GetEventTableEv_ZNK12wxWindowBase9DoHitTestEii_ZNK8wxWindow11DoIsExposedEiiii_ZN19wxTopLevelWindowGTK10RemoveGrabEv_ZN8wxWindow11ScrollLinesEiwxNullIcon_ZN7wxFrame15DoSetClientSizeEii_ZN8wxWindow14DoReleaseMouseEv_ZN9wxAppBase4ExitEv_ZN7wxImage8LoadFileERK8wxStringli_ZN12wxWindowBase20TransferDataToWindowEv_ZNK12wxWindowBase17GetEventHashTableEv_ZN20wxTopLevelWindowBase16DoUpdateWindowUIER15wxUpdateUIEvent_ZN19wxTopLevelWindowGTK4ShowEb_ZNK8wxWindow12AcceptsFocusEv_ZN8wxWindow19SetBackgroundColourERK8wxColour_ZN12wxWindowBase8SetSizerEP7wxSizerb_ZN8wxBitmapC1EPKPKc_ZNK12wxWindowBase16DoGetVirtualSizeEv_ZNK8wxWindow13DoGetPositionEPiS0__ZNK8wxWindow9DoGetSizeEPiS0__ZN19wxTopLevelWindowGTK7RestoreEv_ZTV8wxButton_ZN13wxControlBaseD2Ev_ZN19wxTopLevelWindowGTK8MaximizeEb_ZN8wxWindow16GetConnectWidgetEv_ZNK9wxControl12GetClassInfoEv_ZN5wxApp9OnInitGuiEv_ZN14wxImageHandlerD2Ev_ZN5wxAppC2Ev_ZNK12wxWindowBase23GetClientSizeConstraintEPiS0__ZTI7wxFrame_ZN12wxWindowBase12LayoutPhase1EPi_ZN7wxFrame13CreateToolBarEliRK8wxStringwxEVT_COMMAND_BUTTON_CLICKED_ZN8wxWindow12DoMoveWindowEiiii_ZN8wxWindow9DoSetSizeEiiiii_ZN19wxTopLevelWindowGTK17CanSetTransparentEv_ZN19wxTopLevelWindowGTK14DoSetSizeHintsEiiiiii_ZN8wxWindow7SetFontERK6wxFontwxDefaultValidator_ZN8wxWindow14DoCaptureMouseEv_ZN9wxAppBase5OnRunEv_ZN9wxAppBase21OnExceptionInMainLoopEv_ZN8wxWindow11WarpPointerEii_ZTV14wxCommandEvent_ZN7wxFrame9GtkOnSizeEv_ZNK9wxAppBase8IsActiveEvwxEVT_COMMAND_TEXT_UPDATED_ZNK9wxControl13DoGetBestSizeEvwxNullBitmap_ZNK8wxWindow15GTKProcessEventER7wxEvent_ZN8wxWindow11ScrollPagesEi_ZN19wxTopLevelWindowGTK8SetShapeERK8wxRegion_ZN11wxFrameBase13sm_eventTableE_ZN8wxWindow13SetDropTargetEP12wxDropTarget_ZNK12wxWindowBase10IsTopLevelEv_ZN12wxAppConsole20OnUnhandledExceptionEv_ZN12wxWindowBase18DoSetWindowVariantE15wxWindowVariant_ZN9wxAppBase7PendingEv_ZN22wxSystemSettingsNative9GetMetricE14wxSystemMetricP8wxWindow_ZNK19wxTopLevelWindowGTK10IsIconizedEv_ZN11wxFrameBase15OnCreateToolBarEliRK8wxString_ZN5wxApp10WakeUpIdleEv_ZNK8wxWindow13GetCharHeightEv_ZN7wxImage10AddHandlerEP14wxImageHandler_ZNK7wxImage5ScaleEiii_ZN9wxControl14OnInternalIdleEv_ZN12wxWindowBase25GetClassDefaultAttributesE15wxWindowVariant_ZN7wxPanel6CreateEP8wxWindowiRK7wxPointRK6wxSizelRK8wxString_ZN19wxTopLevelWindowGTK14ShowFullScreenEblwxStaticBoxNameStr_ZN8wxWindow6UpdateEv_ZN9wxControlC2Ev_ZN8wxWindow15ClearBackgroundEv_ZN5wxApp5YieldEb_ZN7wxFrame12ms_classInfoE_ZTV12wxPNGHandler_ZNK9wxControl20GetDefaultAttributesEv_ZN9wxAppBase13OnInitCmdLineER15wxCmdLineParser_ZN18wxControlContainerC1EP8wxWindow_ZN8wxWindow16DoMoveInTabOrderEPS_N12wxWindowBase8MoveKindE_ZN7wxFrameD2Ev_ZN8wxWindow7DestroyEv_ZN7wxFrame13DetachMenuBarEv_ZNK8wxWindow15DoGetClientSizeEPiS0__ZN8wxWindow6EnableEb_ZNK8wxWindow13GetTextExtentERK8wxStringPiS3_S3_S3_PK6wxFont_ZN12wxWindowBase14DoSetSizeHintsEiiiiii_ZN12wxWindowBase9MakeModalEb_ZTI5wxApp_ZTV14wxImageHandlerwxNotebookNameStr_ZN12wxWindowBase21ConvertDialogToPixelsERK7wxPoint_ZN12wxWindowBase19SetVirtualSizeHintsEiiii_ZN12wxWindowBase12TryValidatorER7wxEvent_ZN12wxWindowBase14MoveConstraintEii_ZNK12wxWindowBase16GetDefaultBorderEv_ZNK8wxWindow14GetScrollThumbEi_ZN8wxWindow12SetScrollPosEiib_ZN8wxButton6CreateEP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelRK11wxValidatorS4__ZN9wxAppBase8DispatchEv_ZN7wxFrame14OnInternalIdleEv_ZNK8wxWindow12GetScrollPosEi_ZN8wxWindow7RefreshEbPK6wxRect_ZN11wxFrameBaseC2Ev_ZNK8wxWindow11DoIsExposedEii_ZN20wxTopLevelWindowBase10SetMaxSizeERK6wxSize_ZN19wxTopLevelWindowGTK18SetWindowStyleFlagEl_ZN12wxWindowBase14UpdateWindowUIEl_ZNK12wxWindowBase18GetHelpTextAtPointERK7wxPointN11wxHelpEvent6OriginE_ZN8wxWindow5RaiseEv_ZN12wxWindowBase10GetCaptureEv_ZN8wxWindow15DoSetClientSizeEii_ZTV13wxJPEGHandlerwxButtonNameStr_ZNK20wxTopLevelWindowBase16DoClientToScreenEPiS0__ZNK8wxWindow22GTKWidgetNeedsMnemonicEv_ZN19wxTopLevelWindowGTK7IconizeEb_ZN9wxAppBase8MainLoopEv_ZN12wxAppConsole10CallOnInitEv_ZN12wxWindowBase9FitInsideEv_ZN19wxTopLevelWindowGTK5RaiseEv_ZN9wxAppBase11ProcessIdleEv_ZN8wxWindow8ReparentEP12wxWindowBasewxPanelNameStr_ZN8wxWindow11DoPopupMenuEP6wxMenuii_ZN10wxNotebookC1EP8wxWindowiRK7wxPointRK6wxSizelRK8wxString_ZTV7wxImage_ZN7wxFrame17PositionStatusBarEv_ZTI15wxItemContainer_ZN11wxRect2DIntaSERKS__ZNK8wxWindow16DoClientToScreenEPiS0__ZN7wxImage7DestroyEv_ZN5wxAppD2Ev_ZN15wxItemContainerD2Ev_ZN12wxWindowBase12LayoutPhase2EPi_ZN8wxWindow11RemoveChildEP12wxWindowBasewxFrameNameStr_ZTV8wxBitmap_ZN11wxFrameBase14UpdateWindowUIEl_ZN11wxFrameBase13SetStatusTextERK8wxStringi_ZN14wxStaticBitmapC1EP8wxWindowiRK8wxBitmapRK7wxPointRK6wxSizelRK8wxString_ZTI9wxControl_ZN8wxWindow16ApplyWidgetStyleEb_ZN24wxItemContainerImmutable18SetStringSelectionERK8wxString_ZN12wxWindowBase8ValidateEv_ZN8wxWindowC2EvwxEVT_COMMAND_COMBOBOX_SELECTED_ZN8wxWindow18SetWindowStyleFlagEl_ZN8wxBitmap15CreateFromImageERK7wxImagei_ZN16wxStaticBoxSizerC1EP11wxStaticBoxi_ZN8wxWindow12SetScrollbarEiiiib_ZN8wxWindow12DoSetToolTipEP9wxToolTip_ZN6wxIconC1EPPKcii_ZN20wxTopLevelWindowBase7DestroyEv_ZNK8wxWindow24AdjustForLayoutDirectionEiii_ZN9wxAppBase12ExitMainLoopEv_ZN9wxAppBase14SendIdleEventsEP8wxWindowR11wxIdleEvent_ZN12wxWindowBase14SetInitialSizeERK6wxSize_ZN12wxWindowBase8NavigateEi_ZN7wxFrame12SetStatusBarEP11wxStatusBar_ZN12wxWindowBase3FitEv_ZN8wxWindow8SetFocusEv_ZN12wxWindowBase8DoCentreEiwxMessageBoxCaptionStr_ZN8wxWindow5LowerEv_ZN12wxWindowBase16DoSetVirtualSizeEiiwxComboBoxNameStr_ZN5wxApp10InitializeERiPPw_ZN5wxApp13sm_eventTableE_ZNK9wxAppBase18GetLayoutDirectionEv_ZN8wxWindow4ShowEb_ZTV9wxControl_ZN9wxAppBase9SetActiveEbP8wxWindow_ZN8wxWindow8AddChildEP12wxWindowBase_ZN11wxFrameBase15SetStatusWidthsEiPKi_ZN19wxTopLevelWindowGTK12DoMoveWindowEiiii_ZN20wxTopLevelWindowBase11RemoveChildEP12wxWindowBase_ZN11wxFrameBase13DoMenuUpdatesEP6wxMenu_ZNK12wxWindowBase15IsShownOnScreenEv_ZN10wxComboBox6CreateEP8wxWindowiRK8wxStringRK7wxPointRK6wxSizeRK13wxArrayStringlRK11wxValidatorS4__ZN19wxTopLevelWindowGTK8SetIconsERK12wxIconBundle_ZN8wxWindow9SetCursorERK8wxCursor_ZN19wxTopLevelWindowGTK14SetTransparentEh_ZTV12wxGIFHandler_ZN15wxFlexGridSizerC1Eiiii_ZN19wxTopLevelWindowGTK7SetIconERK6wxIcon_ZN8wxWindow12ApplyToolTipEP12_GtkTooltipsPKw_ZNK9wxControl8GetLabelEv_ZN11wxSizerItemC1EiiiiiP8wxObject_ZN8wxWindow18SetBackgroundStyleE17wxBackgroundStyle_ZN11wxStaticBoxC1EP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelS4__ZNK11wxFrameBase11IsOneOfBarsEPK8wxWindow_ZN8wxWindow19SetForegroundColourERK8wxColour_ZN12wxAppConsole16OnFatalExceptionEv_ZN12wxWindowBase18SetConstraintSizesEb_ZN19wxTopLevelWindowGTK17EnableCloseButtonEb_ZNK12wxWindowBase21GetPositionConstraintEPiS0__ZNK8wxWindow12GetCharWidthEv_ZN11wxSizerItemC1EP7wxSizeriiiP8wxObject_ZNK8wxWindow10IsRetainedEv_ZN9wxControl8SetLabelERK8wxString_ZN13wxControlBase7SetFontERK6wxFont_ZTV6wxIcon_Z12wxMessageBoxRK8wxStringS1_lP8wxWindowii_ZNK12wxWindowBase17GetSizeConstraintEPiS0__ZN8wxWindow18DoApplyWidgetStyleEP11_GtkRcStyle_ZN11wxFrameBase10DoGiveHelpERK8wxStringb_ZNK9wxAppBase14GetDisplayModeEv_ZTV10wxComboBox_ZN7wxFrame6CreateEP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelS4__ZN5wxApp12ms_classInfoEwxTextCtrlNameStr_ZN8wxWindow22GTKWidgetDoSetMnemonicEP10_GtkWidget_ZTV12wxXPMHandlerwxDefaultPosition_ZN11wxFrameBaseD2Ev_ZN12wxWindowBase7DoPhaseEi_ZNK20wxTopLevelWindowBase17IsAlwaysMaximizedEv_ZN7wxPanel4InitEv_ZN9wxAppBase12CreateTraitsEv_ZNK8wxWindow12GTKGetWindowER17wxArrayGdkWindows_ZN11wxFrameBase10SetMenuBarEP9wxMenuBar_ZN8wxBitmapD1Ev_ZN12wxWindowBase6LayoutEv_ZNK12wxWindowBase19GetWindowBorderSizeEv_ZN13wxControlBase16DoUpdateWindowUIER15wxUpdateUIEvent_ZN7wxFrame4InitEv_ZN19wxTopLevelWindowGTK9DoSetSizeEiiiii_ZNK9wxAppBase12GetTopWindowEv_ZN10wxTextCtrlC1EP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelRK11wxValidatorS4_wxStaticBitmapNameStr_ZN5wxApp7CleanUpEv_ZNK20wxTopLevelWindowBase16DoScreenToClientEPiS0__ZN11wxFrameBase17OnCreateStatusBarEiliRK8wxString_ZN20wxTopLevelWindowBase26GetRectForTopLevelChildrenEPiS0_S0_S0__ZNK12wxWindowBase27AdjustForParentClientOriginERiS0_i_ZN20wxTopLevelWindowBase10SetMinSizeERK6wxSize_ZN12wxWindowBase22TransferDataFromWindowEv_Z22wxInitAllImageHandlersv_ZN12wxWindowBase12SetValidatorERK11wxValidator_ZN12wxWindowBase9TryParentER7wxEvent_ZTV7wxPanel_ZNK8wxWindow18GetLayoutDirectionEv_ZN20wxTopLevelWindowBase8DoCentreEi_ZN7wxFrame15CreateStatusBarEiliRK8wxString_ZNK8wxWindow16DoScreenToClientEPiS0__ZNK7wxImage4IsOkEv_ZNK12wxWindowBase13DoGetBestSizeEv_ZN8wxWindowD2Ev_ZN9wxAppBase14SetDisplayModeERK11wxVideoMode_ZN19wxTopLevelWindowGTK8IsActiveEv_ZN15wxFlexGridSizer14AddGrowableColEji_ZN9wxAppBase15OnCmdLineParsedER15wxCmdLineParser_ZNK12wxWindowBase19GetClientAreaOriginEv_ZN19wxTopLevelWindowGTK20RequestUserAttentionEi_ZN9wxAppBase12SetPrintModeEi_ZN8wxBitmapD2Ev_ZN12wxWindowBase17SetSizeConstraintEiiii_ZN19wxTopLevelWindowGTK7AddGrabEv_ZN11wxSizerItemC1EP8wxWindowiiiP8wxObjectwxDefaultSize_ZN9wxAppBase6OnExitEv_ZN7wxFrame10SetToolBarEP9wxToolBar_ZTV7wxFrame_ZN14wxCommandEventC1Eiilibwx_baseu_xml-2.8.so.0libwx_baseu_net-2.8.so.0libwx_baseu-2.8.so.0_ZN9wxProcess4OpenERK8wxStringi_ZN11wxClassInfo8sm_firstE_ZNK12wxEvtHandler17DoGetClientObjectEv_ZN12wxEvtHandler15DoSetClientDataEPv_Z7wxEntryRiPPc_ZN12wxAppConsole14ms_appInstanceE_ZN12wxEvtHandler9TryParentER7wxEvent_ZN8wxString9FromAsciiEPKc_ZN12wxEvtHandler12ProcessEventER7wxEvent_ZNK5wxDir8IsOpenedEv_ZN12wxAppConsole14OnCmdLineErrorER15wxCmdLineParser_ZN8wxString6FormatEPKwz_ZNK8wxObject12CloneRefDataEPK15wxObjectRefData_ZN5wxDirD1Ev_ZN8wxObject3RefERKS__ZN8wxObject5UnRefEv_ZN16wxEventHashTableD1Ev_ZNK10wxListBase4FindERK9wxListKey_ZN12wxAppConsole13OnCmdLineHelpER15wxCmdLineParser_ZTV16wxObjectListNode_ZTI10wxListBase_ZN12wxAppConsole20ProcessPendingEventsEv_ZNK8wxString9CmpNoCaseEPKw_ZN12wxStringBaseaSEPKw_ZN12wxStringBaseaSERKS__ZplRK8wxStringPKw_ZTI8wxThread_Z8wxGetCwdv_ZTV8wxObject_ZN10wxNodeBaseC2EP10wxListBasePS_S2_PvRK9wxListKey_ZN12wxStringBase4nposE_ZNK8wxObject13CreateRefDataEv_ZNK8wxString3CmpEPKw_ZN5wxDirC1ERK8wxString_ZN11wxClassInfo8RegisterEv_ZNK8wxObject12GetClassInfoEv_ZplRK8wxStringS1__ZN8wxThread11TestDestroyEv_ZNK5wxDir7GetNextEP8wxString_ZN6wxFile6ExistsEPKw_ZN12wxAppConsole17CheckBuildOptionsEPKcS1__ZN13wxArrayStringD1Ev_ZNK12wxEvtHandler15DoGetClientDataEv_ZN16wxEventHashTableC1ERK12wxEventTable_ZN13wxArrayString4InitEb_ZN12wxEvtHandler16SearchEventTableER12wxEventTableR7wxEvent_ZN12wxStringBase8InitWithEPKwjj_Z17wxIsPlatform64Bitv_ZNK8wxString5RightEjwxEVT_NULL_ZN11wxClassInfoD1Ev_ZNK8wxString4LeftEj_ZN17wxStringTokenizerC1ERK8wxStringS2_21wxStringTokenizerMode_ZN12wxAppConsole11FilterEventER7wxEvent_ZTI8wxObject_ZN8wxThreadD2Ev_ZN12wxAppConsole12ms_appInitFnE_ZplPKwRK8wxString_ZNK5wxDir8GetFirstEP8wxStringRKS0_i_Z11wxGetLocalevwxEmptyString_ZN10wxListBaseD2Ev_ZN13wxArrayString3AddERK8wxStringj_ZN12wxEvtHandler17DoSetClientObjectEP12wxClientData_ZN19wxStandardPathsBase3GetEv_ZN17wxStringTokenizer12GetNextTokenEv_ZN6wxListC1Ei_ZNK12wxAppConsole11HandleEventEP12wxEvtHandlerMS0_FvR7wxEventES3__ZN8wxString9MakeLowerEvlibstdc++.so.6_Znwj_ZTVN10__cxxabiv120__si_class_type_infoE_Znaj__cxa_pure_virtual_ZNSt8ios_base4InitC1Ev_ZdlPv_ZNSt8ios_base4InitD1Ev__gxx_personality_v0_ZTVN10__cxxabiv117__class_type_infoElibm.so.6libgcc_s.so.1_Unwind_Resumelibpthread.so.0libc.so.6_IO_stdin_used__cxa_atexitmemmove__libc_start_mainfree_edata__bss_start_endGCC_3.0CXXABI_1.3GLIBCXX_3.4GLIBC_2.1.3GLIBC_2.0WXU_2.8? P&y ?;>0ӯk?t)?;?0si ?ii ?'6 H% ?H% ?\JȪP0@p}$t0@P;X`d/x mCp@3^ $@!p dDNP`" Pkd@pMt_O  Kt $(,048<@DHqLPT XI\ `cdhl ptx | &z'lĠȠ̠РԠؠܠ yi  X$(,048<@DHLPTX\`dhlptx|o*? !"ġvȡ#̡С$ԡءܡ|%2&o] '( )$*(,+04-8<Z@4DHL<P~TX\k`.d/hl0ptx|123Bm45v6u(EĢ7Ȣ̢8ТԢ{آ{ܢ9:w);< +=> ?$(8,0@4[8A<B@CDHLDPETFX\`GdhlptYxH|@IJKLMbNOP=ģQȣ̣УԣأܣrRSTnUV  W $X(T,048Y<@ZDGH~L[PTjX\\`]dlhl^pet_x`|RaWbAcLd>geĤUS[èt~!X[5%%h%h%h% h%h %h(%h0%h8p% h@`%$hHP%(hP@%,hX0%0h` %4hh%8hp%<hx%@h%Dh%Hh%Lh%Ph%Th%Xh%\hp%`h`%dhP%hh@%lh0%ph %th%xh%|h%h%h%h%h%h %h(%h0%h8p%h@`%hHP%hP@%hX0%h` %hh%hp%hx%h%Ġh%Ƞh%̠h%Рh%Ԡh%ؠh%ܠhp%h`%hP%h@%h0%h %h%h%h%h%h%h% h%h %h(%h0%h8p% h@`%$hHP%(hP@%,hX0%0h` %4hh%8hp%<hx%@h%Dh%Hh%Lh%Ph%Th%Xh%\hp%`h`%dhP%hh@%lh0%ph %th%xh%|h%h%h%h%h%h %h(%h0%h8p%h@`%hHP%hP@%hX0%h` %hh%hp%hx%h%ġh%ȡh%̡h%Сh%ԡh%ءh%ܡhp%h`%hP%h@%h0%h %h%h%h%h%h%h% h%h %h(%h0%h8p% h@`%$hHP%(hP@%,hX0%0h` %4hh%8hp%<hx%@h%Dh%Hh%Lh%Ph%Th%Xh%\hp%`h`%dhP%hh@%lh0%ph %th%xh%|h%h%h%h%h%h %h(%h0%h8p%h@`%hHP%hP@%hX0%h` %hh%hp%hx%h%Ģh%Ȣh%̢h%Тh%Ԣh%آh%ܢhp%h`%hP%h@%h0%h %h%h%h%h%h%h% h%h %h(%h0%h8p% h@`%$hHP%(hP@%,hX0%0h` %4hh%8hp%<hx%@h%Dh%Hh%Lh%Ph%Th%Xh%\hp%`h`%dhP%hh@%lh0%ph %th%xh%|h%h%h%h%h%h %h(%h0%h8p%h@`%hHP%hP@%hX0%h` %hh%hp%hx%h%ģh%ȣh%̣h%Уh%ԣh%أh%ܣhp%h`%hP%h@%h0%h %h%h%h%h%h%h% h%h %h(%h0%h8p% h@`%$hHP%(hP@%,hX0%0h` %4hh%8hp%<hx%@h%Dh%Hh%Lh%Ph%Th%Xh%\hp%`h`%dhP%hh@%lh0%ph %th%xh%|h%h %h %h %h %h %h( %h0 %h8 p%h@ `%hH P%hP @%hX 0%h` %hh %hp %hx %h %Ĥh 1^PTRh'h'QVh`_US=u?뤞9s9r[]Ít&'Utt $ÐÍv'5Ív'ؿÍv'D$ǀǀǀǀǀǀǀǀǀǀǀǀǀǀǀǀǀǀǀ ÐÍv'S\$ $tD$$@ [Ðt&`$D$h(jD$$@ [ÐDžX`EHDžT`L$@D$ $虧|D$D$D$$T$$T$8$,$D$$D$ D$L$D$0D$ D$'T$,$蓭$PHt҉P]u$PHt҉P-u踣vD$D$*$Rz$t$ D$D$,$ѩl$T$:$PHt҉Pt$DD$@DT$@D$D$D$ D$T$$BL$<l$Q4 $T$P֢DvD$D$`+$RyD$$t$ D$$$t$ D$D$,$̨$T耧L$8$D$@l$D$D$D$0T$ D$L$$$PHt҉PMs$PHt҉Ps$hL$@D$E|$U4,$T$P$D$D$ D$D$$D$D踜D$D$D$ D$|$$蚠L$Hl$Q4 $T$PNiD$D$+$R oD$$t$ D$$g$t$ D$D$,$D$TL$8$D$@l$D$D$D$0T$ D$L$$e$PHt҉Pf$PHt҉Pf$hiL$@D$T$8HPD$$ݑL$8 $aD$HT$8|$D$D$D$ 0D$'D$$艌$0PHt҉PS$證D$@D$D$ D$D$$L$@D$8D$L$$$YD$q@FD$D$-$RK$t$ D$D$<$w$D$|$ $2~$PHt҉PR>=qED$D$-$RH$t$ D$D$<$Vw$D$|$$}$PHt҉P=pED$D$-$R}J$t$ D$D$<$v$D$|$$$}$PHt҉P$=/pED$D$-$RI$t$ D$D$<$Hv$D$|$ $|$PHt҉P<oDD$D$-$R F$t$ D$D$<$u$D$|$$|$PHt҉P;!oDD$D$-$RH$t$ D$D$<$:u$D$|$${$PHt҉P_;nCD$D$-$R G$t$ D$D$<$t$D$|$ ${$PHt҉P:nCD$D$-$RrF$t$ D$D$<$,t$D$|$$z$PHt҉P1:mCD$D$-$RGD$t$ D$D$$s$dL$XDŽ$d#DŽ$hD$\$ $lD$X$t$ D$D$ $D$\,$$8s$qlj$RyLJX`HLJT`D$LD$$o|D$T$T$oT$8$$D$$l$$D$ D$L$D$0D$ D$'T$<$u$PHt҉P8$PHt҉PY8k@AD$D$-$R=D$t$ D$D$<$q|$T$Vy$PHt҉P7$DdpD$D$D$ D$l$$ftL$D|$Q4 $T$PjR@D$D$-$RA$t$ D$D$,$q$t$ D$D$<$p$ToD$DD$8T$D|$D$D$D$0l$ D$D$$z$PHt҉P6$PHt҉PT6$hoŋD$DD$,$D$ni$DnD$D$D$ D$l$$rT$<щ|$R4 $T$P$D$$uoi ?D$D$.$R?$|t$ D$D$<$o$D$|$$u$|PHt҉P-5h6>D$D$.$R?$xt$ D$D$<$o$D$|$ $Vu$xPHt҉P4ah=D$D$.$R@D$$tt$ D$$zn$\T$XDŽ$\DŽ$`D$\$$YgD$X$pt$ D$D$ $D$\ $$ n$llj$'tLJX`HLJT`D$'$<PHt҉P'$h`L$v $>v $>hv $>v $>v $>v $>^v $>7v $x>v $h>v $X>v $H>v $8>v $(>v $> v $=]v $=v $=v $=ov $=-v $=v $=jv $=v $x=+v $h=v $X=v $H=fv $8=v $(=8v $=v $= v $v $;駴v $;v $;yv $;v $x;鱱v $h;遱v $X;?v $H;v $8;Hv $(;v $;Jv $;zv $:iv $:9v $:¨v $:v $:v $:v $:Iv $:鈤v $x:wv $h:Gv $X:Сv $H:v $8:>v $(:v $:v $:v $9鞛v $9nv $9Nv $9v $9Mv $9麖v $9銖v $9۔v $x9Dv $h9v $X9v $H9鞑v $89 v $(9ېv $9+v $9锎v $8v $8֌v $8馌v $8Yv $8Ɗv $8閊v $8v $8Ov $x8鸇v $h8!v $X8銆v $H8cv $883v $(8ev $87v $8v $7v$D$<$8$DŽ$ $t@DŽ$ (<$=鏛*s+ř+,\,鿩L,郧<,@,f,,,.u,,@L,.+陒++w+:*ׅ*F*8+dž+6*:`+҉+鏏+L+闎+鿋+<+鹌,, ,饡,,ʤ,鶫.ĭ-AX+),-w-_-閮4-!- (-醯X-阱@-逰, L-l-ķ-ֹ-龸-I-1 -Z<-l$-TH-ߵ0-Ǵ-銺--T-4x-鿷`-駶.k<,.,,g@.-*.-Ŀ--־-鍼.5-.. , ,"$. d.7..<.,,%.e,,R.3,,`D$h($6U,*,*B,*,*,*j,*:,*=,*,*,*W,*,*s,*,*_,*g,*,*鯻,*p,*Q,*Ȝ,*`,*V,*¦,*,*,*,*Q,*,*騀,*骋,*,*-,*霂,*F,*J,*髵,*,*q,*,*4,*k,*魀,*,*n,*r,*6,*#,*,*,*,*n,*,*,*B,*,*,*,*@,*鄹,*鹻,*,*},*|,*,*!,*,*,*~,*",*٪,*H,*L,*魩,*鿫,*ì,*2,*6,*鳭,*ܧ,*,*O,*,*,*ٴ,*鳲,*,*,*,*,*W,*[,*_,*,*,*y,*龱,*²,*É,$6$T$ 1<$6$$y3$ $j3$$[3$$L3$ $=3$$.3$$3$  $3$$3$+Í$  $5$$$5[cÉ,$s)cÉ,$5t&AËD$P$K)YÉ<$<)JÉ,$}5$t$n5,ËD$H$)<$O5 É,$(Í$l$*5ËD$<$(wÉ,$5vËD$<$(c뜍딉Í$\ $4빋L$8É $h(vL$DÉ $U(<$4됉ËD$8$9(-&É,$#($ $d4$$$U4L$8É $,뫋T$<É$'T$@É$'ËD$<$'ËD$D$',$3$X$3Í&݉Í$X0É<$3,$3!ËD$<$K'$h $3<$d2FÍ$ ىËL$8 $'$X$W3v荶vT$8HZ$6볉É<$*<$&fÉ<$2t&덶㍶ۍӍˍÍ뻍볍뫍룍뛍듍닍냍xÉ<$k2$$\2Í$$B2$$32mÉ<$2,$2$ $2uÍ&ݍ뼍É,$1$ $1/É<$1,$1$$1Í&݉É<$t1뙋L$TLJ|Z $ D$LLJ`Z$LJT(YT$<$4<$$,$1$$1뢉f벉Ít&ʉËL$<LJ`Z $LJT(YT$<$4<$^$$,$0$0$0뱉Ðt&ȉ̉Í$t$i0 T$DLJ|Z$[ËD$<$#É,$#L$LDž|Z $D$DDž`Z$DžT(YT$,$3,$#$D$/$H $/B뛉Í막fvÍ$$z/$b%ËD$DLJ|Z$ T$<LJ`Z$LJT(YT$<$2<$"$p $ /몉f뺉։ډÍt&É,$"ËL$8 $}"$H$.$L $.mىÍ$ $.$$.bT$8HZ$92=Í$< $Q.L$LÉ $!& vt&'t&'T$8HZ$1L$8 $!$8$-gft&'t&'L$DÉ $=!K5vpvht&'Xt&'Ht&'8t&'(t&'t&'t&'Í$ $,lÍ$$,$$,GL$@É $^ 0ËD$<$K ËD$@$8 $ $y,{QÉ,$ É<$tËD$<$,$+,$h$,Ð8Ðt&;v닉É<$mËD$<$$\ $+$`$+UىfÍt&viv t&'ËT$@Dž`Z$DžT(YT$,$/,$$x $,+$|$+뱉É,$ +$$*L$@É $oL$<É $|NÉ<$t&c$ $*$$*ىËD$@$.$$o*$ $`*ىÉ,$fK*'É,$&$ É<$$ Í$D $$d]É,$)f@Í&ÐÍ$ $)$$)&荌$É $) É,$)EHZÉ,$D-,$뙉Nvv=t&'.t&'t&'Ut&'t&'É'-É,$ËD$<$}ۉËD$DDž|Z$^T$@Dž`Z$HDžT(YT$P,$H,,$ 빉Ðt&ƉÉ4$$XB-&ËD$H$$É4$$X(T$8É$L$8 $<$'$É,$'$$'=Í&뿉É<$',$'$t$'fÉ<$|',$t'$ $e'fÉ<$L'fÉ,$='(vt&'t&'pt&'É'xÐv뗍돉ËD$@Dž`Z$nDžT(YT$v,$n*,$F$$&$ $x&c뱉ËD$<$LËD$@$,$F&$$7&"Ít&ËD$DDž|Z$T$@Dž`Z$DžT(YT$,$),$$ $%$$%%Í$$%tGÍt&uÐ놉뢉릉É,$l%Í$ $V%#L$@LJ|Z $D$<LJ`Z$LJT(YT$<$(<$$$${몉f뺉Ít&҉։%Ð%ËD$<$],$$ËD$<$B_CÍt&@Hf.É,$-É<$ËD$@$,$5$Í$ ËD$<$$VÉ,$ËD$@$|,$#$$#7fÉ<$#Kf ËD$DDž|Z$#s'1É'vvt&'5É,$Í$H$#aLÍ&dÉ<$"ËD$@$}hvӍˉÉ<$[vqt&'Dt&'L$DDž|Z $É<$T"t&L$DÉ $<$0"&븉É<$É,$É<$!orvt&'É'ÐËD$@$E뗉Ít&(vL$8É $=D$8$g됍&TvËD$<$,$-!$<$!EHZÉ,$$Ð&vt&'t&'Í$8$ t&UWVSL=pt$<\$`D$D$ |$ 4$D$xt$$D$D$tD$D$pD$D$lD$ D$hD$D$dD$D$ c #6CA2B4~. c #E4BE6C2. c #E4CA94(. c #9C9E9C& c #2C3A4Cc. c #ECDEB4j c #947E6C~ c #C4BEB4x c #54929CE. c #A49A74Z c #A4A69C c Nonen c #9CCAC4Y. c #C4B2940. c #ECD29CX. c #B4CECC1. c #CCD2D4OX c #5C7AAC/. c #344254^ c #848E8C! c #D4A28CE c #4C7E94Q. c #ECD2A4#X c #CCBA8CF. c #A48E5C5 c #64AEB4L. c #6482A4} c #3C5674=X c #0C0A0CQ c #6482ACG c #548694%X c #CCBA9C3 c #5C9AAC8. c #D4C28CP c #9CBEBCa c #8CA2BCe. c #DC9E6C7 c #84BABCh c #ACA28C&X c #B4B6A4&. c #B4C2CC5. c #BCBE94] c #445E7CK. c #D4AA4C:. c #9C7A6Cz c #64A2ACoX c #6C8AB4XX c #1C262C^. c #D4AA54!. c #D4B67Cr c #A4C6C4}. c #949E9C% c #1C2634.. c #BC866C- c #5C8EAC*X c #4C6684B c #8CB6A4I. c #DCB254s c #ACCEC4d c #4C668CM c #6496A4n. c #DCBE84e c #547AA4P. c #BCB294l c #74B2AC6. c #74869Cv c #C4D2D4k. c #C4563CI c #9CA6AC*. c #CCDACC< c #7C9ABC4. c #CC966C) c #E4C6846 c #5CAEB4b c #040A0C.X c #E4D2B4U. c #E4BA64p. c #CC5E3C9. c #E4C68C= c #5C82ACY c #ECE6CCR c #A4AEAC=. c #D4E2CCz. c #ECDAAC-. c #7CBABCo. c #7C8284$ c #344A64s. c #ECDAB4 . c #5CA2ACX c #0C1214l. c #ECCE94S c #D4D6BCN c #749A94p c #9CC6C4C. c #ECDAC4q. c #DCA674T c #F4EEDCC c #8C9EA4O c #3C526Cd. c #D4D6CC#. c #64727Cu c #141A1C;. c #BCD2CC+. c #AC9E7CH c #ACB6CCA c #B4BEBCy c #141A24[ c #548294; c #5C96ACT. c #AC9E84m. c #8C866C+X c #6C86A4$X c #D4BE94W c #C4DACC+ c #4C6E94B. c #94A6BCv. c #CC7254F c #BCC6C4w c #1C222C). c #DCC694m c #C49684H. c #DCAE4C<. c #4C6284'. c #DCBA7C`. c #B4A69Ct c #54769Cj. c #CC6644( c #E4CE94c c #4C8E9Cu. c #DC824C* c #5476A4R. c #BCA26C/ c #E4CE9CO. c #9C967CJ c #2C3E54S. c #E4C27C[. c #9CA2AC. c #040604L c #A47264]. c #E4C2844 c #5CAAB4| c #5C7EA4g. c #C4B694a. c #DCAE74f. c #04060Ct. c #546A94@ c #5C7EACh. c #ECD6A4r. c #C4C2C4' c #5C728Cf c #34465C|. c #ECD6AC>. c #64B2B49 c #6486ACq c #0C0E12b. c #E4B67C: c #5C9EAC@. c #84867C, c #74A2B43. c #ECCA94{ c #8CA6BCZ. c #CC7A44y. c #E4C2ACD. c #5C667CV c #74969CW. c #3C4E6C0 c #44628464 64 54 1 c Black- c #0F0F0Fj c #E8E8E87 c #F7F7F7O c #080808. c #171717k c #262626h c #F0F0F02 c #FFFFFFX c #010101q c #101010; c #1F1F1Fl c #E9E9E9d c #F8F8F8% c #090909n c #1818183 c #F1F1F1: c #0202021 c #111111z c #EAEAEA9 c #F9F9F9# c #0A0A0Af c #191919e c #F2F2F2+ c #030303s c #121212y c #FAFAFA* c #0B0B0Ba c #1A1A1Ap c #F3F3F3@ c #040404= c #131313g c #ECECECt c #FBFBFBo c #0C0C0Ci c #F4F4F4> c #0505055 c #141414x c #EDEDEDr c #FCFCFC$ c #0D0D0Db c #1C1C1Cc c #F5F5F5, c #0606068 c #151515m c #2424244 c #EEEEEE0 c #FDFDFD< c #0E0E0Eu c #F6F6F6& c #0707076 c #161616v c #E0E0E0w c #FEFEFE . X . . o O + @ @ @ # $ % & * = - ; : : > , < = 1 2 X # = 3 4 4 5 6 6 6 6 5 7 8 9 0 q w e - 4 6 5 6 6 4 5 4 6 6 6 5 r < t y u e i 6 5 4 6 4 5 6 6 6 5 6 5 6 6 p a + q . + - 6 4 6 6 5 6 6 4 5 4 6 4 6 4 5 4 s < d f g 4 6 6 7 h j k 5 6 6 5 l z x c x 6 6 v 9 2 b @ : 6 5 4 n m M N 5 B V C Z A S D F G 6 7 H t . J = 5 4 6 6 7 K L P C I U Y Y Y T T R E 6 6 W Q o 0 ; 6 6 5 6 7 ! ~ ^ / ( ) ) _ ` h ' ] [ 4 6 p { } . | .4 6 4 5 n ..X.o.O.+.O.@.#.} ] ] $.E 5 6 %.&.1 X @ *.=.W s -.;.:.>.,.] ] ] $.$.] <.] <.E 4 l B 1.| . w = 2.) ) ) _ 3.4.5.S 6.$.] <.] <.] $.] 7.8.) ) D @ q w @ 9._ ) 0.q.w.e.3._ r.t.] $.] $.] <.] o._ ) ) D @ X y @ ` ) 3.y.u.i.p.a.) s.6.# 0 $.0 $.] $.o.) 3.s.d.@ f. . @ g.) h.K j.k.i.e.) 3.r.t <.] $.] <.] o.l.s.z.x.e # Z 3.c.v.p.k.k.b.) n.s.6.t $.0 $.] $.m.M.N.) B.} J V.) C.Z.A.A.Z.S.9.) _ r.t # $.] D.F.G.H.J.K.L.2 X @ P._ 0.I.J.J.H.U.) ) ( Y.T.h R.K.K.J.J.J.E.e . W.V.9.) Q.) J.J.G.H.) 3.!._ ) l.l.~.H.J.^.L./. b t (._ ) 2.( N.~.S.) l.!.) ) ) )._.l.K.^ + w e `._ _.'.9.) 3.) ]._ ) 3.) 9.) s.[.e {. 2 e }.9.) 3.) ) |. X) ) ) ) 9..Xa e w XX1 V.P.) ) 3.) 9.3.) 3./ ,.oX+ y b O OX+X(.@X#X$X%X&XI oXe f . q J *Xe @ | @ e 0 & =X q X b . XoO X+ @ XX# $@% & o @ * % o+ = - ; o : >%, > <>*> * $@ >%o %= 1 - $ >@ X 2322 # 222, @ O>@ @: ++ -% %24O 2$ XX> &:O ,# @5 @ @ & 6 7o78XO4#O, 29222- o X& +@ : :2 0X q2 X %2 X *7< @ q &# 2: 2, wo @2 ++ >& e< > - % : :* 2 :r ,t < 2 @ & 9, % #$+ + yO u, 2 , i # - #2+@ #@ @p@# 2@pX @2 O: :a w < % < >& %2 @ 0 2, 5r @, 21 +% : ,9 %:w2+ 2 O X&2 *> :X > &= ui2% sdw @& @292e2 :s @>& 1 +O$ - +#@: , O :1 q O% > + q , o: - > O # @ & O+ O + * @ o , * ,%> :O+ * @> $ - %&> o > ++ :@ o @ 5@ #,<@Xo* $ &X o @ $X q @ <,* f & % - > : 2 X : % q #, +@ O+ ** O: XX > 1 X @+% + # $ , : 2 X : 22+2r org 2eh2% < ::X22iys2hO O 2292: *$ > : 2 X : 2d <23<*2 ,+7&-+%7X = Ow $uj%: >2 < 2,+ X# : 2 X : d& y% 7$ + >2= >2o-@ &X2 @ u- >5 2 ,# : 2 X : 8d Ow -%t oX +X@ e ki & @O2> &2 O : * : 2 X : 2 *:eX @i- 722d222O 2O# O 2 , 22r2420yq< 6X : 2 X : or & 0$ ,r+: 2 ,Oe > < 2& o0 + > @@ O+ : 2 X : +y>:+2X 2 2 * :> t@ 2@@ & 2 2>, O >XX - >% > , @@ 2& ++3O 2 # w* 2 > ,20 . &9< > 27< & w : 7O $ %> 6 8tr92t0t:@d2x%>09 Otc>+i2222 t2 , O+X >$ * + @O < 1 - *o $$ %+&O: + 2X <# > O, =:++ * #># &O +b < *8 @ * < % q &O % s# & t q n& %@+ 6 , # f+ & OXX # q# ,X # X> ,O:,@@ * qe# : & @+ = $+%, %> =X% : mX * @X 1 X = >> :% >:,X2227@ > $*&O O n+ + + , %-: @* O % $:$ o < +> , ::, * ,+ # @ , >% = O%: + + : : @> - +O : # X+@> :& $ :$ > : $ o X>& & %YP@Y14wxComboBoxBase$Z@ 0 0ZD12wxObjectList\P p@  p P p  p@ `  @@ p  0 @P `@ 0ppPPP   p   p` `     ` `@  p @@Pp   @ p P p 0`Pp     0\$12wxButtonBasePASLAppXPM fileimage/xpmPNG fileimage/pngJPEG fileimage/jpegGIF fileimage/gifSandBox Launcheryour program2.8 (no debug,Unicode,compiler with C++ ABI 1002,wx containers,compatible with 2.6)X_&&@  & P  0&!0P& @ @P`&0  0p&`p&&7PASLApp_P;| 4 H |\ | ̽ l | < | l <ll \$,  ,\L4,X̡ <|  4ܰH\pܱ ,<\|0DXl̲ܲ , < L4\Hl\x̳ܳ <,\@lTh|̴ܴ ,< l$ @ ܵ\ x , < L \ l p ܶ , ܷ  ̸, @ T AC D D$vC@HLO 4DAvC@HLO XD^vC@HLO |0D{vC@HLO jAC D PrAC D AAC D,xvAA AACI$XvAC0DDvAC0DdwAC0D,xE#wAA AACPD,EVwAA AACPD <wC@HZ <wC@HZ,,˛wAA AAF G,\чAA AAC`F P AA C0D ̌'AA C0D FAC D,,DAA AACpD, ̔e AA AAFGH <\ 8Cp D @ <  8 4 P L HD$@8̳#AC DTCh C|AC D AC DAB C  S^AC0OPAC D,(DnAA AACPG.k =Ob  :Y>Z*6i~*6i~6Wnw6Wnw6Wnw'Fdy!NU             %E&Vq&Vq&Vq&VqN+Ff-_  _  _  /,Lgv;/,Lgv;2Ni~2Ni~ =LEߨŤYްٰLҰݭLҰٱ LҰ  LҰ  LҰ ճ LҰ A  LҰҰOҰ¬ҰҰҰLLLLAʛLզOǭ  L!!L""L#A#$$$%%L&'''((((O))ܢ***Я++ޱ+,,A---آ-.///O0011222ˎ2&33Aİ45Ǒ556ڍ66Ǎ777p899999A˒:;;e<<<==>Ŧ>_?@@@@AAAAeBBƛBCDDD_EFFFFAGHHeIIIJJKK_LLMMُMINNÐNOOOގOOPPՏQQRŪRRROSATUUVVOWWժWXX՝XYYYLZŝZL[[L\՜\L]]L^^L__L``LaaLbbLccLdeLeʓfLf“gLghLhiLj՞jLkŞkLllLmmLnnLooLpړpLqғqLrrLssLttLuuLv͜vLwxLxyLyzLzݙ{L{֙|L}Aŵ}}~~LOŴ̓كڴLÅLҴʆL‡AȈLɴϋӌOۍݠ٠̏/AġOϔ֐ÕLōLLAҙș˚ę˘LМѝOʞ׶ٟȠLġLAݤLħѨOөߩ۶̫[I˯)Oβǟ³OAҵڟ͵޷O˸׸պ/ɻA;OıݡLʡաLʡLʡLʡAíʬLʡϳʡʳOʡ¥ʡŲ[ʡʱʡ7ʡܥ ʡƥʡ”ʡ%ʡʡʡ͔@ʡƔʡ@Njڲ+@פפפEפɨפפҰʡʡʡ1ʡ9Ĩ5,h--  [=u=   =   "he [          );NyK s /   /   /   / Q    P )Ak56'6;>??+?;? @ ,(o\| ?  oHoo&6FVfv&6FVfv  & 6 F V f v           & 6 F V f v           & 6 F V f v           & 6 F V f v           & 6 F V f v         &6FVfv&6FVfv&6FVfv&6FVfv&6FVfv&6FVfv&6FVfv&6FVfv&6FVfv&6FVfv&6FVfv&6FVfv:(:5:B:O:\:i:v:::::::::::;;;,;9;F;S;`;m;z;;;;;;;;;;; <<#<0<=<G<T<a<n<{<<<<<<<<<<< ==$=1=>=K=X=e=r===========>>>(>5>B>O>\>i>v>>>>>>>>>>>???,?9?F?S?`?m?z??????????? @@#@0@=@J@W@d@q@~@@@@@@@@@@A AA'A4AAANA[AhAuAAAAAAAAAAABBB+B8BEBRB_BlByBBBBBBBBBBBCC"C/C ||0F6?Nov[oHHzj {s |  |@@0wpp0,(,`(`7 _dPs@ | 0|Fsandboxgamemaker-2.7.1+dfsg/DISCLAIMER.txt0000664000175000017500000000237511640445372020044 0ustar showardshowardSandbox is based on a software engine that included weapons and monsters. A lot of effort has gone into removing the ability for weapons and monsters to be used in the FPS (main) Game Mode, though there is the unlikely chance that something was missed. In addition, references to monsters and weapons may appear in the source code (the contents of the folder named /src). In addition the sidescroller mode features mild "mario" like action. Teachers/parents might want to try the mode out first and make sure it is appropriate for their children. Sidescroller.bat can simply be deleted if it is deemed not suitable. The RPG and Rose Storm Game Modes do feature and allow the ability for violent spell attacks and melee attacks. If you would like to remove access from them delete CLICK_ME_TO_START - RPG MODE and RoseStorm in the top level folder. When you use this software you agree to keep that in mind and will not hold Platinum Arts liable for any related incidents. For any questions and comments please e-mail PlatinumArts@gmail.com Copyright (C) 2007 Platinum Arts LLC This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. sandboxgamemaker-2.7.1+dfsg/Platinum Arts Sandbox Social Site.url0000664000175000017500000000026111660521044024516 0ustar showardshoward[InternetShortcut] URL=http://sandboxgamemaker.com/game-design-community Modified=00AA389C0645CA0194 IDList= HotKey=0 [{000214A0-0000-0000-C000-000000000046}] Prop3=19,2 sandboxgamemaker-2.7.1+dfsg/Platinum Arts Sandbox Website.url0000664000175000017500000000012311400565520024015 0ustar showardshoward[InternetShortcut] URL=http://sandboxgamemaker.com/ Modified=00AA389C0645CA0194 sandboxgamemaker-2.7.1+dfsg/launcher_new0000664000175000017500000025635411442705532020271 0ustar showardshowardELF4x4 (&#444  TTTnn nn@@hhhDDPtd̻;;,,QtdRtdnnhh/lib/ld-linux.so.2GNUGNU;v*yvMձ򻾡or}I 'BMZTZU[a>ToN_4c$Rwx;)PJU!.9AJD<0jit Pg`Q#0w\g?1l/=M++tWS@)=^-"hC]v5j"yY]1z4kK-&\%8'L*v$3 E2uxnd6~_rb[@EYG3,fVFA  H&6fLQCuNFb8sI:alm ? e,*O25O XW% q}|Kyo>;pz`H(/~ n sX|#h(.eSV i!{GR{^qB7D:dm9kpc<77@ / L H Љv"UhR@AB"DEP@AQdD& A<$"TLRE"00R8€ $ PD" 8HJL$4R 4X) (@B@-4Q%0Xx p !ABlg' i! έB,6@BX J1*@PDp"ǃjN?ADEGIKNOPRSVXZ_`aeghikmopqstxyz{~؈E=[[CT,쌰$tE<-< ҩY&CpˆceC55eFݞm;TQ=1ӾoH6NyIk&Y!l. 6]R}hY~[R=NRjE]uʿ. Ym΀Ƹ$Y˾7վ+|vd.}UHvzX˷WCTyBV *a}l;HYRg3P`䫣u)N{vfcŨzv(GsoA'1ƙVLC۳j|rBoYˆj1e6ܢ>]S7͵s)ݿm^ݸhZb gLc&'U55;4ȁ (@CE1CjDZ#Bي3qM> Ncn`lP(MړtF>E\"j{]{@7Y"a-%B{9P&+b&ddNyP} aXmuV Yf}`Hd2+(O* >?#vz cQ?4+­\xʈi)0.=A\&ΰR-Fei NXme4 FS3GI ,&6ڂbxZޗ$,taa `u`S2ckVa:BQKgRnφ/o.|%N[ WmxoLN$0 O|w{edm8Cvb#be5Ws w'ʟ }U[%vi̶T;j9YraGh9E/U"qXh{Y1ȳM:3j_Ueg,VWj64u+2R#bT+Jf\+Գ@Q)PiWX1x%Wzut$` p jԷO ^mE\V(*9N떏;":.\O֨LrP}:`br7Xx~n@Aej9Եj楋Tl6xxƆ@',S5VzPԃ 鳎˻ rez$}'[[t?u FO,#h1ąT)ELݣ_d6{<|IOlX82Sc<&E?%9QzVd"RqS<3{rv9ؿám6ړlbf,;JО`oCQε͟}? cJgc+n V#A6.T!46R6)H1'2 21645I416. 75\.366312 660,) +#2* %[T",H "~ 4/0"]) v@!.XZ+h0Xm'!Hu !H5h!h X3 u !('l# "!h=6P(q&()t6 0"8$!o "$ H$*" (g2"7"+X}-xE H x\" "]Hj4!ut!*V! ""7ce(&xxHv# "SH-"+"q`*0"yJ#"N-#uW;!' 4 n("[-",$"F&H*f#"e`u!5|,!@}@!G'":#xr5$( #B"-tSm,""[j~) "i"*h  "f 0"H ~!"L/*"83!%6,0"R6t,!4u/X6(t&(8m.  " $")XX#" $"T0*0"x1W)")9{ "J  "! X}"x-H"""3CL @!"$Xe$t-v! 8'%" X 8L"'; !#0},!(8.t t;!r#Xh 2!"'?,0"}(.h"$ "7(h*pt!)">)?" " "+ q"-$/8%%8 Z0"^'"$!|8R!"J28Ox(&&xB'%"!|t!<0""+;!H`y!1(""6d0;!j/H$-"o#"2X$!"Hj X34K"=(+p" v,.% >@8!(hHt !u({"3~2} !Qr$"w0!"@$(H\%8cx/@th: #"(""5/%! "x7(t+-(X,R4`vm $"ah2}!8]$ "'"", .(?"j ! " ;!# ~%,"+HZ "0u5y$ !/h n!"+e*'?"%Z " "/f"M2@u!wD"Y|+"-; !;)@"h18Xh8,-$$Y3H=8"x:0!) "x" "],:3"85|3"" "~H6 !" ;! d/0"4*!"%6n+`t,I "} !#8,X+h; ! '"E+(*W#0x(?"# j""48"|$"% $"I $"" "0h(h.""w3wX/X[$ )" #*"#libwx_gtk2u_richtext-2.8.so.0__gmon_start___Jv_RegisterClasses_ZN13wxTransform2DD1Ev_ZNK14wxMenuItemList4FindERK9wxListKey_ZNK12wxWindowBase9IsEnabledEv_ZN12wxButtonBase15SetImageMarginsEii_ZNK8wxWindow21IsTransparentForMouseEv_ZN12wxWindowBase16DissociateHandleEv_ZTV14wxMenuItemList_ZN12wxWindowBase31GetMainWindowOfCompositeControlEv_ZNK12wxWindowBase20ShouldInheritColoursEv_ZN12wxWindowBase24HasTransparentBackgroundEv_ZN14wxMenuItemListD0Ev_ZNK19wxTopLevelWindowGTK8GetTitleEv_ZN9wxControlD2Ev_ZNK12wxWindowBase10GetMaxSizeEv_init_ZTS13wxTransform2D_ZN14wxMenuItemListD1Ev_ZN12wxButtonBase10SetDefaultEv_ZN12wxWindowBase12SetSizeHintsEiiiiii_ZTS14wxMenuItemList_ZNK12wxWindowBase7GetNameEv_ZNK12wxWindowBase24AcceptsFocusFromKeyboardEv_ZNK12wxButtonBase20ShouldInheritColoursEv_ZN8wxWindow15FixUpMouseEventEP10_GtkWidgetRiS2__ZN8wxThread6OnExitEv_ZN12wxButtonBaseD0Ev_ZN12wxWindowBase14SetTransparentEh_ZNK13wxTransform2D16InverseTransformERK12wxPoint2DInt_ZNK13wxTransform2D16InverseTransformERK11wxRect2DInt_ZTI12wxButtonBase_ZNK12wxWindowBase18GetBestVirtualSizeEv_ZN12wxButtonBaseD1Ev_ZNK9wxControl15UseGTKStyleBaseEv_ZTI20wxThreadHelperThread_ZNK8wxWindow8GetLabelEv_ZN12wxWindowBase12GetValidatorEv_ZNK13wxTransform2D9TransformEP11wxRect2DInt_ZNK12wxWindowBase8IsFrozenEv_ZNK12wxWindowBase27GetWindowSizeForVirtualSizeERK6wxSize_ZNK12wxWindowBase20GetDefaultAttributesEv_ZTS20wxThreadHelperThread_ZN20wxThreadHelperThread5EntryEv_fini_ZN12wxWindowBase6FreezeEv_ZNK12wxWindowBase16HasMultiplePagesEv_ZNK20wxTopLevelWindowBase9IsVisibleEv_ZTV12wxButtonBase_ZNK19wxTopLevelWindowGTK12IsFullScreenEv_ZN12wxWindowBase10SetMaxSizeERK6wxSize_ZN8wxWindow14OnParentEnableEb_ZNK12wxWindowBase7IsShownEv_ZNK19wxTopLevelWindowGTK9IsGrabbedEv_ZN12wxWindowBase9PrepareDCER4wxDC_ZNK12wxWindowBase10HasCaptureEv_ZN12wxWindowBase7SetNameERK8wxString_ZN8wxWindow8SetLabelERK8wxString_ZNK12wxWindowBase10GetMinSizeEv_ZN12wxWindowBase4ThawEv_ZTV13wxTransform2D_ZNK8wxWindow9GetHandleEv_ZN14wxMenuItemList10CreateNodeEP10wxNodeBaseS1_PvRK9wxListKey_ZN12wxWindowBase15SetThemeEnabledEb_ZNK20wxTopLevelWindowBase20ShouldPreventAppExitEv_ZNK13wxTransform2D9TransformERK12wxPoint2DInt_ZNK20wxTopLevelWindowBase10IsTopLevelEv_ZTI14wxMenuItemList_ZNK8wxWindow13IsRadioButtonEv_ZNK13wxTransform2D9TransformERK11wxRect2DInt_ZN12wxEvtHandler12TryValidatorER7wxEvent_ZTS12wxButtonBase_ZN12wxButtonBase13SetImageLabelERK8wxBitmap_ZN12wxWindowBase15AssociateHandleEP10_GtkWidget_ZTI13wxTransform2D_ZTV20wxThreadHelperThread_ZNK12wxWindowBase15GetThemeEnabledEv_ZN12wxWindowBase18SetInitialBestSizeERK6wxSize_ZN12wxWindowBase19SetAcceleratorTableERK18wxAcceleratorTable_ZN20wxThreadHelperThreadD0Ev_ZNK12wxWindowBase18GetWindowStyleFlagEv_ZNK13wxTransform2D16InverseTransformEP11wxRect2DInt_ZNK20wxTopLevelWindowBase19DoGetScreenPositionEPiS0__ZNK12wxWindowBase13GetDropTargetEv_ZN20wxThreadHelperThreadD1Ev_ZN12wxWindowBase17CanSetTransparentEv_ZN13wxTransform2DD0Ev_ZN8wxObjectD2Ev_ZN8wxStringC1EPKw_ZN12wxWindowBase15SetFocusFromKbdEv_ZNK12wxWindowBase18GetBackgroundStyleEv_ZN12wxWindowBase13SetExtraStyleEl_ZN12wxWindowBase10SetMinSizeERK6wxSize_ZN8wxStringD1Evlibwx_gtk2u_aui-2.8.so.0_ZNK7wxFrame19GetClientAreaOriginEv_ZNK11wxFrameBase10GetToolBarEv_ZNK11wxFrameBase10GetMenuBarEv_ZN11wxFrameBase15PositionToolBarEv_ZN11wxFrameBase15PositionMenuBarEv_ZNK11wxFrameBase12GetStatusBarEvlibwx_gtk2u_xrc-2.8.so.0libwx_gtk2u_qa-2.8.so.0libwx_gtk2u_html-2.8.so.0libwx_gtk2u_adv-2.8.so.0libwx_gtk2u_core-2.8.so.0_ZN12wxWindowBase10InitDialogEv_ZNK12wxWindowBase19DoGetScreenPositionEPiS0__ZN11wxFrameBase13SendSizeEventEv_ZN8wxWindow12ScrollWindowEiiPK6wxRect_ZNK19wxTopLevelWindowGTK11IsMaximizedEv_ZN13wxControlBase7CommandER14wxCommandEvent_ZN8wxWindow18SetLayoutDirectionE17wxLayoutDirection_ZN19wxTopLevelWindowGTK8SetTitleERK8wxString_ZN12wxWindowBase17InheritAttributesEv_ZTV8wxColour_ZNK7wxFrame15DoGetClientSizeEPiS0__ZNK8wxWindow16IsDoubleBufferedEv_ZNK8wxWindow14GetScrollRangeEi_ZN7wxFrame13AttachMenuBarEP9wxMenuBar_ZNK12wxWindowBase13GetEventTableEv_ZNK12wxWindowBase9DoHitTestEii_ZNK8wxWindow11DoIsExposedEiiii_ZN19wxTopLevelWindowGTK10RemoveGrabEv_ZN8wxWindow11ScrollLinesEi_ZN7wxFrame15DoSetClientSizeEii_ZNK7wxFrame12GetClassInfoEv_ZN8wxWindow14DoReleaseMouseEv_ZN9wxAppBase4ExitEv_ZN12wxWindowBase20TransferDataToWindowEv_ZNK12wxWindowBase17GetEventHashTableEv_ZN20wxTopLevelWindowBase16DoUpdateWindowUIER15wxUpdateUIEvent_ZN19wxTopLevelWindowGTK4ShowEb_ZNK8wxWindow12AcceptsFocusEv_ZN8wxWindow19SetBackgroundColourERK8wxColour_ZNK12wxWindowBase16DoGetVirtualSizeEv_ZNK8wxWindow13DoGetPositionEPiS0__ZNK8wxWindow9DoGetSizeEPiS0__ZN19wxTopLevelWindowGTK7RestoreEv_ZTV8wxButton_ZN13wxControlBaseD2Ev_ZN6wxMenu4InitEv_ZN19wxTopLevelWindowGTK8MaximizeEb_ZN8wxWindow16GetConnectWidgetEv_ZNK9wxControl12GetClassInfoEv_ZN5wxApp9OnInitGuiEv_ZTV20wxwxMenuItemListNode_ZN8wxColourD1Ev_ZN5wxAppC2Ev_ZNK12wxWindowBase23GetClientSizeConstraintEPiS0__ZTI7wxFrame_ZN12wxWindowBase12LayoutPhase1EPi_ZN7wxFrame13CreateToolBarEliRK8wxStringwxEVT_COMMAND_BUTTON_CLICKED_ZN10wxMenuBaseD2Ev_ZN8wxWindow12DoMoveWindowEiiii_ZN8wxWindow9DoSetSizeEiiiii_ZN19wxTopLevelWindowGTK17CanSetTransparentEv_ZN19wxTopLevelWindowGTK14DoSetSizeHintsEiiiiii_ZN8wxWindow7SetFontERK6wxFontwxDefaultValidator_ZN8wxWindow14DoCaptureMouseEv_ZN9wxAppBase5OnRunEv_ZN9wxAppBase21OnExceptionInMainLoopEv_ZN8wxWindow11WarpPointerEii_ZTV12wxColourBase_ZN7wxFrame9GtkOnSizeEv_ZNK9wxAppBase8IsActiveEv_ZN12wxStaticTextC1EP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelS4__ZNK9wxControl13DoGetBestSizeEv_ZNK8wxWindow15GTKProcessEventER7wxEvent_ZN8wxWindow11ScrollPagesEi_ZN19wxTopLevelWindowGTK8SetShapeERK8wxRegion_ZN8wxWindow13SetDropTargetEP12wxDropTarget_ZNK12wxWindowBase10IsTopLevelEv_ZN12wxAppConsole20OnUnhandledExceptionEv_ZN12wxWindowBase18DoSetWindowVariantE15wxWindowVariant_ZN9wxAppBase7PendingEv_ZN22wxSystemSettingsNative9GetMetricE14wxSystemMetricP8wxWindow_ZNK19wxTopLevelWindowGTK10IsIconizedEv_ZN14wxMenuItemBase3NewEP6wxMenuiRK8wxStringS4_10wxItemKindS1__ZN11wxFrameBase15OnCreateToolBarEliRK8wxString_ZN5wxApp10WakeUpIdleEv_ZNK8wxWindow13GetCharHeightEv_ZN9wxControl14OnInternalIdleEv_ZN12wxWindowBase25GetClassDefaultAttributesE15wxWindowVariant_ZN7wxPanel6CreateEP8wxWindowiRK7wxPointRK6wxSizelRK8wxString_ZN19wxTopLevelWindowGTK14ShowFullScreenEbl_ZTV11wxGDIObject_ZN8wxWindow6UpdateEv_ZN9wxControlC2Ev_ZNK12wxWindowBase13GetClientSizeEv_ZN8wxWindow15ClearBackgroundEv_ZN5wxApp5YieldEb_ZN10wxMenuBase4InitEl_ZNK5wxApp17GetEventHashTableEv_ZNK9wxControl20GetDefaultAttributesEv_ZN9wxAppBase13OnInitCmdLineER15wxCmdLineParser_ZN18wxControlContainerC1EP8wxWindow_ZN8wxWindow16DoMoveInTabOrderEPS_N12wxWindowBase8MoveKindE_ZN7wxFrameD2Ev_ZN8wxWindow7DestroyEv_ZN7wxFrame13DetachMenuBarEv_ZNK8wxWindow15DoGetClientSizeEPiS0__ZN8wxWindow6EnableEb_ZNK8wxWindow13GetTextExtentERK8wxStringPiS3_S3_S3_PK6wxFont_ZN12wxWindowBase14DoSetSizeHintsEiiiiii_ZN12wxWindowBase9MakeModalEb_ZTI5wxApp_ZN12wxWindowBase19SetVirtualSizeHintsEiiii_ZN12wxWindowBase12TryValidatorER7wxEvent_ZN12wxWindowBase14MoveConstraintEii_ZNK12wxWindowBase16GetDefaultBorderEv_ZNK8wxWindow14GetScrollThumbEi_ZN8wxWindow12SetScrollPosEiib_ZN8wxButton6CreateEP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelRK11wxValidatorS4__ZN9wxAppBase8DispatchEv_ZN7wxFrame14OnInternalIdleEv_ZNK8wxWindow12GetScrollPosEi_ZN8wxWindow7RefreshEbPK6wxRect_ZN11wxFrameBaseC2Ev_ZNK8wxWindow11DoIsExposedEii_ZN20wxTopLevelWindowBase10SetMaxSizeERK6wxSize_ZN19wxTopLevelWindowGTK18SetWindowStyleFlagEl_ZN12wxWindowBase14UpdateWindowUIEl_ZNK12wxWindowBase18GetHelpTextAtPointERK7wxPointN11wxHelpEvent6OriginE_ZN8wxWindow5RaiseEv_ZN12wxWindowBase10GetCaptureEv_ZN8wxWindow15DoSetClientSizeEiiwxButtonNameStr_ZNK20wxTopLevelWindowBase16DoClientToScreenEPiS0__ZNK8wxWindow22GTKWidgetNeedsMnemonicEv_ZN19wxTopLevelWindowGTK7IconizeEb_ZN9wxAppBase8MainLoopEv_ZN12wxAppConsole10CallOnInitEv_ZN12wxWindowBase9FitInsideEv_ZN19wxTopLevelWindowGTK5RaiseEv_ZN9wxAppBase11ProcessIdleEv_ZN8wxWindow8ReparentEP12wxWindowBasewxPanelNameStr_ZN8wxWindow11DoPopupMenuEP6wxMenuii_ZN7wxFrame17PositionStatusBarEv_ZN11wxRect2DIntaSERKS__ZNK8wxWindow16DoClientToScreenEPiS0__ZN5wxAppD2Ev_ZN12wxWindowBase12LayoutPhase2EPi_ZN8wxWindow11RemoveChildEP12wxWindowBasewxFrameNameStr_ZN11wxFrameBase14UpdateWindowUIEl_ZN11wxFrameBase13SetStatusTextERK8wxStringi_ZTI9wxControl_ZN8wxWindow16ApplyWidgetStyleEb_ZTV10wxMenuBase_ZTV6wxMenu_ZN12wxWindowBase8ValidateEv_ZN8wxWindowC2Ev_ZN8wxWindow18SetWindowStyleFlagEl_ZN8wxWindow12SetScrollbarEiiiib_ZN8wxWindow12DoSetToolTipEP9wxToolTip_ZN20wxTopLevelWindowBase7DestroyEv_ZNK8wxWindow24AdjustForLayoutDirectionEiii_ZN9wxAppBase12ExitMainLoopEv_ZN9wxAppBase14SendIdleEventsEP8wxWindowR11wxIdleEvent_ZN12wxWindowBase14SetInitialSizeERK6wxSize_ZN12wxWindowBase8NavigateEi_ZNK5wxApp12GetClassInfoEv_ZN7wxFrame12SetStatusBarEP11wxStatusBar_ZN12wxWindowBase3FitEv_ZN8wxWindow8SetFocusEv_ZN12wxWindowBase8DoCentreEi_ZN8wxWindow5LowerEv_ZN12wxWindowBase16DoSetVirtualSizeEii_ZN5wxApp10InitializeERiPPw_ZNK9wxAppBase18GetLayoutDirectionEv_ZN8wxWindow4ShowEb_ZTV9wxControl_ZN9wxAppBase9SetActiveEbP8wxWindow_ZN8wxWindow8AddChildEP12wxWindowBase_ZN11wxFrameBase15SetStatusWidthsEiPKi_ZN19wxTopLevelWindowGTK12DoMoveWindowEiiii_ZN20wxTopLevelWindowBase11RemoveChildEP12wxWindowBase_ZN11wxFrameBase13DoMenuUpdatesEP6wxMenu_ZN12wxWindowBase5CloseEb_ZNK12wxWindowBase15IsShownOnScreenEv_ZN19wxTopLevelWindowGTK8SetIconsERK12wxIconBundle_ZN8wxWindow9SetCursorERK8wxCursor_ZN19wxTopLevelWindowGTK14SetTransparentEh_ZN19wxTopLevelWindowGTK7SetIconERK6wxIcon_ZN8wxWindow12ApplyToolTipEP12_GtkTooltipsPKw_ZNK9wxControl8GetLabelEv_ZN8wxWindow18SetBackgroundStyleE17wxBackgroundStyle_ZNK11wxFrameBase11IsOneOfBarsEPK8wxWindow_ZN8wxWindow19SetForegroundColourERK8wxColour_ZN12wxAppConsole16OnFatalExceptionEv_ZN12wxWindowBase18SetConstraintSizesEb_ZN19wxTopLevelWindowGTK17EnableCloseButtonEb_ZNK12wxWindowBase21GetPositionConstraintEPiS0__ZNK8wxWindow12GetCharWidthEv_ZNK8wxWindow10IsRetainedEv_ZN9wxControl8SetLabelERK8wxString_ZN13wxControlBase7SetFontERK6wxFont_ZNK12wxWindowBase17GetSizeConstraintEPiS0__ZN8wxWindow18DoApplyWidgetStyleEP11_GtkRcStyle_ZN11wxFrameBase10DoGiveHelpERK8wxStringb_ZNK9wxAppBase14GetDisplayModeEv_ZN7wxFrame6CreateEP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelS4__ZN8wxWindow22GTKWidgetDoSetMnemonicEP10_GtkWidgetwxDefaultPosition_ZN11wxFrameBaseD2Ev_ZN12wxWindowBase7DoPhaseEi_ZNK20wxTopLevelWindowBase17IsAlwaysMaximizedEv_ZN7wxPanel4InitEv_ZN9wxAppBase12CreateTraitsEv_ZNK8wxWindow12GTKGetWindowER17wxArrayGdkWindows_ZN11wxFrameBase10SetMenuBarEP9wxMenuBar_ZN12wxWindowBase6LayoutEv_ZNK12wxWindowBase19GetWindowBorderSizeEv_ZN13wxControlBase16DoUpdateWindowUIER15wxUpdateUIEvent_ZN7wxFrame4InitEv_ZNK11wxFrameBase17GetEventHashTableEv_ZN19wxTopLevelWindowGTK9DoSetSizeEiiiiiwxStaticTextNameStr_ZNK9wxAppBase12GetTopWindowEv_ZN5wxApp7CleanUpEv_ZNK20wxTopLevelWindowBase16DoScreenToClientEPiS0__ZN11wxFrameBase17OnCreateStatusBarEiliRK8wxString_ZN20wxTopLevelWindowBase26GetRectForTopLevelChildrenEPiS0_S0_S0__ZNK12wxWindowBase27AdjustForParentClientOriginERiS0_i_ZN20wxTopLevelWindowBase10SetMinSizeERK6wxSize_ZN9wxMenuBarC1Ev_ZNK5wxApp13GetEventTableEv_ZN12wxWindowBase22TransferDataFromWindowEv_ZN12wxWindowBase12SetValidatorERK11wxValidator_ZN12wxWindowBase9TryParentER7wxEvent_ZTV7wxPanel_ZNK8wxWindow18GetLayoutDirectionEv_ZN20wxTopLevelWindowBase8DoCentreEiwxEVT_COMMAND_MENU_SELECTED_ZN7wxFrame15CreateStatusBarEiliRK8wxString_ZNK8wxWindow16DoScreenToClientEPiS0__ZNK12wxWindowBase13DoGetBestSizeEv_ZN8wxWindowD2Ev_ZN9wxAppBase14SetDisplayModeERK11wxVideoMode_ZN19wxTopLevelWindowGTK8IsActiveEv_ZN9wxAppBase15OnCmdLineParsedER15wxCmdLineParser_ZNK12wxWindowBase19GetClientAreaOriginEv_ZN19wxTopLevelWindowGTK20RequestUserAttentionEi_ZN9wxAppBase12SetPrintModeEi_ZN12wxWindowBase17SetSizeConstraintEiiii_ZN19wxTopLevelWindowGTK7AddGrabEvwxDefaultSize_ZNK11wxFrameBase13GetEventTableEv_ZN9wxAppBase6OnExitEv_ZN7wxFrame10SetToolBarEP9wxToolBar_ZTV7wxFramelibwx_baseu_xml-2.8.so.0libwx_baseu_net-2.8.so.0libwx_baseu-2.8.so.0_ZNK12wxEvtHandler17DoGetClientObjectEv_ZN12wxEvtHandler15DoSetClientDataEPv_Z7wxEntryRiPPc_ZN12wxAppConsole14ms_appInstanceE_ZN12wxEvtHandler9TryParentER7wxEvent_ZN12wxEvtHandler12ProcessEventER7wxEvent_ZN10wxListBase4InitE9wxKeyType_ZN12wxAppConsole14OnCmdLineErrorER15wxCmdLineParser_ZN8wxString6FormatEPKwz_ZNK8wxObject12CloneRefDataEPK15wxObjectRefData_ZN12wxEvtHandlerD2Ev_ZN8wxObject3RefERKS__ZN8wxObject5UnRefEv_ZNK10wxListBase4FindERK9wxListKey_ZN12wxAppConsole13OnCmdLineHelpER15wxCmdLineParser_ZTI10wxListBase_ZN12wxAppConsole20ProcessPendingEventsEv_ZN12wxStringBaseaSERKS__ZTI8wxThread_ZTV8wxObject_ZN10wxNodeBaseC2EP10wxListBasePS_S2_PvRK9wxListKey_ZN12wxStringBase4nposE_ZNK8wxObject13CreateRefDataEv_ZNK8wxObject12GetClassInfoEv_ZN8wxThread11TestDestroyEv_ZN12wxAppConsole17CheckBuildOptionsEPKcS1__ZNK12wxEvtHandler15DoGetClientDataEv_ZTV10wxListBase_ZN12wxEvtHandlerC2Ev_ZN12wxEvtHandler16SearchEventTableER12wxEventTableR7wxEvent_ZN12wxStringBase8InitWithEPKwjj_ZN12wxAppConsole11FilterEventER7wxEvent_ZN8wxThreadD2Ev_ZN12wxAppConsole12ms_appInitFnEwxEmptyString_ZN12wxStringData6UnlockEv_ZN10wxListBaseD2Ev_ZN12wxEvtHandler17DoSetClientObjectEP12wxClientData_ZN12wxEvtHandler7ConnectEiiiM8wxObjectFvR7wxEventEPS0_PS__ZNK12wxAppConsole11HandleEventEP12wxEvtHandlerMS0_FvR7wxEventES3_libstdc++.so.6_Znwj_ZTVN10__cxxabiv120__si_class_type_infoE__cxa_pure_virtual_ZNSt8ios_base4InitC1Ev_ZdlPv_ZNSt8ios_base4InitD1Ev__gxx_personality_v0_ZTVN10__cxxabiv117__class_type_infoElibm.so.6libgcc_s.so.1_Unwind_Resumelibpthread.so.0systemlibc.so.6_IO_stdin_used__cxa_atexitmemmove__libc_start_mainfree_edata__bss_start_endGLIBC_2.0GCC_3.0GLIBCXX_3.4CXXABI_1.3GLIBC_2.1.3WXU_2.8 6 ii 76 P&y 750t)%7ӯk1760si <7ii 7b0 H% H7 H% H7o @tHt`tstttOt uG@uKHuB`uu;uua v<`v*vv`y||d||}-}@}}u}}j =ppp> pkpp1ppb p$p(p,p0p4p8p|`s,dsUhswlsxpsltsixs|ss-ss?sss.sgsss/ss s:s0s1sws8s's2s]s)s"ss3ssss4s@ss5sRttt t$t^t_t6tNUS[zt1:X[5o%o%ph%ph%ph% ph%ph %ph(%ph0%ph8p% ph@`%$phHP%(phP@%,phX0%0ph` %4phh%8php%UWVSlD$|E$BEUT$D$@@ UT$UT$U T$ D$D$$E$ E4Eȉ$ D$2Eȉ$e ӉƍE$ډ$D$E$u$\ËU؉t$D$(D$@tD$ tD$T$$]܍E$uE܋@E܍UȉT$$*։lj$ӉƍE$7AE$ËE$U؉\$ D$D$2$SuD$,D$E$}D$`tEԉ$EԉE$TËU܉؋ML$D$D$@t|$t$ D$T$$]ЍEԉ$jE؉$_E$h<։lj$ӉƍEԉ$1ӉƍE؉$)E܉D$E$Eȉ$e[^_]ÉӉƍEȉ$ӉƋE$ډ$uUWVSlD$|E$xEUT$D$@@ UT$UT$U T$ D$D$$GE$VE4Eȉ$D$2Eȉ$ӉƍE$ډ$D$E$u$\8ËU؉t$D$(D$@tD$ tD$T$$) ]܍E$E܋@E܍UȉT$$*։lj$:ӉƍE$mAE$ ËE$U؉\$ D$D$2$uD$,D$E$>}D$`tEԉ$EԉE$T0ËU܉؋ML$D$D$@t|$t$ D$T$$]ЍEԉ$E؉$E$<։lj$4ӉƍEԉ$gӉƍE؉$R)E܉D$E$Eȉ$e[^_]ÉӉƍEȉ$ӉƋE$ډ$U$@3U$Z3U$t3U$3U$3UED$$ ÐU]ÐUD$$UD$$U}uF} u=$D$$tD$$D$$UD$$UE]UE$t EPEÐUE$tEPEEut E$ ÐUE ]ÐU`vE]UE$ÐUE $t E$E EE$$ÐUD$ D$E D$E$ ÐUE$O$ÐUE$3@UE$UE$#ÐUU ET$$U} tE h0UD$$7ÐUE$OÐUU ET$$|EÐUE}E@]UE}E$Dt E$@UE;E tE D$E$EÐUVSE$E(uE D$E$ ӉƋE$kډ$[^]UEU EUP]UEtE@t]UEU EUP]U]ÐUE@E@$U(E D$ED$EUD$T$ED$ D$E D$E$KÐU]UEDE$U]ÐU]UEu]U塀u]UE@N]UEU PD]U]U]ÐUE $ÐUE$EhuUE$EH}UE4E D$E$ÐUE$E(vUEE D$$LUS]؋U ¼T$$؉؃[]UE]US$]E ED$ED$E $ҋUET$D$$؃$[]US]E $tE SE E D$$҃؋]U(EtE D$ED$ED$ED$ ED$E D$E$UE EPLE PEPP]UE EPTE PEPX]US]E PPE @LT$D$$؃[]US]E PXE @TT$D$$v؃[]US$]EU T$$dEU T$$UE9~UUME9~EET$D$$؋]UE]UE]ÐUE]UEU ]ÐUE EEUÐUE]ÐUEE$UEE$UE@`]ÐUU ET$$EÐUEE D$$UU9ÐU]ÐU]ÐU]U]ÐUVS]ދE $D$4$2؉؍e[^]UE]U]U]UE@d]ÐUE EÐU]U]ÐU]ÐU]UE]US]ED$D$$؃[]UE D$E$PU]ÐUS]؋`vT$$؉؃[]UE]UE EU]ÐU]U]UVS E$EvEPD$$E$9E D$ED$ED$ED$ ED$E D$E$ӉƋE$sډ$ [^]U]U]UEE$UE EUT$U T$$UEq]ÐUS]؋U œT$$+؉؃[]UE]ÐUE]UE]UE]U]ÐU]ÐUVS E$E}E$ E$D$E D$ED$ED$ED$ ED$E D$E$ӉƋE$nډ$R [^]ÐUS]D$D$$؃[]UEU EUP]UE EE PEP]ÐUS]؋U JU L$T$$؉؃[]UVS]؋U JU R ыU 2U RL$T$$a؉؃[^]UE EE PEPE PEPE P EP ]ÐUE E9}E EUE PE@9}E @E@UBE E)ȉ1)ЋUBE PE@)ȉ1)ЋUB ]UE:t E$ÐUE:t E$mÐU8EU T$$fEU T$$EED$E$ҋEED$E$ҍED$ED$E؉$E؉D$E $=ÐUS$]؋UT$$E ؉D$E $҉؉؃$[]US$]؋UT$$ E ؉D$E $҉؉؃$[]U8EU T$$VEU T$$uEED$E$ҋEED$E$ҍED$ED$E؉$E؉D$E $-ÐUS$]؋UT$$E ؉D$E $҉؉؃$[]US$]؋UT$$E ؉D$E $҉؉؃$[]U]UE(EP$iE$t E$UE$EH8U]ÐU]ÐU]ÐU]UEH8E$nt E$UEH8E$>t E$jUEH8E$t E$:UVS0E$%EhyE(D$ E$D$E D$ED$ED$ED$ ED$E D$E$yӉƋE$ډ$0[^]ÐUS$MUE]\$]\$L$ T$U T$$Et$[]UEU T$$@E8ÐUEU T$$dUWVSL$Ë}uM U]ԋEEED$|$t$ L$T$Eԉ$0؃L[^_]É։lj$$UE8E$t E$UE8E$Xt E$dUVSE$?E|E0$*E4D$$E D$E$IӉƋE4$:ӉƋE0$,ډӉƋE$ډ$[^]US$EXED$UT$UT$ UT$U T$$D$E$Ӄ$[]UVS0`vD$E$p`vD$E$\D$ED$ ED$D$E$UÍE$NE$C؃0[^]ÉӉƍE$+ӉƍE$ډ$UVSEU T$$FEuE$ӉƋE$3ډ$w[^]UE$E3UE3E$t E$&UE3E$Zt E$UE4E$ t E$UE4E$t E$UE;E$t E$fUE;E$t E$6ÐU]Ít&'UWVSO9@?)t$1ED$E D$E$9rރ[^_]Ë$ÐUSntnfЋu[]ÐUS[ì?Y[your program2.8 (no debug,Unicode,compiler with C++ ABI 1002,wx containers,compatible with 2.6)Platinum Arts: SandboxLaunch - FPSLaunch - RPGLaunch - SSPLaunch - MOCLaunch - KRSAboutClosePrefrencesFileEdit#4F5049Detected Resoultion: %ix%ibin/sandbox_client_32_fpsbin/sandbox_client_32_rpgbin/sandbox_client_32_sspbin/sandbox_client_32_mocbin/sandbox_client_32_krsD;t..(H8XHHX88X(x(x8 *8;./(hhX# #xH~%XxX6 f 8 h!!2!h@!R!n!~!!"$xX8H!h(X!x"X"""","xx2"xj"x""H8xH"h(XH8J#""H"h"#8H$HH"(xH(X#(x(f#l#v#hX8hHr$8$X$,$x8$$$Xh$X8H$Xh$h;H,6,(+|+;0*`*(hXXxX 6 f 8 h!!h2!h@!R!n!~!!(xXH!h(X!x"X"""","xxxj"x""H8xH"h(XH""(J#""H)h"#Xh8H8"H(X#(x(f#l#v#h~))));'8'^''.(n((>);T4/d/Z8Launcher|,;Ht|P;}5Entry14wxMenuItemList|W;}12wxButtonBase|t;Hut;13wxTransform2D|;@u20wxThreadHelperThread;($:@dXRfz,HddHd"6x (D`|DXv$@|6Lr,Hd#0:F T( ^D d` x|  <$ J@ \ x 2 N j  < P< fX tt  8 4T Jp P V ` f  8 T p 44NPTl~L8VT`p|4P$l*D<XFtl"b2r8Tp$*4d4PlH:j$@>d: (D8`h|zPR|  0AB <$'AB X0KAB t` AB RAB FAB >AAB d+AB tAB tAB 8nAB TjAB pbAB `'AB lAB dAB fAB b0AB v%AB zPLR|  $`RSAB KxAB &AB AB AB v AB zEAB   AB <AB XAB tzAB c AB T AB B AB 2AB $ AB AB 8AB TAB pAB !AB AB  AB -AB GAB LAB G42XAB GPnDAB lAB AB 0AB G0AB GqAB GAB  AB 0AB LAB hAB AB AB AB  AB AB  AB ,AB HAB dAB  AB AB ~7AB HAB  AB v AB ,d AB HTAB dL AB :AB $AB  AB AB +AB G AB ( AB D *AB G` AB | AB  AB  AB  AB  SAB K AB , AB H AB d *AB  AB  -AB G AB  AB  AB  AB ( AB D AB  0 SAB K ,AB G AB  AB  3AB G FAB H F3AB 0 ^AB L %AB h %AB  AB  R?AB G v?AB G AB  ?AB G 2?AB G, V AB H D@AB d hAB  hAB  RAB  <AB  & AB  0AB  (0AB (<0AB   PSAB KhDAB P#AB AB  pSAB M*0AB >0AB  RSAB K<RAB N ( TAB T L RTAB RAB  ̵W(TAB U AB AB  8TAB T ^QTAB W 0ȾfTAB M T \UAB T xUAB TVAB NAB FAB  >AB <6AB X.AB t.AB AB AB TAB 0AB 0AB 0AB 80AB T0AB p0AB AB )0F /Ev "Ae{ Zaw IXk;lMT+Tz )0F 0?Rkx        wF+?Y|/NOVaUOVaU0      00I0b05x6666  <0o0` P7 o@ooonN^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~.>N^n~GCC: (Ubuntu 4.4.1-4ubuntu8) 4.4.1GCC: (Ubuntu 4.4.1-4ubuntu9) 4.4.1"!bu_IO_stdin_used^../sysdeps/i386/elf/start.S/build/buildd/eglibc-2.10.1/csuGNU AS 2.203}[o b]q?intXxId0O%% $ > $ > $ > 4: ; I?  &IW2 ../sysdeps/i386/elfstart.S3!4=%" YZ!"\[# init.c/build/buildd/eglibc-2.10.1/csushort unsigned intGNU C 4.4.1short int_IO_stdin_usedlong long unsigned intunsigned charinit.clong long int.symtab.strtab.shstrtab.interp.note.ABI-tag.note.gnu.build-id.gnu.hash.dynsym.dynstr.gnu.version.gnu.version_r.rel.dyn.rel.plt.init.text.fini.rodata.eh_frame_hdr.eh_frame.gcc_except_table.ctors.dtors.jcr.dynamic.got.got.plt.data.bss.comment.debug_aranges.debug_pubnames.debug_info.debug_abbrev.debug_line.debug_strTT#hh 1$H Do00 N V``0P7^og0kojz k l@ u088uЅl*<0<`0`k ;̻,@Sbn nnn@oo, t @t(x 0(Fp %-9_GS0^h#%C hKTh0`    8 <0`0;@Snnnnoo t@t !"n!n/n<Rao`{nSn0T33383L3k333330 nn/oEnNhZ "Xh@tx=r"6,0"#L"GLHt !b "'"`t, A"#:t_*"2;!bX"1^(+D" 83HlXhf#"@8!""JgD+",0" <0 /* S s   "   " * !"Y ;!t  !"  ( 8'%"% 8b "x H X 0 )" h5 x     D #"f   ;! t L"(tL!"k(:8jt!H`*0")"X T"6P;!Ahqxt %"9"J q"s.R".0"*f! "X#"(?"#t,!U" u !$" @u!#(v# "GpD" 8H6Xe,$"J#"Hu !4,!hx"r$"LX+#"mF`u!" "*f 0"K""q"j"""$ ";c"wu "&.(?"Tr>)?"(H$"h-"" "$"H,XXh xu"<a; !KuD; !%(Nt!""K""^'"(BHrh ) N    &!(t-!b!!'?"!! "+" "U"8|"H"X"h#\-"=#g#####$ $;!4$|$ut!$ $$D"$'%"$`0$%>%\%""% v@!%`v%(%8"&HP& -R"&X&v,&h&x&'T'"o''*0"'n("'(v!/(2"7"Z(u(" "(""((*)Z)) ")V&3")" ") "*$";***(*8+HE+X+`y!+h++|t!+,E,/ZU,{,,,-+-^-~!"--~%,"--(.6 0"2.8[.Hx..|.Z0".8; !.:0!.""/X7/hc/x///t.0"/0=0W0g0000$"0W1f,"1 1+p"Y111(18 2|,!@2Hs2X22x2)@"2"3|!"33{33\'"3|3404)"F4$fc444$ "4}!4'50*0"=5&F"a54/0"5|+"5""56<6h6(6*"6t;!6"68%7HL7} !f7)"7X7B"7.0"7@}@!7B8xs8"+"88 #*"893!9} !.9; !A9\9}u99  "9h; !9:<:c::$":::#"!;3;"D;#"};8;H;X<h?<nL<x<< t <<$"=".=>"?=d=$tq===R!"=>@>@!"c>>>?(/?8$!D?8?d/0"?/0"?p"?},!?'@R"D@Xs@h@x@&" A) "5A"[Ax" "AA%"An!"A$"B2BkBl# "BB$-"B3CQCH$*"CC%"CD8DDD8DHDX"E>E~) "`EEW;!ETExF""(F,""KF! "mFFF&"F"" "FG%3"1Gd0@G !XGzE"GGX."GGH@H`"VHH0"HnHH2!"IZ.I[I}II8IIH'JXaJhJxJJ,; ! K4KWKinit.ccrtstuff.c__CTOR_LIST____DTOR_LIST____JCR_LIST____do_global_dtors_auxcompleted.6990dtor_idx.6992frame_dummy__CTOR_END____FRAME_END____JCR_END____do_global_ctors_auxmain.cpp_ZStL8__ioinit_Z41__static_initialization_and_destruction_0ii_ZL15wxInvalidOffset_ZL5wxEOF_ZL19wxALPHA_TRANSPARENT_ZL14wxALPHA_OPAQUE_ZL25wxIMAGE_ALPHA_TRANSPARENT_ZL23wxIMAGE_ALPHA_THRESHOLD_ZL20wxIMAGE_ALPHA_OPAQUE_ZL20wxPRINTMEDIA_DEFAULT_ZL21wxOutOfRangeTextCoord_ZL18wxInvalidTextCoord_GLOBAL__I__Z11wxCreateAppv__init_array_end__init_array_start_GLOBAL_OFFSET_TABLE__DYNAMIC_ZN8wxWindowC2Ev@@WXU_2.8_ZN20wxThreadHelperThread5EntryEv_ZN7wxFrame12SetStatusBarEP11wxStatusBar@@WXU_2.8_ZNK11wxFrameBase13GetEventTableEv@@WXU_2.8wxDefaultSize@@WXU_2.8_ZN8wxWindow18SetLayoutDirectionE17wxLayoutDirection@@WXU_2.8_ZNK12wxWindowBase17GetSizeConstraintEPiS0_@@WXU_2.8_ZN12wxWindowBase22TransferDataFromWindowEv@@WXU_2.8_ZN10wxListBaseD2Ev@@WXU_2.8_ZN12wxAppConsole10CallOnInitEv_ZN14wxMenuItemListD0Ev_ZN9wxAppBase12CreateTraitsEv@@WXU_2.8_ZNK12wxWindowBase13GetClientSizeEvmain_ZTI7wxFrame@@WXU_2.8_ZN12wxAppConsole22SetInitializerFunctionEPFPS_vE_ZN8wxStringC1EPKwwxStaticTextNameStr@@WXU_2.8_ZNK12wxWindowBase9DoHitTestEii@@WXU_2.8__libc_start_main@@GLIBC_2.0_ZN12wxStringBaseC2ERKS__ZN5wxAppC2Ev@@WXU_2.8wxEVT_COMMAND_MENU_SELECTED@@WXU_2.8_ZN8wxButtonC1EP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelRK11wxValidatorS4__ZN8Launcher11OpenGameRpgEv_ZTV20wxThreadHelperThread_ZN19wxTopLevelWindowGTK8MaximizeEb@@WXU_2.8_ZNK12wxWindowBase11GetBestSizeEv_ZNK12wxWindowBase13DoGetBestSizeEv@@WXU_2.8_ZN7wxFrame13CreateToolBarEliRK8wxString@@WXU_2.8_ZN19wxTopLevelWindowGTK9DoSetSizeEiiiii@@WXU_2.8_ZN20wxwxMenuItemListNodeC1EP10wxListBasePS_S2_P10wxMenuItemRK9wxListKey_ZN8wxWindow14DoReleaseMouseEv@@WXU_2.8_ZN12wxWindowBase12SetValidatorERK11wxValidator@@WXU_2.8_ZN12wxWindowBase7DoPhaseEi@@WXU_2.8_ZN8wxWindow18DoApplyWidgetStyleEP11_GtkRcStyle@@WXU_2.8_start_ZN8wxWindow15FixUpMouseEventEP10_GtkWidgetRiS2__ZTV12wxButtonBase_ZN12wxWindowBase31GetMainWindowOfCompositeControlEv_ZN10wxMenuBaseD2Ev@@WXU_2.8_ZN12wxStringBaseC2EPKw_ZN19wxTopLevelWindowGTK7AddGrabEv@@WXU_2.8_ZN11wxFrameBase13SendSizeEventEv@@WXU_2.8_ZN14wxMenuItemListD1Ev_ZN8wxWindow9DoSetSizeEiiiii@@WXU_2.8_fini__libc_csu_fini_ZN19wxTopLevelWindowGTK4ShowEb@@WXU_2.8_ZN10wxMenuBase4InitEl@@WXU_2.8_ZN8wxColourD1Ev@@WXU_2.8_ZNK9wxAppBase8IsActiveEv_ZNK8wxWindow15GTKProcessEventER7wxEvent@@WXU_2.8_ZN12wxWindowBase10SetMaxSizeERK6wxSize_ZN8wxWindow7RefreshEbPK6wxRect@@WXU_2.8_ZNK12wxWindowBase24AcceptsFocusFromKeyboardEv_ZTS20wxThreadHelperThread_ZN12wxWindowBase8NavigateEi@@WXU_2.8_ZNK12wxWindowBase9IsEnabledEv_ZN12wxEvtHandler12ProcessEventER7wxEvent@@WXU_2.8_ZN9wxAppBase8DispatchEv@@WXU_2.8_ZN13wxTransform2DD0Ev_ZN12wxAppConsole13OnCmdLineHelpER15wxCmdLineParser@@WXU_2.8_ZN12wxStringBaseC2Ev_ZNK8wxObject12GetClassInfoEv@@WXU_2.8_ZN7wxFrame13DetachMenuBarEv@@WXU_2.8__i686.get_pc_thunk.bx_ZN12wxButtonBase13SetImageLabelERK8wxBitmap_ZN12wxWindowBase12LayoutPhase1EPi@@WXU_2.8_ZNK12wxWindowBase18GetHelpTextAtPointERK7wxPointN11wxHelpEvent6OriginE@@WXU_2.8memmove@@GLIBC_2.0_ZNK12wxWindowBase23GetClientSizeConstraintEPiS0_@@WXU_2.8_ZNK8wxWindow12AcceptsFocusEv@@WXU_2.8_ZN12wxWindowBase3FitEv@@WXU_2.8_ZNK9wxControl12GetClassInfoEv@@WXU_2.8_ZN8wxWindow8SetLabelERK8wxString_ZN8wxWindow22GTKWidgetDoSetMnemonicEP10_GtkWidget@@WXU_2.8_ZN12wxWindowBase16DoSetVirtualSizeEii@@WXU_2.8_ZTS13wxTransform2D__data_start_ZNK12wxStringData7IsEmptyEv__bss_start_ZN8wxWindow12ScrollWindowEiiPK6wxRect@@WXU_2.8_ZN18wxAcceleratorTableaSERKS__ZN12wxWindowBase10GetCaptureEv@@WXU_2.8_ZN8Launcher12SetupButtonsEP7wxPanel_ZN7wxFrame6CreateEP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelS4_@@WXU_2.8_ZN8wxWindow12ApplyToolTipEP12_GtkTooltipsPKw@@WXU_2.8_ZNK12wxWindowBase16DoGetVirtualSizeEv@@WXU_2.8_ZTV20wxwxMenuItemListNode@@WXU_2.8_ZNK7wxFrame15DoGetClientSizeEPiS0_@@WXU_2.8_ZN12wxButtonBaseD0Ev_ZN12wxButtonBase15SetImageMarginsEii_ZN12wxWindowBase10InitDialogEv@@WXU_2.8_ZN8wxThread6OnExitEv_ZTS5Entry_ZN7wxFrame13AttachMenuBarEP9wxMenuBar@@WXU_2.8_ZN19wxTopLevelWindowGTK14DoSetSizeHintsEiiiiii@@WXU_2.8_ZNK8wxObject13CreateRefDataEv@@WXU_2.8_ZN8wxWindow11RemoveChildEP12wxWindowBase@@WXU_2.8wxDefaultPosition@@WXU_2.8_ZN12wxPoint2DIntC1ERKS__ZN8wxStringC1Ev_ZNK12wxWindowBase18GetBestVirtualSizeEv_ZN19wxTopLevelWindowGTK8IsActiveEv@@WXU_2.8_ZN8wxWindow8SetFocusEv@@WXU_2.8_ZN6wxMenuC1ElwxTheAppInitializer_ZNK8wxWindow24AdjustForLayoutDirectionEiii@@WXU_2.8_ZN8LauncherD1Ev_ZNK20wxTopLevelWindowBase16DoScreenToClientEPiS0_@@WXU_2.8_ZN12wxWindowBase19SetAcceleratorTableERK18wxAcceleratorTable_ZN10wxListBase4InitE9wxKeyType@@WXU_2.8_ZN8wxWindow14OnParentEnableEb_ZNK13wxTransform2D16InverseTransformERK12wxPoint2DInt_ZTVN10__cxxabiv117__class_type_infoE@@CXXABI_1.3_ZNK10wxListBase4FindERK9wxListKey@@WXU_2.8_ZN12wxAppConsole20OnUnhandledExceptionEv_ZN9wxAppBase7PendingEv@@WXU_2.8_ZTV10wxListBase@@WXU_2.8_ZNK19wxTopLevelWindowGTK9IsGrabbedEv_ZTI8wxThread@@WXU_2.8_end_ZNK8wxWindow13IsRadioButtonEv_ZNK9wxControl13DoGetBestSizeEv@@WXU_2.8_ZN12wxWindowBase12SetSizeHintsEiiiiii__gmon_start___ZN19wxTopLevelWindowGTK8SetTitleERK8wxString@@WXU_2.8_ZN8Launcher6onInfoER14wxCommandEvent_ZN11wxFrameBase10DoGiveHelpERK8wxStringb@@WXU_2.8_ZNK8wxWindow16DoClientToScreenEPiS0_@@WXU_2.8_ZNK20wxTopLevelWindowBase9IsVisibleEv_ZNK8wxWindow9GetHandleEv_ZTI9wxControl@@WXU_2.8_ZTV8Launcher_ZNK8wxWindow16DoScreenToClientEPiS0_@@WXU_2.8_ZN9wxAppBase12ExitMainLoopEv@@WXU_2.8_ZNK19wxTopLevelWindowGTK12IsFullScreenEv_ZN14wxMenuItemListC1E9wxKeyType_ZN11wxFrameBase13SetStatusTextERK8wxStringi@@WXU_2.8_ZNK8wxWindow14GetScrollRangeEi@@WXU_2.8_ZN8Launcher11OpenGameSspEv_ZTV11wxGDIObject@@WXU_2.8_ZNK12wxWindowBase16HasMultiplePagesEv_ZNK12wxWindowBase10GetMaxSizeEv_ZN12wxWindowBase16DissociateHandleEv_ZN8wxWindow15DoSetClientSizeEii@@WXU_2.8_ZN12wxStringBase4InitEv_ZNK12wxWindowBase18GetBackgroundStyleEv_ZN7wxFrame15CreateStatusBarEiliRK8wxString@@WXU_2.8_ZNK20wxTopLevelWindowBase10IsTopLevelEv_ZN8wxWindow14DoCaptureMouseEv@@WXU_2.8_ZN8wxStringC1ERKS__ZN12wxAppConsole14ms_appInstanceE@@WXU_2.8_ZNK8wxWindow13GetCharHeightEv@@WXU_2.8_ZNK12wxWindowBase19DoGetScreenPositionEPiS0_@@WXU_2.8_ZNK12wxStringBase13GetStringDataEv_ZNK13wxTransform2D9TransformERK11wxRect2DInt_ZN9wxAppBase4ExitEv@@WXU_2.8_ZN10wxNodeBaseC2EP10wxListBasePS_S2_PvRK9wxListKey@@WXU_2.8_ZN19wxTopLevelWindowGTK8SetShapeERK8wxRegion@@WXU_2.8_ZNK13wxTransform2D16InverseTransformERK11wxRect2DInt_ZN12wxWindowBase12LayoutPhase2EPi@@WXU_2.8_ZNK11wxFrameBase10GetMenuBarEv_ZNK12wxWindowBase7GetNameEv_ZN8wxObject3RefERKS_@@WXU_2.8_ZNK12wxWindowBase20ShouldInheritColoursEv_ZN11wxFrameBase15PositionMenuBarEv_ZN9wxAppBase13OnInitCmdLineER15wxCmdLineParser@@WXU_2.8_ZN19wxTopLevelWindowGTK7RestoreEv@@WXU_2.8_ZNK12wxWindowBase17GetEventHashTableEv@@WXU_2.8_Z8wxGetAppv_ZN8wxWindow18SetBackgroundStyleE17wxBackgroundStyle@@WXU_2.8_ZN12wxAppConsole12ms_appInitFnE@@WXU_2.8_ZN8wxStringD1Ev_ZN20wxTopLevelWindowBase7DestroyEv@@WXU_2.8_ZN5wxApp10InitializeERiPPw@@WXU_2.8_ZNK8wxWindow13GetTextExtentERK8wxStringPiS3_S3_S3_PK6wxFont@@WXU_2.8_ZN11wxFrameBase10SetMenuBarEP9wxMenuBar@@WXU_2.8_ZdlPv@@GLIBCXX_3.4_ZN8Launcher4ResXEv_ZTI20wxThreadHelperThread_ZN12wxEvtHandler9TryParentER7wxEvent@@WXU_2.8_ZN7wxFrame17PositionStatusBarEv@@WXU_2.8_ZNK8wxWindow12GTKGetWindowER17wxArrayGdkWindows@@WXU_2.8_ZTI5Entry_ZN19wxTopLevelWindowGTK14SetTransparentEh@@WXU_2.8_ZN19wxTopLevelWindowGTK17EnableCloseButtonEb@@WXU_2.8_ZN9wxControl14OnInternalIdleEv@@WXU_2.8_ZN8Launcher6onExitER14wxCommandEvent_ZNK12wxWindowBase7IsShownEv_ZN12wxWindowBase10SetMinSizeERK6wxSize_ZN12wxStringData6UnlockEv_ZNK12wxWindowBase16GetWindowVariantEv_ZNK13wxTransform2D9TransformEP11wxRect2DInt_ZN8wxThreadD2Ev@@WXU_2.8_ZN12wxWindowBase17InheritAttributesEv@@WXU_2.8_Znwj@@GLIBCXX_3.4_ZN11wxFrameBase15OnCreateToolBarEliRK8wxString@@WXU_2.8_ZN22wxSystemSettingsNative9GetMetricE14wxSystemMetricP8wxWindow@@WXU_2.8__gxx_personality_v0@@CXXABI_1.3_ZN8wxThread11TestDestroyEv@@WXU_2.8_ZN13wxControlBase16DoUpdateWindowUIER15wxUpdateUIEvent@@WXU_2.8_ZN8wxWindow19SetForegroundColourERK8wxColour@@WXU_2.8_ZNK12wxWindowBase21GetPositionConstraintEPiS0_@@WXU_2.8_ZN12wxWindowBase9MakeModalEb@@WXU_2.8_edata_ZN19wxTopLevelWindowGTK14ShowFullScreenEbl@@WXU_2.8_ZN9wxAppBase11ProcessIdleEv@@WXU_2.8_ZNK13wxTransform2D9TransformERK12wxPoint2DInt_ZNK5wxApp12GetClassInfoEv@@WXU_2.8_ZN12wxAppConsole11FilterEventER7wxEvent@@WXU_2.8_ZN11wxFrameBaseC2Ev@@WXU_2.8_ZN12wxEvtHandler12TryValidatorER7wxEvent_ZN7wxFrame14OnInternalIdleEv@@WXU_2.8_ZN19wxTopLevelWindowGTK5RaiseEv@@WXU_2.8_ZN12wxEvtHandler15DoSetClientDataEPv@@WXU_2.8_ZN8wxWindow16DoMoveInTabOrderEPS_N12wxWindowBase8MoveKindE@@WXU_2.8_ZN10wxMenuBase15AppendSeparatorEv_ZN12wxStringBase8InitWithEPKwjj@@WXU_2.8_ZN8wxWindow7SetFontERK6wxFont@@WXU_2.8_ZN7wxFrame15DoSetClientSizeEii@@WXU_2.8_ZN8wxWindow4ShowEb@@WXU_2.8_ZN8Launcher4ResYEv_ZN12wxEvtHandlerD2Ev@@WXU_2.8_Unwind_Resume@@GCC_3.0_ZTI13wxTransform2D_ZN20wxTopLevelWindowBase16DoUpdateWindowUIER15wxUpdateUIEvent@@WXU_2.8_ZTV6wxMenu@@WXU_2.8_Jv_RegisterClasses_ZNSt8ios_base4InitD1Ev@@GLIBCXX_3.4_ZN11wxGDIObjectC2Ev_ZN13wxTransform2DD1Ev_fp_hw_ZN7wxFrameD2Ev@@WXU_2.8_ZNK9wxAppBase12GetTopWindowEv@@WXU_2.8_ZN8wxWindow5RaiseEv@@WXU_2.8_ZN12wxWindowBase15AssociateHandleEP10_GtkWidget_ZTV8wxColour@@WXU_2.8wxEmptyString@@WXU_2.8_ZNK8wxObject12CloneRefDataEPK15wxObjectRefData@@WXU_2.8_ZNK8wxWindow15DoGetClientSizeEPiS0_@@WXU_2.8_ZN8wxWindow11DoPopupMenuEP6wxMenuii@@WXU_2.8_ZN10wxMenuBase6AppendEiRK8wxStringS2_10wxItemKind_ZN12wxAppConsole20ProcessPendingEventsEv@@WXU_2.8wxDefaultValidator@@WXU_2.8_ZN12wxWindowBase8ValidateEv@@WXU_2.8_ZN20wxTopLevelWindowBase8DoCentreEi@@WXU_2.8_ZN13wxControlBase7SetFontERK6wxFont@@WXU_2.8_ZNK12wxStringBase5emptyEv_ZNK9wxControl20GetDefaultAttributesEv@@WXU_2.8_ZN12wxButtonBaseD2Ev_ZNK13wxTransform2D16InverseTransformEP11wxRect2DInt_ZN12wxWindowBase9TryParentER7wxEvent@@WXU_2.8_ZTV7wxPanel@@WXU_2.8_ZNK12wxWindowBase20GetDefaultAttributesEv_ZN6wxMenu4InitEv@@WXU_2.8_ZN12wxWindowBase17CanSetTransparentEv_ZN12wxWindowBase6FreezeEv_ZN7wxPanel6CreateEP8wxWindowiRK7wxPointRK6wxSizelRK8wxString@@WXU_2.8_ZNK8wxWindow13DoGetPositionEPiS0_@@WXU_2.8_ZNK12wxWindowBase16GetDefaultBorderEv@@WXU_2.8_ZN19wxTopLevelWindowGTK8SetIconsERK12wxIconBundle@@WXU_2.8_ZN12wxAppConsole11GetInstanceEv_ZN11wxRect2DIntC1ERKS__ZNK12wxWindowBase13GetDropTargetEv_ZN12wxWindowBase7SetNameERK8wxString_ZNK11wxFrameBase12GetStatusBarEv_ZN12wxEvtHandler7ConnectEiiiM8wxObjectFvR7wxEventEPS0_PS_@@WXU_2.8_ZN9wxAppBase6OnExitEv@@WXU_2.8_ZN12wxWindowBase18DoSetWindowVariantE15wxWindowVariant@@WXU_2.8_ZN19wxTopLevelWindowGTK10RemoveGrabEv@@WXU_2.8_ZN8wxWindow13SetDropTargetEP12wxDropTarget@@WXU_2.8_ZN9wxAppBase15OnCmdLineParsedER15wxCmdLineParser@@WXU_2.8_ZTV8wxButton@@WXU_2.8_ZNK19wxTopLevelWindowGTK10IsIconizedEv@@WXU_2.8_ZN8wxWindowD2Ev@@WXU_2.8_ZTV10wxMenuBase@@WXU_2.8_ZN8wxWindow7DestroyEv@@WXU_2.8_ZNK8wxWindow14GetScrollThumbEi@@WXU_2.8__libc_csu_init_ZN12wxWindowBase8DoCentreEi@@WXU_2.8_ZN12wxEvtHandlerC2Ev@@WXU_2.8_ZNK20wxTopLevelWindowBase17IsAlwaysMaximizedEv@@WXU_2.8_ZN12wxWindowBase14MoveConstraintEii@@WXU_2.8_ZNK9wxAppBase14GetDisplayModeEv@@WXU_2.8_ZNK12wxWindowBase19GetClientAreaOriginEv@@WXU_2.8_ZN12wxWindowBase15SetFocusFromKbdEv_ZN5wxApp5YieldEb@@WXU_2.8_ZNK7wxFrame19GetClientAreaOriginEv_ZN8wxWindow11ScrollPagesEi@@WXU_2.8_ZN8wxWindow16GetConnectWidgetEv@@WXU_2.8_ZNK12wxWindowBase10GetMinSizeEv_ZNK5wxApp17GetEventHashTableEv@@WXU_2.8_ZN5wxApp7CleanUpEv@@WXU_2.8_ZN8LauncherC2ERK8wxStringRK7wxPointRK6wxSizewxEVT_COMMAND_BUTTON_CLICKED@@WXU_2.8_ZN8wxObjectD2Ev_ZTI8Launcher_ZTV13wxTransform2D_ZN12wxWindowBase4ThawEv_ZN8wxWindow6UpdateEv@@WXU_2.8_ZN8wxWindow18SetWindowStyleFlagEl@@WXU_2.8_ZN8wxWindow11WarpPointerEii@@WXU_2.8_ZN7wxFrame9GtkOnSizeEv@@WXU_2.8_ZN12wxEvtHandler17DoSetClientObjectEP12wxClientData@@WXU_2.8_ZN5EntryD1Ev_ZN12wxWindowBase6LayoutEv@@WXU_2.8_ZNK9wxControl8GetLabelEv@@WXU_2.8__cxa_atexit@@GLIBC_2.1.3free@@GLIBC_2.0_ZN8wxWindow12DoMoveWindowEiiii@@WXU_2.8_ZN19wxTopLevelWindowGTK18SetWindowStyleFlagEl@@WXU_2.8_ZN5Entry6OnInitEv_ZN8wxStringaSERKS__Z11wxCreateAppv_ZN10wxMenuBaseC2El_init_ZN14wxMenuItemList10CreateNodeEP10wxNodeBaseS1_PvRK9wxListKey_ZN19wxTopLevelWindowGTK17CanSetTransparentEv@@WXU_2.8_ZN12wxAppConsole17CheckBuildOptionsEPKcS1_@@WXU_2.8_ZN5wxApp10WakeUpIdleEv@@WXU_2.8_ZN8wxWindow11ScrollLinesEi@@WXU_2.8_ZTVN10__cxxabiv120__si_class_type_infoE@@CXXABI_1.3_ZN12wxWindowBase17SetSizeConstraintEiiii@@WXU_2.8_ZN7wxFrame10SetToolBarEP9wxToolBar@@WXU_2.8_ZN8wxString6FormatEPKwz@@WXU_2.8_ZNK8wxWindow11DoIsExposedEiiii@@WXU_2.8_ZN9wxControlD2Ev_ZNK12wxStringBase6lengthEv_ZN12wxColourBase3SetEPKw_ZN12wxWindowBase25GetClassDefaultAttributesE15wxWindowVariant@@WXU_2.8_ZN12wxWindowBase14DoSetSizeHintsEiiiiii@@WXU_2.8_ZN12wxStringData4LockEvwxFrameNameStr@@WXU_2.8_ZN8wxWindow12DoSetToolTipEP9wxToolTip@@WXU_2.8_ZN12wxStringBaseaSERKS_@@WXU_2.8_ZN12wxButtonBaseC2Ev_ZN8Launcher12SetupMenuBarEv_ZN13wxControlBaseD2Ev@@WXU_2.8_ZNK12wxWindowBase13GetEventTableEv@@WXU_2.8_ZNK20wxTopLevelWindowBase20ShouldPreventAppExitEv_ZTV8wxObject@@WXU_2.8_ZN9wxAppBase9SetActiveEbP8wxWindow@@WXU_2.8_ZN12wxButtonBaseD1Ev_ZNK11wxRect2DInt14GetRightBottomEv_ZN20wxThreadHelperThreadD1Ev_ZNK14wxMenuItemList4FindERK9wxListKey_ZN12wxWindowBase14SetTransparentEh_ZN11wxFrameBase17OnCreateStatusBarEiliRK8wxString@@WXU_2.8_ZN13wxControlBase7CommandER14wxCommandEvent@@WXU_2.8_ZN19wxTopLevelWindowGTK7IconizeEb@@WXU_2.8_ZN12wxWindowBase20TransferDataToWindowEv@@WXU_2.8_ZN9wxAppBase12SetPrintModeEi_ZTS12wxButtonBase_ZN9wxAppBase12SetTopWindowEP8wxWindow_ZN11wxFrameBase13DoMenuUpdatesEP6wxMenu@@WXU_2.8_ZNK8wxWindow9DoGetSizeEPiS0_@@WXU_2.8_ZTI10wxListBase@@WXU_2.8_ZN12wxButtonBase10SetDefaultEv_ZN12wxWindowBase9FitInsideEv@@WXU_2.8_ZN8wxObjectC2Ev_ZN5EntryD0Ev_ZTV12wxColourBase@@WXU_2.8_ZN8wxButton6CreateEP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelRK11wxValidatorS4_@@WXU_2.8_ZNK8wxWindow22GTKWidgetNeedsMnemonicEv@@WXU_2.8_ZNK12wxWindowBase27GetWindowSizeForVirtualSizeERK6wxSize_ZN8wxWindow6EnableEb@@WXU_2.8_ZNK8wxWindow8GetLabelEv_ZN8wxWindow16ApplyWidgetStyleEb@@WXU_2.8_ZTV5Entry_ZTI5wxApp@@WXU_2.8_ZTI12wxButtonBase_ZN9wxControlC2Ev@@WXU_2.8wxButtonNameStr@@WXU_2.8__cxa_pure_virtual@@CXXABI_1.3_ZN9wxAppBase14SetDisplayModeERK11wxVideoMode_ZTI14wxMenuItemList_ZN18wxControlContainerC1EP8wxWindow@@WXU_2.8_ZN8wxWindow19SetBackgroundColourERK8wxColour@@WXU_2.8_ZNK8wxWindow12GetScrollPosEi@@WXU_2.8_ZN19wxTopLevelWindowGTK12DoMoveWindowEiiii@@WXU_2.8_ZN11wxFrameBase15PositionToolBarEv_ZN8wxWindow5LowerEv@@WXU_2.8_ZN5wxAppD2Ev@@WXU_2.8_ZN12wxWindowBase18SetInitialBestSizeERK6wxSizesystem@@GLIBC_2.0_ZN8wxColourC1Ev_ZN7wxPanelC1EP8wxWindowiRK7wxPointRK6wxSizelRK8wxString_ZN9wxAppBase21OnExceptionInMainLoopEv@@WXU_2.8_ZN19wxTopLevelWindowGTK7SetIconERK6wxIcon@@WXU_2.8_ZN20wxTopLevelWindowBase10SetMinSizeERK6wxSize@@WXU_2.8_ZNK8wxWindow10IsRetainedEv@@WXU_2.8__DTOR_END___ZNK11wxFrameBase11IsOneOfBarsEPK8wxWindow@@WXU_2.8_ZNK7wxFrame12GetClassInfoEv@@WXU_2.8data_start_ZN12wxWindowBase18SetConstraintSizesEb@@WXU_2.8_ZN7wxFrameC2EP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelS4__ZN6wxSizeC1Eii_ZN7wxPointC1Eii_ZNSt8ios_base4InitC1Ev@@GLIBCXX_3.4__dso_handle_ZN5wxApp9OnInitGuiEv@@WXU_2.8_Z7wxEntryRiPPc@@WXU_2.8_ZN12wxWindowBase15SetThemeEnabledEb_ZN20wxTopLevelWindowBase26GetRectForTopLevelChildrenEPiS0_S0_S0_@@WXU_2.8_ZNK8wxWindow12GetCharWidthEv@@WXU_2.8_ZN12wxWindowBase13SetExtraStyleEl_ZN12wxEvtHandler16SearchEventTableER12wxEventTableR7wxEvent@@WXU_2.8_ZN12wxWindowBase12TryValidatorER7wxEvent@@WXU_2.8_ZN8wxWindow15ClearBackgroundEv@@WXU_2.8_ZNK12wxWindowBase10IsTopLevelEv@@WXU_2.8_ZTV14wxMenuItemList_ZN20wxTopLevelWindowBase11RemoveChildEP12wxWindowBase@@WXU_2.8_ZN20wxThreadHelperThreadD0Ev_ZN8LauncherD0Ev_ZN12wxStringBaseD2Ev_ZTV7wxFrame@@WXU_2.8_ZN14wxMenuItemBase3NewEP6wxMenuiRK8wxStringS4_10wxItemKindS1_@@WXU_2.8_ZN10wxListBaseC2E9wxKeyType_ZN8wxWindow8AddChildEP12wxWindowBase@@WXU_2.8_ZNK11wxFrameBase17GetEventHashTableEv@@WXU_2.8_ZN9wxAppBase14SendIdleEventsEP8wxWindowR11wxIdleEvent@@WXU_2.8_ZN11wxRect2DIntC1ERK12wxPoint2DIntS2__ZNK12wxButtonBase20ShouldInheritColoursEv_ZN12wxAppConsole16OnFatalExceptionEv_ZN12wxWindowBase24HasTransparentBackgroundEv_ZNK12wxEvtHandler17DoGetClientObjectEv@@WXU_2.8_ZN12wxPoint2DIntC1Eii_ZNK12wxWindowBase15GetThemeEnabledEv_ZNK11wxFrameBase10GetToolBarEv_ZN9wxMenuBarC1Ev@@WXU_2.8_ZN20wxTopLevelWindowBase10SetMaxSizeERK6wxSize@@WXU_2.8_ZNK8wxWindow21IsTransparentForMouseEv_ZN11wxFrameBase15SetStatusWidthsEiPKi@@WXU_2.8_ZNK19wxTopLevelWindowGTK8GetTitleEv_ZNK12wxAppConsole11HandleEventEP12wxEvtHandlerMS0_FvR7wxEventES3_@@WXU_2.8_ZN11wxFrameBaseD2Ev@@WXU_2.8_ZNK20wxTopLevelWindowBase19DoGetScreenPositionEPiS0__ZN11wxFrameBase14UpdateWindowUIEl@@WXU_2.8_ZN8wxObjectaSERKS__ZNK20wxTopLevelWindowBase16DoClientToScreenEPiS0_@@WXU_2.8_ZN12wxWindowBase19SetVirtualSizeHintsEiiii@@WXU_2.8_ZN12wxStaticTextC1EP8wxWindowiRK8wxStringRK7wxPointRK6wxSizelS4_@@WXU_2.8_ZN7wxFrame4InitEv@@WXU_2.8_ZNK19wxTopLevelWindowGTK11IsMaximizedEv@@WXU_2.8_ZNK5wxApp13GetEventTableEv@@WXU_2.8_ZN9wxControl8SetLabelERK8wxString@@WXU_2.8_ZN8Launcher11OpenGameFpsEv_ZNK9wxControl15UseGTKStyleBaseEv_ZN12wxWindowBase14SetInitialSizeERK6wxSize@@WXU_2.8_ZTS14wxMenuItemList_ZN8LauncherC1ERK8wxStringRK7wxPointRK6wxSize_ZN8wxWindow8ReparentEP12wxWindowBase@@WXU_2.8_ZNK12wxWindowBase10HasCaptureEv_ZN12wxWindowBase9PrepareDCER4wxDC_ZN12wxWindowBase12GetValidatorEv_ZN9wxAppBase5OnRunEv@@WXU_2.8_ZNK12wxWindowBase15IsShownOnScreenEv@@WXU_2.8_ZNK6wxSize16IsFullySpecifiedEv_ZNK12wxWindowBase8IsFrozenEvwxPanelNameStr@@WXU_2.8_ZNK11wxRect2DInt10GetLeftTopEv_IO_stdin_used_ZTV9wxControl@@WXU_2.8_ZN12wxEvtHandler7ConnectEiiM8wxObjectFvR7wxEventEPS0_PS__ZN8wxWindow12SetScrollPosEiib@@WXU_2.8_ZN5EntryC1Ev_ZN8wxObject5UnRefEv@@WXU_2.8_ZNK9wxAppBase18GetLayoutDirectionEv@@WXU_2.8_ZN8wxWindow9SetCursorERK8wxCursor@@WXU_2.8_ZN12wxColourBaseC2Ev_ZNK12wxEvtHandler15DoGetClientDataEv@@WXU_2.8_ZN16wxAppInitializerC1EPFP12wxAppConsolevE_ZN8Launcher11OpenGameKrsEv_ZN7wxPanel4InitEv@@WXU_2.8_ZNK12wxWindowBase18GetWindowStyleFlagEv_ZN8Launcher11OpenGameMocEv_ZN12wxWindowBase14UpdateWindowUIEl@@WXU_2.8_ZN9wxAppBase8MainLoopEv@@WXU_2.8_ZN11wxRect2DIntaSERKS_@@WXU_2.8_ZN12wxAppConsole14OnCmdLineErrorER15wxCmdLineParser@@WXU_2.8_ZN12wxStringBase4nposE@@WXU_2.8_ZN8wxWindow12SetScrollbarEiiiib@@WXU_2.8_ZN19wxTopLevelWindowGTK20RequestUserAttentionEi@@WXU_2.8_ZNK12wxWindowBase19GetWindowBorderSizeEv@@WXU_2.8_ZNK8wxWindow11DoIsExposedEii@@WXU_2.8_ZNK12wxWindowBase27AdjustForParentClientOriginERiS0_i@@WXU_2.8_ZTS8Launcher_ZNK8wxWindow16IsDoubleBufferedEv@@WXU_2.8_ZN12wxWindowBase5CloseEb@@WXU_2.8_ZNK8wxWindow18GetLayoutDirectionEv@@WXU_2.8sandboxgamemaker-2.7.1+dfsg/src/0000775000175000017500000000000011660750521016444 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/pzlgame/0000775000175000017500000000000011660234752020106 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/pzlgame/pzlgame.h0000664000175000017500000000354611571424710021722 0ustar showardshoward#ifndef __KRSGAME_H__ #define __KRSGAME_H__ /* * Puzzle Games By: Dale Weiler (graphitemaster) * for use with sandbox and sandbox related projects or mods */ #include "cube.h" #define ENTSPAWNTIME 30000 // 30 seconds enum { NOTUSED = ET_EMPTY, // entity slot not in use in map LIGHT = ET_LIGHT, // lightsource, attr1 = radius, attr2 = intensity MAPMODEL = ET_MAPMODEL, // attr1 = angle, attr2 = idx PLAYERSTART, // attr1 = angle ENVMAP = ET_ENVMAP, // attr1 = radius PARTICLES = ET_PARTICLES, MAPSOUND = ET_SOUND, SPOTLIGHT = ET_SPOTLIGHT, MAXENTTYPES }; struct pzlentity : extentity{}; struct pzlchar : dynent { const char *name; int playerindex; bool attacking; editinfo *edit; pzlchar() : playerindex(0), attacking(false) { respawn(); } void respawn() { dynent::reset(); collidetype = COLLIDE_AABB; attacking = false; } }; enum pzlportaltype { PORTAL_BLUE, // in PORTAL_YELLOW // out }; struct pzlportal { pzlportal() : dist(1024), size(0030), dir (0, 0, 0), pos (0, 0, 0), o (0, 0, 0) {} void calc(pzlchar *d) { // calculate placement for decal dir = vec(d->yaw * RAD, d->pitch * RAD); o = d->o; raycubepos(o, vec(dir).normalize(), pos, dist, RAY_CLIPMAT|RAY_ALPHAPOLY); } float dist; // max distance for portal float size; // portal size vec dir; // direction vec pos; // position vec o; // start point }; namespace entities { extern vector ents; extern void renderentities(); extern void checkitems(pzlchar *d); extern void trypickup(int n, pzlchar *d); extern int lastpickupmillis; } namespace game { extern pzlchar *player1; extern void spawnplayer(pzlchar *d); extern bool intermission; extern int debug; } #endif sandboxgamemaker-2.7.1+dfsg/src/pzlgame/pzl.cpp0000664000175000017500000000775211571424710021426 0ustar showardshoward#include "pzlgame.h" using namespace entities; namespace game { string clientmap; const char *getclientmap() { return clientmap; } bool connected = false; bool intermission = false; void gamedisconnect(bool cleanup) {connected = false;} void gameconnect (bool remote) {connected = true; } VARP(debug, 0, 0, 1); SVARFP ( name, "unnamed", player1->name = newstring(name) ); VARFP ( playermodel, 0, 0, 1, player1->playerindex = playermodel ); pzlchar *player1 = new pzlchar (); // our player pzlportal portals[2]; pzlchar *spawnstate(pzlchar *d) { d->respawn(); return d; } // PORTALS ICOMMAND(portal_y, "", (), { portals[PORTAL_YELLOW].calc(player1); adddecal(2, portals[PORTAL_YELLOW].pos, vec(1, 1, 1), portals[PORTAL_YELLOW].size, bvec(255, 255, 000)); }); ICOMMAND(portal_b, "", (), { portals[PORTAL_BLUE].calc(player1); adddecal(2, portals[PORTAL_BLUE].pos, vec(1, 1, 1), portals[PORTAL_BLUE].size, bvec(000, 000, 255)); }); void spawnplayer(pzlchar *d) { findplayerspawn(d, -1, 0); spawnstate(d); d->state = d==player1 && editmode ? CS_EDITING : CS_ALIVE; } void respawnself() { if(paused || ispaused()) return; spawnplayer(player1); } bool canjump() { if(player1->state == CS_ALIVE) return true; return false; } void updateplayer() { checkitems(player1); moveplayer(player1, 10, true); } void updateworld() //main game update loop { if(!curtime) return; physicsframe(); updateplayer(); if(editmode) intermission = false; else disablezoom(); } bool mousemove(int &dx, int &dy, float &cursens) { return false; } bool recomputecamera(physent *&camera1, physent &tempcamera, bool &detachedcamera, float &thirdpersondistance) { if(player1->state == CS_DEAD || editmode || !thirdperson) return false; return true; } ///engine specific void setwindowcaption() { defformatstring(capt)("SandBox %s: Puzzle Games - %s", version, getclientmap()[0] ? getclientmap() : "[new map]"); SDL_WM_SetCaption(capt, NULL); } void startmap(const char *name) { lastpickupmillis = -30000; copystring(clientmap, name ? name : ""); intermission = false; findplayerspawn(player1, -1); if(identexists("mapstart")) execute("mapstart"); } void edittoggled(bool on) { } void physicstrigger(physent *d, bool local, int floorlevel, int waterlevel, int material) { if(d->state!=CS_ALIVE||d->type==ENT_INANIMATE) return; switch(material) { case MAT_LAVA: if (waterlevel==0) break; //playsound(S_BURN, d==player1 ? NULL : &d->o); loopi(60) { vec o = d->o; o.z -= d->eyeheight *i/60.0f; regular_particle_flame(PART_FLAME, o, 6, 2, 0x903020, 3, 2.0f); regular_particle_flame(PART_SMOKE, vec(o.x, o.y, o.z + 8.0f), 6, 2, 0x303020, 1, 4.0f, 100.0f, 2000.0f, -20); } if(d==player1) respawnself(); break; case MAT_WATER: if (waterlevel==0) break; //playsound(waterlevel > 0 ? S_SPLASH_IN : S_SPLASH_OUT , d==player1 ? NULL : &d->o); particle_splash(PART_WATER, 200, 200, d->o, (watercolor.x<<16) | (watercolor.y<<8) | watercolor.z, 0.5); break; default: if (floorlevel==0) break; //playsound(floorlevel > 0 ? S_JUMP : S_LAND, local ? NULL : &d->o); break; } } void openworld(const char *name, bool fall = false) { if(!connected) localconnect(); if(name && *name && load_world(name)) return; else emptymap(10, true, (name && *name) ? name : NULL); } ICOMMAND(map, "s", (char *s), openworld(s)) void initclient() { if(!player1->name) player1->name = name; clientmap[0] = 0; } int numdynents(){ return 1; } dynent *iterdynents(int i) { if(!i) return player1; i--; return NULL; } void changemap(const char *name) { openworld(name, true); } void forceedit(const char *name) { openworld(name); } const char *gameident() { return "pzl"; } const char *autoexec() { return "autoexec.cfg"; } const char *savedservers() { return NULL; } } sandboxgamemaker-2.7.1+dfsg/src/pzlgame/pzlscript.cpp0000664000175000017500000000050511442705030022632 0ustar showardshoward#include "pzlgame.h" using namespace game; namespace pzlscript { //Scripting for various map entities for the puzzel games :D //Eventually, when I figure out how I'm going to do map entites //That have proper physics, perhaps I'll add Newton game dynamics //Or ODE physics, Bullet is out of the question, too slow... } sandboxgamemaker-2.7.1+dfsg/src/pzlgame/pzlstubs.cpp0000664000175000017500000000743011527772734022515 0ustar showardshoward#include "pzlgame.h" namespace game { int clipconsole(int w, int h){ return 0;} float abovegameplayhud(int w, int h) {return 1;} const char *getmapinfo() {return NULL;} void g3d_gamemenus() {} void adddynlights() {} void resetgamestate() {} void newmap(int size){} void writemapdata(stream *f) {} void preload() {} void parsepacketclient(int chan, packetbuf &p) {} void writeclientinfo(stream *f) {} void toserver(char *text) {} void connectattempt(const char *name, const char *password, const ENetAddress &address) {} void connectfail() {} void parseoptions(vector &args) {} void renderavatar() {} void setupcamera(){} void lighteffects(dynent *d, vec &color, vec &dir) {} void particletrack(physent *owner, vec &o, vec &d) {} void dynlighttrack(physent *owner, vec &o, vec &hud) {} #ifndef NEWGUI void serverinfoendcolumn(g3d_gui *g, int i) {} #endif void vartrigger(ident *id) {} void bounced(physent *d, const vec &surface) {} void registeranimation(char *dir, char* anim, int num) {} void writegamedata(vector &extras) {} void readgamedata(vector &extras) {} void loadconfigs(){} void dynentcollide(physent *d, physent *o, const vec &dir) {} void edittrigger(const selinfo &sel, int op, int arg1, int arg2, int arg3) {} void texturefailed(char *name, int slot) {} void mmodelfailed(const char *name, int idx) {} void mapfailed(const char *name) {} void suicide(physent *d){} bool showenthelpers() { return editmode; } bool ispaused() { return false; } bool allowdoublejump(){ return false; } bool detachcamera() { return false; } bool needminimap() { return false; } bool allowedittoggle() { return true; } bool allowmove (physent *d) {return true;} bool collidecamera() {return !editmode;} #ifndef NEWGUI bool serverinfostartcolumn(g3d_gui *g, int i) {return false;} bool serverinfoentry(g3d_gui *g, int i, const char *name, int port, const char *desc, const char *map, int ping, const vector &attr, int np) {return false;} #endif } namespace entities { int extraentinfosize() { return 0; } int *getmodelattr(extentity &e) { return NULL; } const char *entnameinfo(entity &e) { return ""; } void fixentity(extentity &e){} void editent(int i, bool local) {} void writeent(entity &e, char *buf) {} void renderhelpertext(extentity &e, int &colour, vec &pos, string &tmp){} void entradius(extentity &e, bool &color){} void readent(entity &e, char *buf, int ver){} bool dirent(extentity &e){return false;} bool radiusent(extentity &e){return false;} bool mayattach(extentity &e) { return false; } bool attachent(extentity &e, extentity &a) { return false; } bool printent(extentity &e, char *buf) { return false; } bool checkmodelusage(extentity &e, int i){ return false; } } namespace server { int reserveclients() { return 0; } int clientconnect(int n, uint ip) { return DISC_NONE; } int numchannels() {return 0;} int laninfoport() {return 0;} int serverinfoport(int servport) {return 0;} int serverport(int infoport) {return 0;} int masterport() {return 0;} const char *defaultmaster() {return "";} void *newclientinfo() {return NULL;} void deleteclientinfo(void *ci) {} void serverinit() {} void clientdisconnect(int n) {} void localdisconnect(int n) {} void localconnect(int n) {} void recordpacket(int chan, void *data, int len) {} void parsepacket(int sender, int chan, packetbuf &p) {} void sendservmsg(const char *s) {} void serverinforeply(ucharbuf &q, ucharbuf &p) {} void serverupdate() {} void processmasterinput(const char *cmd, int cmdlen, const char *args) {} bool allowbroadcast(int n) { return false; } bool sendpackets(bool force) { return false; } bool servercompatible(char *name, char *sdec, char *map, int ping, const vector &attr, int np) { return true; } bool ispaused() {return game::ispaused();} } sandboxgamemaker-2.7.1+dfsg/src/pzlgame/pzlents.cpp0000664000175000017500000000421311571424710022305 0ustar showardshoward#include "pzlgame.h" namespace entities { int lastpickupmillis; vector ents; vector &getents() { return ents; } extentity *newentity() { return new pzlentity();} void deleteentity(extentity *e) { delete (pzlentity *)e;} void fixentity(entity &e){} const char *entmodel(const entity &e) { const char *mdl[] = { NULL, //NOTUSED - ET_EMPTY = 0 NULL, //LIGHT - ET_LIGHT = 1 NULL, //MAPMODEL - ET_MAPMODEL = 2 NULL, //PLAYERSTART - ET_NULL = 3 NULL, //ENVMAP - ET_ENVMAP = 4 NULL, //PARTICLES - ET_PARTICLES = 5 NULL, //MAPSOUND - ET_SOUND = 6 NULL //SPOTLIGHT - ET_SPOTLIGHT = 7 }; return mdl[e.type]; } void renderent(extentity &e, const char *mdlname, float z, float yaw, int anim = ANIM_MAPMODEL) { if(!mdlname) return; rendermodel(&e.light, mdlname, anim|ANIM_LOOP, vec(e.o).add(vec(0, 0, z)), yaw, 0, MDL_SHADOW|MDL_CULL_VFC|MDL_CULL_DIST|MDL_CULL_OCCLUDED ); } void renderentities() { loopv(ents) { extentity &e = *ents[i]; switch(e.type) { default: continue; } } } void animatemapmodel(const extentity &e, int &anim, int &basetime) { anim = ANIM_MAPMODEL|ANIM_LOOP; } void trypickup(int n, pzlchar *d) { extentity &e = *ents[n]; switch(e.type) {} } const char *entname(int i) { static const char *entnames[] = { "none?", "light", "mapmodel", "playerstart", "envmap", "particles", "sound", "spotlight" }; return i>=0 && size_t(i)o; o.z -= d->eyeheight; loopv(ents) { extentity &e = *ents[i]; if(e.type==NOTUSED) continue; if(lastmillis > lastpickupmillis + ENTSPAWNTIME && !e.spawned) e.spawned = true; } } const int numattrs(int type) { static const int num[] = {}; type -= ET_GAMESPECIFIC; return type >= 0 && size_t(type) < sizeof(num)/sizeof(num[0]) ? num[type] : 0; } float dropheight(entity &e) { if(e.type==MAPMODEL) return 0.0f; return 4.0f; } void clearents() { while(ents.length()) deleteentity(ents.pop()); } } sandboxgamemaker-2.7.1+dfsg/src/pzlgame/pzlrender.cpp0000664000175000017500000000075011442705030022607 0ustar showardshoward#include "pzlgame.h" namespace game { const char *playermodels(int mdl) { const char *mdls[] = { "rc", "ogre" }; return mdls[mdl]; }; void renderplayer(pzlchar *d) { renderclient(d, playermodels(d->playerindex), NULL, ANIM_HOLD1|ANIM_LOOP, ANIM_ATTACK1, 0, 0, 0, 1, false); } void rendergame(bool mainpass) { startmodelbatches(); if(isthirdperson()) renderplayer(game::player1); entities::renderentities(); endmodelbatches(); if(mainpass){} } } sandboxgamemaker-2.7.1+dfsg/src/pzlgame/pzlhud.cpp0000664000175000017500000000134511442705030022111 0ustar showardshoward#include "pzlgame.h" #include "engine.h" namespace game { void quad(int x, int y, int xs, int ys) { glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2i(x, y); glTexCoord2f(1, 0); glVertex2i(x+xs, y); glTexCoord2f(0, 1); glVertex2i(x, y+ys); glTexCoord2f(1, 1); glVertex2i(x+xs, y+ys); glEnd(); } void gameplayhud(int w, int h) { float scale = min(w / 1600.0f, h / 1200.0f); float right = w / scale, bottom = h / scale; glPushMatrix(); glScalef(scale, scale, 1); //draw glPopMatrix(); } const char *defaultcrosshair(int index) { return editmode ? "data/edit" : "data/items"; } int selectcrosshair(float &r, float &g, float &b) { r = b = 0.5; g = 1.0f; return editmode; } } sandboxgamemaker-2.7.1+dfsg/src/launcher/0000775000175000017500000000000011660234746020253 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/launcher/paslapp.cpp0000664000175000017500000000376511400572314022416 0ustar showardshoward///////////////////////////////////////////////////////////////////////////// // Name: paslapp.cpp // Purpose: // Author: James Burns // Modified by: // Created: 17/12/2008 19:03:06 // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes ////@end includes #include "paslapp.h" ////@begin XPM images ////@end XPM images /*! * Application instance implementation */ ////@begin implement app IMPLEMENT_APP( PASLApp ) ////@end implement app /*! * PASLApp type definition */ IMPLEMENT_CLASS( PASLApp, wxApp ) /*! * PASLApp event table definition */ BEGIN_EVENT_TABLE( PASLApp, wxApp ) ////@begin PASLApp event table entries ////@end PASLApp event table entries END_EVENT_TABLE() /*! * Constructor for PASLApp */ PASLApp::PASLApp() { Init(); } /*! * Member initialisation */ void PASLApp::Init() { ////@begin PASLApp member initialisation ////@end PASLApp member initialisation } /*! * Initialisation for PASLApp */ bool PASLApp::OnInit() { ////@begin PASLApp initialisation // Remove the comment markers above and below this block // to make permanent changes to the code. #if wxUSE_XPM wxImage::AddHandler(new wxXPMHandler); #endif #if wxUSE_LIBPNG wxImage::AddHandler(new wxPNGHandler); #endif #if wxUSE_LIBJPEG wxImage::AddHandler(new wxJPEGHandler); #endif #if wxUSE_GIF wxImage::AddHandler(new wxGIFHandler); #endif PASL* mainWindow = new PASL( NULL ); mainWindow->Show(true); ////@end PASLApp initialisation return true; } /*! * Cleanup for PASLApp */ int PASLApp::OnExit() { ////@begin PASLApp cleanup return wxApp::OnExit(); ////@end PASLApp cleanup } sandboxgamemaker-2.7.1+dfsg/src/launcher/NoImage.xpm0000664000175000017500000001243211400572314022306 0ustar showardshoward/* XPM */ static const char *NoImage_xpm[] = { /* columns rows colors chars-per-pixel */ "64 64 54 1", " c Black", "- c #0F0F0F", "j c #E8E8E8", "7 c #F7F7F7", "O c #080808", ". c #171717", "k c #262626", "h c #F0F0F0", "2 c #FFFFFF", "X c #010101", "q c #101010", "; c #1F1F1F", "l c #E9E9E9", "d c #F8F8F8", "% c #090909", "n c #181818", "3 c #F1F1F1", ": c #020202", "1 c #111111", "z c #EAEAEA", "9 c #F9F9F9", "# c #0A0A0A", "f c #191919", "e c #F2F2F2", "+ c #030303", "s c #121212", "y c #FAFAFA", "* c #0B0B0B", "a c #1A1A1A", "p c #F3F3F3", "@ c #040404", "= c #131313", "g c #ECECEC", "t c #FBFBFB", "o c #0C0C0C", "i c #F4F4F4", "> c #050505", "5 c #141414", "x c #EDEDED", "r c #FCFCFC", "$ c #0D0D0D", "b c #1C1C1C", "c c #F5F5F5", ", c #060606", "8 c #151515", "m c #242424", "4 c #EEEEEE", "0 c #FDFDFD", "< c #0E0E0E", "u c #F6F6F6", "& c #070707", "6 c #161616", "v c #E0E0E0", "w c #FEFEFE", /* pixels */ " ", " ", " ", " ", " ", " ", " ", " ", " . XoO X+ @ XX# $@% & o @ * ", " % o+ = - ; o : >%, ", " > <>*> * $@ >%o %= 1 - $ >@ ", " X 2322 # 222, @ O>@ @: ++ ", " -% %24O 2$ XX> &:O ,# @5 @ ", " @ & 6 7o78XO4#O, 29222- o X& ", " +@ : :2 0X q2 X %2 X *7< @ q ", " &# 2: 2, wo @2 ++ >& e< > - % ", " : :* 2 :r ,t < 2 @ & 9, % ", " #$+ + yO u, 2 , i # - #2+@ #@ ", " @p@# 2@pX @2 O: :a w < % ", " < >& %2 @ 0 2, 5r @, 21 +% : ", " ,9 %:w2+ 2 O X&2 *> :X ", " > &= ui2% sdw @& @292e2 :s @>& ", " 1 +O$ - +#@: , O :1 q O% > ", " + q , o: - > O # @ & O+ O + ", "* @ o , * ", " ,%> :O+ * ", " @> $ - %&> o > ", " ++ :@ o ", "@ 5@ #,<@Xo* $ ", "&X o @ $X ", " q @ <,* f & ", "% - > ", " : 2 X : % q #, +@ O+ ** O: XX > 1 X @+% + # $ ,", " : 2 X : 22+2r org 2eh2% < ::X22iys2hO O 2292: *$ > ", " : 2 X : 2d <23<*2 ,+7&-+%7X = Ow $uj%: >2 < 2,+ X#", " : 2 X : d& y% 7$ + >2= >2o-@ &X2 @ u- >5 2 ,# ", " : 2 X : 8d Ow -%t oX +X@ e ki & @O2> &2 O : *", " : 2 X : 2 *:eX @i- 722d222O 2O# O 2 , 22r2420yq< 6X ", " : 2 X : or & 0$ ,r+: 2 ,Oe > < 2& o0 + > @@ O+", " : 2 X : +y>:+2X 2 2 * :> t@ 2@@ & 2 2>, O >XX - >", "% > , @@ 2& ++3O 2 # w* 2 > ,20 . &9< > 27< & w : 7O $ ", " %> 6 8tr92t0t:@d2x%>09 Otc>+i2222 t2 , O+X >$ * + @O < 1 - *o $$ %+&O: + 2X <# > O, =:++", " * #># &O +b < *8 @ * < % q &O % s# & t q n& %@+ 6 , ", " # f+ & OXX # q# ,X # X> ,O:,@@ * qe# : & @+ = $+%", ", %> =X% : mX * @X 1 X = >> :% >:,X2227@ > $*&O O n+ + + ", ", %-: @* O % $:$ o < +> , ::, * ,+ # @ , >% = ", " O%: + + : : @> - +O : # X+@> :& $ :$ > : $ o X>& & %", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " }; sandboxgamemaker-2.7.1+dfsg/src/launcher/Makefile0000664000175000017500000000522611400572314021704 0ustar showardshoward### Begin DialogBlocks generated body ################################################################################ # Makefile generated by DialogBlocks # # Available configurations: # release ################################################################################ CONFIG=release # release ifeq ($(CONFIG),release) WXWIN= TOOLCHAINNAME=gtk2u WXVERSION:=$(shell echo `wx-config --version`) CXX=g++ LINKER=g++ CC=gcc RESCOMP=windres.exe RCFILEOBJ=PASL_rc.o RCFILESRC=PASL.rc RESOURCEOBJECT= OUTPUTPATH=GCCRelease OBJECTPATH=GCCRelease BUILDPATHS=$(OBJECTPATH) PROGRAM=PASL LIBS=$(shell wx-config --libs std --cxxflags) LINKERFLAGS= WARNINGFLAGS=-Wall -Wno-write-strings OPTFLAGS=-O2 DEBUGFLAGS= LIBPATH= CPPINC:=$(shell wx-config --cxxflags) GCCFLAGS= LDFLAGS=$(LIBS) $(LIBPATH) $(LINKERFLAGS) CPPFLAGS=$(CPPINC) $(GCCFLAGS) $(DEBUGFLAGS) $(OPTFLAGS) $(WARNINGFLAGS) LIBDIRNAME=$(WXWIN)/GCCBuildReleaseGTK2Unicode/lib RESPATH=--include-dir "$(WXWIN)/include" --include-dir "$(WXWIN)/contrib/include" --include-dir "$(WXWIN)/GCCBuildReleaseGTK2Unicode/lib/wx/include/gtk2-unicode-release-static-2.8" MACPACKAGEINFO= endif OBJECTS=$(OBJECTPATH)/pasl.o $(OBJECTPATH)/paslapp.o $(RESOURCEOBJECT) all: $(BUILDPATHS) $(MACPACKAGEINFO) $(OUTPUTPATH)/$(PROGRAM) $(OBJECTPATH): mkdir -p $(OBJECTPATH) clean: rm -f $(OBJECTPATH)/*.o rm -f $(OBJECTPATH)/*.res rm -fr .deps .pch rm -fr $(PROGRAM).app rm -f $(OUTPUTPATH)/$(PROGRAM) help: @echo "Usage: make -f Makefile CONFIG=[release] [all|clean|help]" $(OUTPUTPATH)/$(PROGRAM): $(OBJECTS) $(LINKER) -o $@ $(OBJECTS) $(LDFLAGS) # Windows only $(OBJECTPATH)/$(RCFILEOBJ): $(RCFILESRC) $(RESCOMP) --use-temp-file -i$< -o$@ $(RESPATH) --include-dir . --define NOPCH # Mac only $(OUTPUTPATH)/$(PROGRAM).app/Contents/PkgInfo: $(OUTPUTPATH)/$(PROGRAM) $(INFOPLISTSOURCE) $(ICNSSOURCE) mkdir -p $(OUTPUTPATH)/$(PROGRAM).app/Contents mkdir -p $(OUTPUTPATH)/$(PROGRAM).app/Contents/MacOS mkdir -p $(OUTPUTPATH)/$(PROGRAM).app/Contents/Resources sed -e "s/IDENTIFIER/$(PROGRAM)/" \ -e "s/EXECUTABLE/$(PROGRAM)/" \ -e "s/VERSION/$(WXVERSION)/" \ $(INFOPLISTSOURCE) >$(OUTPUTPATH)/$(PROGRAM).app/Contents/Info.plist echo -n "APPL????" >$(OUTPUTPATH)/$(PROGRAM).app/Contents/PkgInfo ln -f $(OUTPUTPATH)/$(PROGRAM) $(OUTPUTPATH)/$(PROGRAM).app/Contents/MacOS/$(PROGRAM) cp -f $(ICNSSOURCE) $(ICNSDEST) $(OBJECTPATH)/pasl.o: pasl.cpp pasl.h sandboxlogo.xpm NoImage.xpm $(CXX) -c -o $@ $(CPPFLAGS) pasl.cpp $(OBJECTPATH)/paslapp.o: paslapp.cpp paslapp.h pasl.h $(CXX) -c -o $@ $(CPPFLAGS) paslapp.cpp .PHONY: all clean ### End DialogBlocks generated body sandboxgamemaker-2.7.1+dfsg/src/launcher/pasl.cpp0000664000175000017500000007663511400572314021723 0ustar showardshoward///////////////////////////////////////////////////////////////////////////// // Name: pasl.cpp // Purpose: // Author: James Burns // Modified by: // Created: 17/12/2008 19:03:58 // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #include "wx/stdpaths.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes #include "wx/imaglist.h" ////@end includes #include "pasl.h" ////@begin XPM images #include "sandboxlogo.xpm" #include "NoImage.xpm" ////@end XPM images /*! * PASL type definition */ IMPLEMENT_CLASS( PASL, wxFrame ) /*! * PASL event table definition */ BEGIN_EVENT_TABLE( PASL, wxFrame ) ////@begin PASL event table entries EVT_COMBOBOX( ID_COMBOBOX, PASL::OnResBoxSelected ) EVT_COMBOBOX( ID_COMBOBOX1, PASL::OnShaderBoxSelected ) EVT_COMBOBOX( ID_COMBOBOX2, PASL::OnVSyncSelected ) EVT_COMBOBOX( ID_COMBOBOX6, PASL::OnMapBoxSelected ) EVT_BUTTON( ID_BUTTON, PASL::OnFPSLaunch ) EVT_BUTTON( ID_BUTTON1, PASL::OnSSPLaunch ) EVT_BUTTON( ID_BUTTON2, PASL::OnRPGLaunch ) EVT_TEXT( ID_TEXTCTRL, PASL::OnServerNameTextUpdated ) EVT_COMBOBOX( ID_COMBOBOX3, PASL::OnPlayerBoxSelected ) EVT_COMBOBOX( ID_COMBOBOX4, PASL::OnMasterBoxSelected ) EVT_TEXT( ID_TEXTCTRL1, PASL::OnServerPasswordTextUpdated ) EVT_COMBOBOX( ID_COMBOBOX5, PASL::OnDedBoxSelected ) EVT_COMBOBOX( ID_COMBOBOX7, PASL::OnModeBoxSelected ) EVT_BUTTON( ID_BUTTON3, PASL::OnServerLaunch ) EVT_TEXT( ID_TEXTCTRL2, PASL::OnClientIPTextUpdated ) EVT_TEXT( ID_TEXTCTRL3, PASL::OnClientPasswordTextUpdated ) EVT_COMBOBOX( ID_COMBOBOX8, PASL::OnCModeBoxSelected ) EVT_BUTTON( ID_BUTTON4, PASL::OnClientLaunch ) EVT_BUTTON( ID_BUTTON5, PASL::OnMovieCubeButtonClick ) ////@end PASL event table entries END_EVENT_TABLE() /*! * PASL constructors */ PASL::PASL() { Init(); } PASL::PASL( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create( parent, id, caption, pos, size, style ); } /*! * PASL creator */ bool PASL::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin PASL creation wxFrame::Create( parent, id, caption, pos, size, style ); CreateControls(); SetIcon(GetIconResource(wxT("sandboxlogo.xpm"))); Centre(); ////@end PASL creation return true; } /*! * PASL destructor */ PASL::~PASL() { ////@begin PASL destruction ////@end PASL destruction } /*! * Member initialisation */ void PASL::Init() { ////@begin PASL member initialisation ResBox = NULL; ShaderBox = NULL; VSyncBox = NULL; MapBox = NULL; MapPrev = NULL; FPSLaunch = NULL; SSPLaunch = NULL; RPGLaunch = NULL; ServerName = NULL; PlayerBox = NULL; MasterBox = NULL; ServerPassword = NULL; DedBox = NULL; ModeBox = NULL; ServerLaunch = NULL; ClientIP = NULL; ClientPassword = NULL; CModeBox = NULL; ClientLaunch = NULL; MovieCubeButton = NULL; ////@end PASL member initialisation } /*! * Control creation for PASL */ void PASL::CreateControls() { ////@begin PASL content construction // Generated by DialogBlocks, Fri 15 Jan 2010 16:18:25 EST (unregistered) PASL* itemFrame1 = this; wxPanel* itemPanel2 = new wxPanel( itemFrame1, ID_PANEL, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); wxFlexGridSizer* itemFlexGridSizer3 = new wxFlexGridSizer(3, 1, 0, 0); itemPanel2->SetSizer(itemFlexGridSizer3); wxFlexGridSizer* itemFlexGridSizer4 = new wxFlexGridSizer(1, 3, 0, 0); itemFlexGridSizer3->Add(itemFlexGridSizer4, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer5Static = new wxStaticBox(itemPanel2, wxID_ANY, _("Resolution")); wxStaticBoxSizer* itemStaticBoxSizer5 = new wxStaticBoxSizer(itemStaticBoxSizer5Static, wxHORIZONTAL); itemFlexGridSizer4->Add(itemStaticBoxSizer5, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString ResBoxStrings; ResBoxStrings.Add(_("640x480")); ResBoxStrings.Add(_("800x600")); ResBoxStrings.Add(_("1024x768")); ResBoxStrings.Add(_("1280x960")); ResBoxStrings.Add(_("1600x1200")); ResBox = new wxComboBox( itemPanel2, ID_COMBOBOX, _("1024x768"), wxDefaultPosition, wxSize(110, -1), ResBoxStrings, wxCB_READONLY ); ResBox->SetStringSelection(_("1024x768")); itemStaticBoxSizer5->Add(ResBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer7Static = new wxStaticBox(itemPanel2, wxID_ANY, _("Shaders")); wxStaticBoxSizer* itemStaticBoxSizer7 = new wxStaticBoxSizer(itemStaticBoxSizer7Static, wxHORIZONTAL); itemFlexGridSizer4->Add(itemStaticBoxSizer7, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString ShaderBoxStrings; ShaderBoxStrings.Add(_("Off")); ShaderBoxStrings.Add(_("Low")); ShaderBoxStrings.Add(_("High")); ShaderBox = new wxComboBox( itemPanel2, ID_COMBOBOX1, _("Low"), wxDefaultPosition, wxSize(70, -1), ShaderBoxStrings, wxCB_READONLY ); ShaderBox->SetStringSelection(_("Low")); itemStaticBoxSizer7->Add(ShaderBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer9Static = new wxStaticBox(itemPanel2, wxID_ANY, _("VSync")); wxStaticBoxSizer* itemStaticBoxSizer9 = new wxStaticBoxSizer(itemStaticBoxSizer9Static, wxHORIZONTAL); itemFlexGridSizer4->Add(itemStaticBoxSizer9, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString VSyncBoxStrings; VSyncBoxStrings.Add(_("Off")); VSyncBoxStrings.Add(_("On")); VSyncBox = new wxComboBox( itemPanel2, ID_COMBOBOX2, _("Off"), wxDefaultPosition, wxSize(60, -1), VSyncBoxStrings, wxCB_READONLY ); VSyncBox->SetStringSelection(_("Off")); itemStaticBoxSizer9->Add(VSyncBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxFlexGridSizer* itemFlexGridSizer11 = new wxFlexGridSizer(1, 2, 0, 0); itemFlexGridSizer3->Add(itemFlexGridSizer11, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer12Static = new wxStaticBox(itemPanel2, wxID_ANY, _("Map")); wxStaticBoxSizer* itemStaticBoxSizer12 = new wxStaticBoxSizer(itemStaticBoxSizer12Static, wxHORIZONTAL); itemFlexGridSizer11->Add(itemStaticBoxSizer12, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString MapBoxStrings; MapBox = new wxComboBox( itemPanel2, ID_COMBOBOX6, wxEmptyString, wxDefaultPosition, wxSize(180, -1), MapBoxStrings, wxCB_READONLY ); itemStaticBoxSizer12->Add(MapBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer14Static = new wxStaticBox(itemPanel2, wxID_ANY, _("Map Image")); wxStaticBoxSizer* itemStaticBoxSizer14 = new wxStaticBoxSizer(itemStaticBoxSizer14Static, wxHORIZONTAL); itemFlexGridSizer11->Add(itemStaticBoxSizer14, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); MapPrev = new wxStaticBitmap( itemPanel2, wxID_STATIC, itemFrame1->GetBitmapResource(wxT("NoImage.xpm")), wxDefaultPosition, wxSize(64, 64), wxSIMPLE_BORDER ); itemStaticBoxSizer14->Add(MapPrev, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxFlexGridSizer* itemFlexGridSizer16 = new wxFlexGridSizer(1, 1, 0, 0); itemFlexGridSizer3->Add(itemFlexGridSizer16, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxNotebook* itemNotebook17 = new wxNotebook( itemPanel2, ID_NOTEBOOK, wxDefaultPosition, wxSize(320, -1), wxBK_DEFAULT ); wxPanel* itemPanel18 = new wxPanel( itemNotebook17, ID_PANEL1, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); itemPanel18->SetBackgroundColour(wxColour(224, 223, 227)); wxFlexGridSizer* itemFlexGridSizer19 = new wxFlexGridSizer(1, 3, 0, 0); itemFlexGridSizer19->AddGrowableCol(0); itemPanel18->SetSizer(itemFlexGridSizer19); FPSLaunch = new wxButton( itemPanel18, ID_BUTTON, _("Launch"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer19->Add(FPSLaunch, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); itemNotebook17->AddPage(itemPanel18, _("FPS")); wxPanel* itemPanel21 = new wxPanel( itemNotebook17, ID_PANEL2, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); itemPanel21->SetBackgroundColour(wxColour(224, 223, 227)); wxFlexGridSizer* itemFlexGridSizer22 = new wxFlexGridSizer(2, 2, 0, 0); itemFlexGridSizer22->AddGrowableCol(0); itemPanel21->SetSizer(itemFlexGridSizer22); SSPLaunch = new wxButton( itemPanel21, ID_BUTTON1, _("Launch"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer22->Add(SSPLaunch, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); itemNotebook17->AddPage(itemPanel21, _("SSP")); wxPanel* itemPanel24 = new wxPanel( itemNotebook17, ID_PANEL3, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); itemPanel24->SetBackgroundColour(wxColour(224, 223, 227)); wxFlexGridSizer* itemFlexGridSizer25 = new wxFlexGridSizer(2, 2, 0, 0); itemFlexGridSizer25->AddGrowableCol(0); itemPanel24->SetSizer(itemFlexGridSizer25); RPGLaunch = new wxButton( itemPanel24, ID_BUTTON2, _("Launch"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer25->Add(RPGLaunch, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); itemNotebook17->AddPage(itemPanel24, _("RPG")); wxPanel* itemPanel27 = new wxPanel( itemNotebook17, ID_PANEL4, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); itemPanel27->SetBackgroundColour(wxColour(224, 223, 227)); wxFlexGridSizer* itemFlexGridSizer28 = new wxFlexGridSizer(3, 1, 0, 0); itemPanel27->SetSizer(itemFlexGridSizer28); wxFlexGridSizer* itemFlexGridSizer29 = new wxFlexGridSizer(1, 3, 0, 0); itemFlexGridSizer28->Add(itemFlexGridSizer29, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer30Static = new wxStaticBox(itemPanel27, wxID_ANY, _("Server Name")); wxStaticBoxSizer* itemStaticBoxSizer30 = new wxStaticBoxSizer(itemStaticBoxSizer30Static, wxHORIZONTAL); itemFlexGridSizer29->Add(itemStaticBoxSizer30, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); ServerName = new wxTextCtrl( itemPanel27, ID_TEXTCTRL, _("Sandbox Server"), wxDefaultPosition, wxSize(100, -1), 0 ); itemStaticBoxSizer30->Add(ServerName, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer32Static = new wxStaticBox(itemPanel27, wxID_ANY, _("Players")); wxStaticBoxSizer* itemStaticBoxSizer32 = new wxStaticBoxSizer(itemStaticBoxSizer32Static, wxHORIZONTAL); itemFlexGridSizer29->Add(itemStaticBoxSizer32, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString PlayerBoxStrings; PlayerBoxStrings.Add(_("0")); PlayerBoxStrings.Add(_("1")); PlayerBoxStrings.Add(_("2")); PlayerBoxStrings.Add(_("3")); PlayerBoxStrings.Add(_("4")); PlayerBoxStrings.Add(_("5")); PlayerBoxStrings.Add(_("6")); PlayerBoxStrings.Add(_("7")); PlayerBoxStrings.Add(_("8")); PlayerBoxStrings.Add(_("9")); PlayerBoxStrings.Add(_("10")); PlayerBoxStrings.Add(_("11")); PlayerBoxStrings.Add(_("12")); PlayerBoxStrings.Add(_("13")); PlayerBoxStrings.Add(_("14")); PlayerBoxStrings.Add(_("15")); PlayerBoxStrings.Add(_("16")); PlayerBoxStrings.Add(_("17")); PlayerBoxStrings.Add(_("18")); PlayerBoxStrings.Add(_("19")); PlayerBoxStrings.Add(_("20")); PlayerBoxStrings.Add(_("21")); PlayerBoxStrings.Add(_("22")); PlayerBoxStrings.Add(_("23")); PlayerBoxStrings.Add(_("24")); PlayerBoxStrings.Add(_("25")); PlayerBoxStrings.Add(_("26")); PlayerBoxStrings.Add(_("27")); PlayerBoxStrings.Add(_("28")); PlayerBoxStrings.Add(_("29")); PlayerBoxStrings.Add(_("30")); PlayerBoxStrings.Add(_("31")); PlayerBoxStrings.Add(_("32")); PlayerBox = new wxComboBox( itemPanel27, ID_COMBOBOX3, _("12"), wxDefaultPosition, wxSize(60, -1), PlayerBoxStrings, wxCB_READONLY ); PlayerBox->SetStringSelection(_("12")); itemStaticBoxSizer32->Add(PlayerBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer34Static = new wxStaticBox(itemPanel27, wxID_ANY, _("MMode")); wxStaticBoxSizer* itemStaticBoxSizer34 = new wxStaticBoxSizer(itemStaticBoxSizer34Static, wxHORIZONTAL); itemFlexGridSizer29->Add(itemStaticBoxSizer34, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString MasterBoxStrings; MasterBoxStrings.Add(_("N")); MasterBoxStrings.Add(_("Y")); MasterBox = new wxComboBox( itemPanel27, ID_COMBOBOX4, _("N"), wxDefaultPosition, wxSize(50, -1), MasterBoxStrings, wxCB_READONLY ); MasterBox->SetStringSelection(_("N")); itemStaticBoxSizer34->Add(MasterBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxFlexGridSizer* itemFlexGridSizer36 = new wxFlexGridSizer(1, 3, 0, 0); itemFlexGridSizer28->Add(itemFlexGridSizer36, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer37Static = new wxStaticBox(itemPanel27, wxID_ANY, _("Server Password")); wxStaticBoxSizer* itemStaticBoxSizer37 = new wxStaticBoxSizer(itemStaticBoxSizer37Static, wxHORIZONTAL); itemFlexGridSizer36->Add(itemStaticBoxSizer37, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); ServerPassword = new wxTextCtrl( itemPanel27, ID_TEXTCTRL1, wxEmptyString, wxDefaultPosition, wxSize(100, -1), 0 ); itemStaticBoxSizer37->Add(ServerPassword, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer39Static = new wxStaticBox(itemPanel27, wxID_ANY, _("Dedicated")); wxStaticBoxSizer* itemStaticBoxSizer39 = new wxStaticBoxSizer(itemStaticBoxSizer39Static, wxHORIZONTAL); itemFlexGridSizer36->Add(itemStaticBoxSizer39, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString DedBoxStrings; DedBoxStrings.Add(_("N")); DedBoxStrings.Add(_("Y")); DedBox = new wxComboBox( itemPanel27, ID_COMBOBOX5, _("N"), wxDefaultPosition, wxSize(60, -1), DedBoxStrings, wxCB_READONLY ); DedBox->SetStringSelection(_("N")); itemStaticBoxSizer39->Add(DedBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer41Static = new wxStaticBox(itemPanel27, wxID_ANY, _("Mode")); wxStaticBoxSizer* itemStaticBoxSizer41 = new wxStaticBoxSizer(itemStaticBoxSizer41Static, wxHORIZONTAL); itemFlexGridSizer36->Add(itemStaticBoxSizer41, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString ModeBoxStrings; ModeBoxStrings.Add(_("FPS")); ModeBoxStrings.Add(_("SSP")); ModeBoxStrings.Add(_("RPG")); ModeBox = new wxComboBox( itemPanel27, ID_COMBOBOX7, _("FPS"), wxDefaultPosition, wxSize(65, -1), ModeBoxStrings, wxCB_READONLY ); ModeBox->SetStringSelection(_("FPS")); itemStaticBoxSizer41->Add(ModeBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxFlexGridSizer* itemFlexGridSizer43 = new wxFlexGridSizer(1, 3, 0, 0); itemFlexGridSizer28->Add(itemFlexGridSizer43, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); itemFlexGridSizer43->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); ServerLaunch = new wxButton( itemPanel27, ID_BUTTON3, _("Launch"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer43->Add(ServerLaunch, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); itemFlexGridSizer43->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); itemNotebook17->AddPage(itemPanel27, _("Server")); wxPanel* itemPanel47 = new wxPanel( itemNotebook17, ID_PANEL5, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); itemPanel47->SetBackgroundColour(wxColour(224, 223, 227)); wxFlexGridSizer* itemFlexGridSizer48 = new wxFlexGridSizer(2, 1, 0, 0); itemFlexGridSizer48->AddGrowableCol(0); itemPanel47->SetSizer(itemFlexGridSizer48); wxFlexGridSizer* itemFlexGridSizer49 = new wxFlexGridSizer(1, 2, 0, 0); itemFlexGridSizer48->Add(itemFlexGridSizer49, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer50Static = new wxStaticBox(itemPanel47, wxID_ANY, _("IP Address")); wxStaticBoxSizer* itemStaticBoxSizer50 = new wxStaticBoxSizer(itemStaticBoxSizer50Static, wxHORIZONTAL); itemFlexGridSizer49->Add(itemStaticBoxSizer50, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); ClientIP = new wxTextCtrl( itemPanel47, ID_TEXTCTRL2, _("192.168.1.100"), wxDefaultPosition, wxSize(120, -1), 0 ); itemStaticBoxSizer50->Add(ClientIP, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer52Static = new wxStaticBox(itemPanel47, wxID_ANY, _("Password")); wxStaticBoxSizer* itemStaticBoxSizer52 = new wxStaticBoxSizer(itemStaticBoxSizer52Static, wxHORIZONTAL); itemFlexGridSizer49->Add(itemStaticBoxSizer52, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); ClientPassword = new wxTextCtrl( itemPanel47, ID_TEXTCTRL3, wxEmptyString, wxDefaultPosition, wxSize(100, -1), 0 ); itemStaticBoxSizer52->Add(ClientPassword, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxFlexGridSizer* itemFlexGridSizer54 = new wxFlexGridSizer(1, 2, 0, 0); itemFlexGridSizer48->Add(itemFlexGridSizer54, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticBox* itemStaticBoxSizer55Static = new wxStaticBox(itemPanel47, wxID_ANY, _("Mode")); wxStaticBoxSizer* itemStaticBoxSizer55 = new wxStaticBoxSizer(itemStaticBoxSizer55Static, wxHORIZONTAL); itemFlexGridSizer54->Add(itemStaticBoxSizer55, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString CModeBoxStrings; CModeBoxStrings.Add(_("FPS")); CModeBoxStrings.Add(_("SSP")); CModeBoxStrings.Add(_("RPG")); CModeBox = new wxComboBox( itemPanel47, ID_COMBOBOX8, _("FPS"), wxDefaultPosition, wxSize(70, -1), CModeBoxStrings, wxCB_DROPDOWN ); CModeBox->SetStringSelection(_("FPS")); itemStaticBoxSizer55->Add(CModeBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); ClientLaunch = new wxButton( itemPanel47, ID_BUTTON4, _("Launch"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer54->Add(ClientLaunch, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); itemNotebook17->AddPage(itemPanel47, _("Client")); wxPanel* itemPanel58 = new wxPanel( itemNotebook17, ID_PANEL6, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); itemPanel58->SetBackgroundColour(wxColour(224, 223, 227)); wxFlexGridSizer* itemFlexGridSizer59 = new wxFlexGridSizer(1, 1, 0, 0); itemFlexGridSizer59->AddGrowableCol(0); itemPanel58->SetSizer(itemFlexGridSizer59); MovieCubeButton = new wxButton( itemPanel58, ID_BUTTON5, _("Launch"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer59->Add(MovieCubeButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); itemNotebook17->AddPage(itemPanel58, _("MovieCube")); itemFlexGridSizer16->Add(itemNotebook17, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5); ////@end PASL content construction //Enable JPEG Loading wxInitAllImageHandlers(); //Get Current Resolution ResWidth = wxString::Format(wxT("%i"),wxSystemSettings::GetMetric(wxSYS_SCREEN_X)); ResHeight = wxString::Format(wxT("%i"),wxSystemSettings::GetMetric(wxSYS_SCREEN_Y)); ResBox->Append(ResWidth + wxT("x") + ResHeight); ResBox->SetValue(ResWidth + wxT("x") + ResHeight); //Figure Out Which OS Is Running And Set EXE/Map Directories #ifdef __WIN32__ //WinExe = wxT("bin\\sandbox.exe -r "); CurFPSc = wxT("bin\\sandbox_fps.exe -qmy_stuff -r "); CurSSPc = wxT("bin\\sandbox_ssp.exe -qmy_stuff -r "); CurRPGc = wxT("bin\\sandbox_rpg.exe -qmy_stuff -r "); CurFPSs = wxT("bin\\sandbox_fps.exe -r "); CurSSPs = wxT("bin\\sandbox_ssp.exe -r "); CurRPGs = wxT("bin\\sandbox_rpg.exe -r "); CurMovie = wxT("bin\\sandbox_movie.exe"); //CurExe = WinExe; MapDir = (wxGetCwd() + wxT("\\packages\\base\\")); StuffDir = (wxGetCwd() + wxT("\\my_stuff\\packages\\base\\")); #endif #ifdef __UNIX__ if(wxIsPlatform64Bit()) { //LinExe = wxT("./bin//sandbox_client_x86_64 -r "); CurFPSc = wxT("./bin/sandbox_client_64_fps -q") + wxStandardPaths::Get().GetUserConfigDir() + wxT("/.platinumarts -r "); CurSSPc = wxT("./bin/sandbox_client_64_ssp -q") + wxStandardPaths::Get().GetUserConfigDir() + wxT("/.platinumarts -r "); CurRPGc = wxT("./bin/sandbox_client_64_rpg -q") + wxStandardPaths::Get().GetUserConfigDir() + wxT("/.platinumarts -r "); CurFPSs = wxT("./bin/sandbox_server_64_fps "); CurSSPs = wxT("./bin/sandbox_server_64_ssp "); CurRPGs = wxT("./bin/sandbox_server_64_rpg "); CurMovie = wxT("./bin/sandbox_client_32_movie"); } else { CurFPSc = wxT("./bin/sandbox_client_32_fps -q") + wxStandardPaths::Get().GetUserConfigDir() + wxT("/.platinumarts -r "); CurSSPc = wxT("./bin/sandbox_client_32_ssp -q") + wxStandardPaths::Get().GetUserConfigDir() + wxT("/.platinumarts -r "); CurRPGc = wxT("./bin/sandbox_client_32_rpg -q") + wxStandardPaths::Get().GetUserConfigDir() + wxT("/.platinumarts -r "); CurFPSs = wxT("./bin/sandbox_server_32_fps "); CurSSPs = wxT("./bin/sandbox_server_32_ssp "); CurRPGs = wxT("./bin/sandbox_server_32_rpg "); CurMovie = wxT("./bin/sandbox_client_32_movie"); //LinExe = wxT(".//bin//sandbox_client_i686 -r "); } //LinExe = wxT(".//bin//sandbox_client_") + wxGetCommandOutput(wxT("uname -m")) + " -r "); //CurExe = LinExe; MapDir = (wxGetCwd() + wxT("/packages/base/")); StuffDir = (wxStandardPaths::Get().GetUserConfigDir() + wxT("/.platinumarts/packages/base/")); #endif //Get Map List wxString filename; wxDir dir(MapDir); if (dir.IsOpened()) { bool cont = dir.GetFirst(&filename, wxEmptyString, wxDIR_FILES); while(cont) { if(filename.Right(4).IsSameAs(wxT(".ogz"))) { MapBox->Append(filename.Left(filename.Len() - 4)); } cont = dir.GetNext(&filename); } } wxDir dir2(StuffDir); if (dir2.IsOpened()) { bool cont = dir2.GetFirst(&filename, wxEmptyString, wxDIR_FILES); while(cont) { if(filename.Right(4).IsSameAs(wxT(".ogz"))) { MapBox->Append(filename.Left(filename.Len() - 4)); } cont = dir2.GetNext(&filename); } } MapBox->SetValue(wxT("village")); //Set Default Values wxCommandEvent ce; OnResBoxSelected(ce); OnShaderBoxSelected(ce); OnVSyncSelected(ce); OnMapBoxSelected(ce); OnServerNameTextUpdated(ce); OnPlayerBoxSelected(ce); OnMasterBoxSelected(ce); OnServerPasswordTextUpdated(ce); OnDedBoxSelected(ce); OnModeBoxSelected(ce); OnClientIPTextUpdated(ce); OnClientPasswordTextUpdated(ce); OnCModeBoxSelected(ce); } /*! * Should we show tooltips? */ bool PASL::ShowToolTips() { return true; } /*! * Get bitmap resources */ wxBitmap PASL::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin PASL bitmap retrieval wxUnusedVar(name); if (name == _T("NoImage.xpm")) { wxBitmap bitmap(NoImage_xpm); return bitmap; } return wxNullBitmap; ////@end PASL bitmap retrieval } /*! * Get icon resources */ wxIcon PASL::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin PASL icon retrieval wxUnusedVar(name); if (name == _T("sandboxlogo.xpm")) { wxIcon icon(sandboxlogo_xpm); return icon; } return wxNullIcon; ////@end PASL icon retrieval } void PASL::GetError(wxProcess* MyProc) { pid = MyProc->GetPid(); err = MyProc->GetErrorStream(); if(err->CanRead()) { char *buf = new char[2048]; err->Read(buf,2048); wxMessageBox(wxString::FromAscii(buf)); } } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON */ void PASL::OnFPSLaunch( wxCommandEvent& event ) { SBProc = SBProc->Open(CurFPSc + CurRes + Shader + VSync + Map,wxEXEC_ASYNC); GetError(SBProc); event.Skip(); } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON1 */ void PASL::OnSSPLaunch( wxCommandEvent& event ) { SBProc = SBProc->Open(CurSSPc + CurRes + Shader + VSync + Map,wxEXEC_ASYNC); GetError(SBProc); event.Skip(); } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON2 */ void PASL::OnRPGLaunch( wxCommandEvent& event ) { SBProc = SBProc->Open(CurRPGc + CurRes + Shader + VSync + Map,wxEXEC_ASYNC); GetError(SBProc); event.Skip(); } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON3 */ void PASL::OnServerLaunch( wxCommandEvent& event ) { if(Mode.IsSameAs(wxT("-gfps "))) SBSProc = SBSProc->Open(CurFPSs + CurRes + Shader + VSync + Map + ServerN + ServerP + Players + Master + Ded,wxEXEC_ASYNC); if(Mode.IsSameAs(wxT("-gssp "))) SBSProc = SBSProc->Open(CurSSPs + CurRes + Shader + VSync + Map + ServerN + ServerP + Players + Master + Ded,wxEXEC_ASYNC); if(Mode.IsSameAs(wxT("-grpg "))) SBSProc = SBSProc->Open(CurRPGs + CurRes + Shader + VSync + Map + ServerN + ServerP + Players + Master + Ded,wxEXEC_ASYNC); GetError(SBSProc); event.Skip(); } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON4 */ void PASL::OnClientLaunch( wxCommandEvent& event ) { if(CMode.IsSameAs(wxT("-gfps "))) SBProc = SBProc->Open(CurFPSc + CurRes + Shader + VSync + Client,wxEXEC_ASYNC); if(CMode.IsSameAs(wxT("-gssp "))) SBProc = SBProc->Open(CurSSPc + CurRes + Shader + VSync + Client,wxEXEC_ASYNC); if(CMode.IsSameAs(wxT("-grpg "))) SBProc = SBProc->Open(CurRPGc + CurRes + Shader + VSync + Client,wxEXEC_ASYNC); GetError(SBProc); event.Skip(); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX */ void PASL::OnResBoxSelected( wxCommandEvent& event ) { wxStringTokenizer tkz(ResBox->GetValue(), wxT("x")); ResWidth = tkz.GetNextToken(); ResHeight = tkz.GetNextToken(); CurRes = wxT("-w") + ResWidth + wxT(" -h") + ResHeight + wxT(" "); event.Skip(); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX1 */ void PASL::OnShaderBoxSelected( wxCommandEvent& event ) { Shader = wxT("-f") + wxString::Format(wxT("%i"),ShaderBox->GetCurrentSelection()) + wxT(" "); event.Skip(); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX2 */ void PASL::OnVSyncSelected( wxCommandEvent& event ) { VSync = wxT("-v") + wxString::Format(wxT("%i"),VSyncBox->GetCurrentSelection()) + wxT(" "); event.Skip(); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX6 */ void PASL::OnMapBoxSelected( wxCommandEvent& event ) { Map = wxT("-l") + MapBox->GetValue() + wxT(" "); PrevImg.Destroy(); if(wxFile::Exists(MapDir + MapBox->GetValue() + wxT(".png"))) PrevImg.LoadFile(MapDir + MapBox->GetValue() + wxT(".png")); else if(wxFile::Exists(MapDir + MapBox->GetValue() + wxT(".jpg"))) PrevImg.LoadFile(MapDir + MapBox->GetValue() + wxT(".jpg")); else if(wxFile::Exists(MapDir + MapBox->GetValue() + wxT(".bmp"))) PrevImg.LoadFile(MapDir + MapBox->GetValue() + wxT(".bmp")); wxSize imgsize = PASL::ConvertDialogToPixels(wxSize(35, 35)); imgsize.Set(64,64); if(PrevImg.IsOk()) MapPrev->SetBitmap(wxBitmap(PrevImg.Rescale(imgsize.x,imgsize.y))); else MapPrev->SetBitmap(wxBitmap(GetBitmapResource(wxT("NoImage.xpm"))).ConvertToImage().Rescale(imgsize.x,imgsize.y)); event.Skip(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_TEXTCTRL */ void PASL::OnServerNameTextUpdated( wxCommandEvent& event ) { if(ServerName) ServerN = wxT("-n\"") + ServerName->GetValue() + wxT("\" "); event.Skip(); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX3 */ void PASL::OnPlayerBoxSelected( wxCommandEvent& event ) { Players = wxT("-c") + wxString::Format(wxT("%i"),PlayerBox->GetCurrentSelection()) + wxT(" "); event.Skip(); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX4 */ void PASL::OnMasterBoxSelected( wxCommandEvent& event ) { Master = wxT("-o") + wxString::Format(wxT("%i"),MasterBox->GetCurrentSelection()) + wxT(" "); event.Skip(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_TEXTCTRL1 */ void PASL::OnServerPasswordTextUpdated( wxCommandEvent& event ) { if(ServerPassword) ServerP = wxT("-p\"") + ServerPassword->GetValue() + wxT("\" "); event.Skip(); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX5 */ void PASL::OnDedBoxSelected( wxCommandEvent& event ) { if(DedBox->GetCurrentSelection() == 1) Ded = wxT("-d "); event.Skip(); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX7 */ void PASL::OnModeBoxSelected( wxCommandEvent& event ) { Mode = wxT("-g") + ModeBox->GetValue().MakeLower() + wxT(" "); event.Skip(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_TEXTCTRL2 */ void PASL::OnClientIPTextUpdated( wxCommandEvent& event ) { if(ClientIP) CIP = wxT("[ connect ") + ClientIP->GetValue() + wxT(" ]"); Client = wxT("-x\"sleep 1000 ") + CIP + CPassword + wxT("\" "); event.Skip(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_TEXTCTRL3 */ void PASL::OnClientPasswordTextUpdated( wxCommandEvent& event ) { if(ClientPassword) CPassword = wxT("[ setmaster ") + ClientPassword->GetValue() + wxT(" ]"); Client = wxT("-x\"sleep 1000 ") + CIP + CPassword + wxT("\" "); event.Skip(); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX8 */ void PASL::OnCModeBoxSelected( wxCommandEvent& event ) { CMode = wxT("-g") + CModeBox->GetValue().MakeLower() + wxT(" "); event.Skip(); } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON5 */ void PASL::OnMovieCubeButtonClick( wxCommandEvent& event ) { //SBProc = SBProc->Open(CurMovie + CurRes + Shader + VSync + Map,wxEXEC_ASYNC); SBProc = SBProc->Open(CurMovie,wxEXEC_ASYNC); GetError(SBProc); ////@begin wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON5 in PASL. // Before editing this code, remove the block markers. event.Skip(); ////@end wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON5 in PASL. } sandboxgamemaker-2.7.1+dfsg/src/launcher/PASL.rc0000664000175000017500000000003111400572314021316 0ustar showardshoward#include "wx/msw/wx.rc" sandboxgamemaker-2.7.1+dfsg/src/launcher/pasl.h0000664000175000017500000001527311400572314021357 0ustar showardshoward///////////////////////////////////////////////////////////////////////////// // Name: pasl.h // Purpose: // Author: James Burns // Modified by: // Created: 17/12/2008 19:03:58 // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// #ifndef _PASL_H_ #define _PASL_H_ /*! * Includes */ ////@begin includes #include "wx/frame.h" #include "wx/notebook.h" ////@end includes #include "wx/tokenzr.h" #include "wx/process.h" #include "wx/dir.h" #include "wx/file.h" #include "wx/utils.h" #include "wx/dc.h" #include "wx/dcclient.h" /*! * Forward declarations */ ////@begin forward declarations ////@end forward declarations /*! * Control identifiers */ ////@begin control identifiers #define ID_PASL 10000 #define ID_PANEL 10001 #define ID_COMBOBOX 10002 #define ID_COMBOBOX1 10003 #define ID_COMBOBOX2 10004 #define ID_COMBOBOX6 10021 #define ID_NOTEBOOK 10005 #define ID_PANEL1 10006 #define ID_BUTTON 10011 #define ID_PANEL2 10007 #define ID_BUTTON1 10012 #define ID_PANEL3 10008 #define ID_BUTTON2 10013 #define ID_PANEL4 10009 #define ID_TEXTCTRL 10016 #define ID_COMBOBOX3 10014 #define ID_COMBOBOX4 10015 #define ID_TEXTCTRL1 10017 #define ID_COMBOBOX5 10018 #define ID_COMBOBOX7 10024 #define ID_BUTTON3 10019 #define ID_PANEL5 10010 #define ID_TEXTCTRL2 10020 #define ID_TEXTCTRL3 10022 #define ID_COMBOBOX8 10025 #define ID_BUTTON4 10023 #define ID_PANEL6 10026 #define ID_BUTTON5 10027 #define SYMBOL_PASL_STYLE wxCAPTION|wxSYSTEM_MENU|wxCLOSE_BOX #define SYMBOL_PASL_TITLE _("SandBox Launcher") #define SYMBOL_PASL_IDNAME ID_PASL #define SYMBOL_PASL_SIZE wxSize(330, 450) #define SYMBOL_PASL_POSITION wxDefaultPosition ////@end control identifiers /*! * PASL class declaration */ class PASL: public wxFrame { DECLARE_CLASS( PASL ) DECLARE_EVENT_TABLE() public: /// Constructors PASL(); PASL( wxWindow* parent, wxWindowID id = SYMBOL_PASL_IDNAME, const wxString& caption = SYMBOL_PASL_TITLE, const wxPoint& pos = SYMBOL_PASL_POSITION, const wxSize& size = SYMBOL_PASL_SIZE, long style = SYMBOL_PASL_STYLE ); bool Create( wxWindow* parent, wxWindowID id = SYMBOL_PASL_IDNAME, const wxString& caption = SYMBOL_PASL_TITLE, const wxPoint& pos = SYMBOL_PASL_POSITION, const wxSize& size = SYMBOL_PASL_SIZE, long style = SYMBOL_PASL_STYLE ); /// Destructor ~PASL(); /// Initialises member variables void Init(); /// Creates the controls and sizers void CreateControls(); ////@begin PASL event handler declarations /// wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX void OnResBoxSelected( wxCommandEvent& event ); /// wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX1 void OnShaderBoxSelected( wxCommandEvent& event ); /// wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX2 void OnVSyncSelected( wxCommandEvent& event ); /// wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX6 void OnMapBoxSelected( wxCommandEvent& event ); /// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON void OnFPSLaunch( wxCommandEvent& event ); /// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON1 void OnSSPLaunch( wxCommandEvent& event ); /// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON2 void OnRPGLaunch( wxCommandEvent& event ); /// wxEVT_COMMAND_TEXT_UPDATED event handler for ID_TEXTCTRL void OnServerNameTextUpdated( wxCommandEvent& event ); /// wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX3 void OnPlayerBoxSelected( wxCommandEvent& event ); /// wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX4 void OnMasterBoxSelected( wxCommandEvent& event ); /// wxEVT_COMMAND_TEXT_UPDATED event handler for ID_TEXTCTRL1 void OnServerPasswordTextUpdated( wxCommandEvent& event ); /// wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX5 void OnDedBoxSelected( wxCommandEvent& event ); /// wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX7 void OnModeBoxSelected( wxCommandEvent& event ); /// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON3 void OnServerLaunch( wxCommandEvent& event ); /// wxEVT_COMMAND_TEXT_UPDATED event handler for ID_TEXTCTRL2 void OnClientIPTextUpdated( wxCommandEvent& event ); /// wxEVT_COMMAND_TEXT_UPDATED event handler for ID_TEXTCTRL3 void OnClientPasswordTextUpdated( wxCommandEvent& event ); /// wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX8 void OnCModeBoxSelected( wxCommandEvent& event ); /// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON4 void OnClientLaunch( wxCommandEvent& event ); /// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON5 void OnMovieCubeButtonClick( wxCommandEvent& event ); ////@end PASL event handler declarations void GetError(wxProcess*); ////@begin PASL member function declarations /// Retrieves bitmap resources wxBitmap GetBitmapResource( const wxString& name ); /// Retrieves icon resources wxIcon GetIconResource( const wxString& name ); ////@end PASL member function declarations /// Should we show tooltips? static bool ShowToolTips(); ////@begin PASL member variables wxComboBox* ResBox; wxComboBox* ShaderBox; wxComboBox* VSyncBox; wxComboBox* MapBox; wxStaticBitmap* MapPrev; wxButton* FPSLaunch; wxButton* SSPLaunch; wxButton* RPGLaunch; wxTextCtrl* ServerName; wxComboBox* PlayerBox; wxComboBox* MasterBox; wxTextCtrl* ServerPassword; wxComboBox* DedBox; wxComboBox* ModeBox; wxButton* ServerLaunch; wxTextCtrl* ClientIP; wxTextCtrl* ClientPassword; wxComboBox* CModeBox; wxButton* ClientLaunch; wxButton* MovieCubeButton; ////@end PASL member variables wxString RunMsg; wxString ResWidth, ResHeight, CurRes; //wxString WinExe, LinExe, CurExe; wxString WinMap, LinMap, CurMap; //wxString WinFPS, WinRPG, WinSSP; //wxString LinFPSc, LinRPGc, LinSSPc; //wxString LinFPSs, LinRPGs, LinSSPs; wxString CurFPSc, CurRPGc, CurSSPc; wxString CurFPSs, CurRPGs, CurSSPs; wxString CurMovie; wxString Shader, VSync, Map; wxString ServerN, ServerP, Players, Master, Ded, Mode, CMode; wxString CIP, CPassword, Client; wxProcess* SBProc; wxProcess* SBSProc; wxImage PrevImg; wxString MapDir, StuffDir; int pid, spid; char msg[50]; wxInputStream* err; }; #endif // _PASL_H_ sandboxgamemaker-2.7.1+dfsg/src/launcher/paslapp.h0000664000175000017500000000265011400572314022053 0ustar showardshoward///////////////////////////////////////////////////////////////////////////// // Name: paslapp.h // Purpose: // Author: James Burns // Modified by: // Created: 17/12/2008 19:03:06 // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// #ifndef _PASLAPP_H_ #define _PASLAPP_H_ /*! * Includes */ ////@begin includes #include "wx/image.h" #include "pasl.h" ////@end includes /*! * Forward declarations */ ////@begin forward declarations ////@end forward declarations /*! * Control identifiers */ ////@begin control identifiers ////@end control identifiers /*! * PASLApp class declaration */ class PASLApp: public wxApp { DECLARE_CLASS( PASLApp ) DECLARE_EVENT_TABLE() public: /// Constructor PASLApp(); void Init(); /// Initialises the application virtual bool OnInit(); /// Called on exit virtual int OnExit(); ////@begin PASLApp event handler declarations ////@end PASLApp event handler declarations ////@begin PASLApp member function declarations ////@end PASLApp member function declarations ////@begin PASLApp member variables ////@end PASLApp member variables }; /*! * Application instance declaration */ ////@begin declare app DECLARE_APP(PASLApp) ////@end declare app #endif // _PASLAPP_H_ sandboxgamemaker-2.7.1+dfsg/src/launcher/PASL.pjd0000664000175000017500000067475311400572314021523 0ustar showardshoward
0 "" "" "" "" "" 0 0 0 1 1 1 1 0 "James Burns" "" "" 0 0 0 0 "<All platforms>" "2.8.9" "Standard" "///////////////////////////////////////////////////////////////////////////// // Name: %HEADER-FILENAME% // Purpose: // Author: %AUTHOR% // Modified by: // Created: %DATE% // RCS-ID: // Copyright: %COPYRIGHT% // Licence: ///////////////////////////////////////////////////////////////////////////// " "///////////////////////////////////////////////////////////////////////////// // Name: %SOURCE-FILENAME% // Purpose: // Author: %AUTHOR% // Modified by: // Created: %DATE% // RCS-ID: // Copyright: %COPYRIGHT% // Licence: ///////////////////////////////////////////////////////////////////////////// " "///////////////////////////////////////////////////////////////////////////// // Name: %SYMBOLS-FILENAME% // Purpose: Symbols file // Author: %AUTHOR% // Modified by: // Created: %DATE% // RCS-ID: // Copyright: %COPYRIGHT% // Licence: ///////////////////////////////////////////////////////////////////////////// " "" "// For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif " " /// %BODY% " " /*! * %BODY% */ " "app_resources.h" "app_resources.cpp" "AppResources" "app.h" "app.cpp" "Application" 0 "" "MinGW Release" "iso-8859-1" "utf-8" "utf-8" "" 0 0 4 " " "" 0 0 1 0 1 1 0 1 0 0
"" "data-document" "" "" 0 1 0 0 "Configurations" "config-data-document" "" "" 0 1 0 0 "" 1 -8519680 "" "Debug" "ANSI" "Static" "Modular" "GUI" "wxMSW" "Default" "Dynamic" "Yes" "No" "Yes" "No" "No" "Yes" "Yes" "Yes" "Yes" "Yes" "Yes" "%EXECUTABLE%" "" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%WXVERSION%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" 0 1 "MinGW Release" "mingw-config-data-document" "" "" 0 1 0 0 "MinGW" 0 -8519680 "MinGW" "Release" "Unicode" "Static" "Modular" "GUI" "wxMSW" "Default" "Dynamic" "Yes" "No" "Yes" "No" "No" "Yes" "Yes" "Yes" "Yes" "Yes" "Yes" "%EXECUTABLE%" "" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%WXVERSION%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" 0 1 "GCC Release" "gcc-config-data-document" "" "" 0 1 0 0 "GCC" 0 -8519680 "GCC" "Release" "Unicode" "Static" "Modular" "GUI" "wxGTK+2" "Default" "Dynamic" "Yes" "No" "Yes" "No" "No" "Yes" "Yes" "Yes" "Yes" "Yes" "Yes" "Yes" "Yes" "%EXECUTABLE%" "" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%WXVERSION%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" 0 1 "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "%AUTO%" "Projects" "root-document" "" "project" 1 1 0 1 "Windows" "html-document" "" "dialogsfolder" 1 1 0 1 "PASLApp" "dialog-document" "" "app" 0 1 0 0 "17/12/2008" "wbAppProxy" 10000 0 "" 0 "" "Standard" 0 0 "PASLApp" "wxApp" "paslapp.cpp" "paslapp.h" "" "ID_PASL" "" "PASL" "dialog-document" "" "frame" 0 1 0 0 "17/12/2008" "wbFrameProxy" 10000 0 "" 0 "" "Standard" 0 0 "ID_PASL" 10000 "PASL" "wxFrame" "pasl.cpp" "pasl.h" "" "SandBox Launcher" 1 "sandboxlogo.xpm" 0 "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" 0 1 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "" 0 0 -1 -1 330 450 0 "" "wxPanel: ID_PANEL" "dialog-control-document" "" "panel" 0 1 0 0 "17/12/2008" "wbPanelProxy" "ID_PANEL" 10001 "" "wxPanel" "wxPanel" 1 0 "" "" "" "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "Tiled" 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 "" 1 -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "" 0 "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "17/12/2008" "wbFlexGridSizerProxy" "" "" 1 3 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "17/12/2008" "wbFlexGridSizerProxy" "" "" 3 1 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "17/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Resolution" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxComboBox: ID_COMBOBOX" "dialog-control-document" "" "combobox" 0 1 0 0 "17/12/2008" "wbComboBoxProxy" "wxEVT_COMMAND_COMBOBOX_SELECTED|OnResBoxSelected|NONE||PASL" "ID_COMBOBOX" 10002 "" "wxComboBox" "wxComboBox" 1 0 "" "" "ResBox" "640x480|800x600|1024x768|1280x960|1600x1200" "1024x768" "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 1 0 0 0 0 "" -1 -1 110 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "17/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Shaders" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxComboBox: ID_COMBOBOX1" "dialog-control-document" "" "combobox" 0 1 0 0 "17/12/2008" "wbComboBoxProxy" "wxEVT_COMMAND_COMBOBOX_SELECTED|OnShaderBoxSelected|NONE||PASL" "ID_COMBOBOX1" 10003 "" "wxComboBox" "wxComboBox" 1 0 "" "" "ShaderBox" "Off|Low|High" "Low" "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 1 0 0 0 0 "" -1 -1 70 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "17/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "VSync" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxComboBox: ID_COMBOBOX2" "dialog-control-document" "" "combobox" 0 1 0 0 "17/12/2008" "wbComboBoxProxy" "wxEVT_COMMAND_COMBOBOX_SELECTED|OnVSyncSelected|NONE||PASL" "ID_COMBOBOX2" 10004 "" "wxComboBox" "wxComboBox" 1 0 "" "" "VSyncBox" "Off|On" "Off" "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 1 0 0 0 0 "" -1 -1 60 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbFlexGridSizerProxy" "" "" 2 1 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Map" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxComboBox: ID_COMBOBOX6" "dialog-control-document" "" "combobox" 0 1 0 0 "18/12/2008" "wbComboBoxProxy" "wxEVT_COMMAND_COMBOBOX_SELECTED|OnMapBoxSelected|NONE||PASL" "ID_COMBOBOX6" 10021 "" "wxComboBox" "wxComboBox" 1 0 "" "" "MapBox" "" "" "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 1 0 0 0 0 "" -1 -1 180 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "22/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Map Image" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxStaticBitmap: wxID_STATIC" "dialog-control-document" "" "staticbitmap" 0 1 0 0 "22/12/2008" "wbStaticBitmapProxy" "wxID_STATIC" 5105 "" "wxStaticBitmap" "wxStaticBitmap" 1 0 "" "" "MapPrev" "NoImage.xpm" "" "" "" "" "" "" "" "" "" "" "" "" 0 1 "<Any platform>" 0 1 0 0 0 0 0 0 0 0 "" -1 -1 64 64 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbFlexGridSizerProxy" "" "" 1 1 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxNotebook: ID_NOTEBOOK" "dialog-control-document" "" "notebook" 0 1 0 0 "18/12/2008" "wbNotebookProxy" "ID_NOTEBOOK" 10005 "" "wxNotebook" "wxNotebook" 1 0 "" "" "" 0 "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "" -1 -1 320 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxPanel: ID_PANEL1" "dialog-control-document" "" "panel" 0 1 0 0 "18/12/2008" "wbPanelProxy" "ID_PANEL1" 10006 "" "wxPanel" "wxPanel" 1 0 "" "" "" "FPS" "" "" "" "E0DFE3" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "Tiled" 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 "" 1 -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "" 0 "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "22/12/2008" "wbFlexGridSizerProxy" "0" "" 3 1 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxButton: ID_BUTTON" "dialog-control-document" "" "dialogcontrol" 0 1 0 0 "22/12/2008" "wbButtonProxy" "wxEVT_COMMAND_BUTTON_CLICKED|OnFPSLaunch|NONE||PASL" "ID_BUTTON" 10011 "" "wxButton" "wxButton" 1 0 "" "" "FPSLaunch" "Launch" 0 "" "" "" "" "" "" "" "" "" "" "" "" 0 1 "<Any platform>" 0 0 0 0 0 0 0 0 0 "" -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxPanel: ID_PANEL2" "dialog-control-document" "" "panel" 0 1 0 0 "18/12/2008" "wbPanelProxy" "ID_PANEL2" 10007 "" "wxPanel" "wxPanel" 1 0 "" "" "" "SSP" "" "" "" "E0DFE3" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "Tiled" 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 "" 1 -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "" 0 "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbFlexGridSizerProxy" "0" "" 2 2 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxButton: ID_BUTTON1" "dialog-control-document" "" "dialogcontrol" 0 1 0 0 "19/12/2008" "wbButtonProxy" "wxEVT_COMMAND_BUTTON_CLICKED|OnSSPLaunch|NONE||PASL" "ID_BUTTON1" 10012 "" "wxButton" "wxButton" 1 0 "" "" "SSPLaunch" "Launch" 0 "" "" "" "" "" "" "" "" "" "" "" "" 0 1 "<Any platform>" 0 0 0 0 0 0 0 0 0 "" -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxPanel: ID_PANEL3" "dialog-control-document" "" "panel" 0 1 0 0 "18/12/2008" "wbPanelProxy" "ID_PANEL3" 10008 "" "wxPanel" "wxPanel" 1 0 "" "" "" "RPG" "" "" "" "E0DFE3" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "Tiled" 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 "" 1 -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "" 0 "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbFlexGridSizerProxy" "0" "" 2 2 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxButton: ID_BUTTON2" "dialog-control-document" "" "dialogcontrol" 0 1 0 0 "19/12/2008" "wbButtonProxy" "wxEVT_COMMAND_BUTTON_CLICKED|OnRPGLaunch|NONE||PASL" "ID_BUTTON2" 10013 "" "wxButton" "wxButton" 1 0 "" "" "RPGLaunch" "Launch" 0 "" "" "" "" "" "" "" "" "" "" "" "" 0 1 "<Any platform>" 0 0 0 0 0 0 0 0 0 "" -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxPanel: ID_PANEL4" "dialog-control-document" "" "panel" 0 1 0 0 "18/12/2008" "wbPanelProxy" "ID_PANEL4" 10009 "" "wxPanel" "wxPanel" 1 0 "" "" "" "Server" "" "" "" "E0DFE3" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "Tiled" 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 "" 1 -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "" 0 "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbFlexGridSizerProxy" "" "" 1 3 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbFlexGridSizerProxy" "" "" 3 1 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Server Name" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxTextCtrl: ID_TEXTCTRL" "dialog-control-document" "" "textctrl" 0 1 0 0 "18/12/2008" "wbTextCtrlProxy" "wxEVT_COMMAND_TEXT_UPDATED|OnServerNameTextUpdated|NONE||PASL" "ID_TEXTCTRL" 10016 "" "wxTextCtrl" "wxTextCtrl" 1 0 "" "" "ServerName" "Sandbox Server" 0 "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "" -1 -1 100 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Players" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxComboBox: ID_COMBOBOX3" "dialog-control-document" "" "combobox" 0 1 0 0 "18/12/2008" "wbComboBoxProxy" "wxEVT_COMMAND_COMBOBOX_SELECTED|OnPlayerBoxSelected|NONE||PASL" "ID_COMBOBOX3" 10014 "" "wxComboBox" "wxComboBox" 1 0 "" "" "PlayerBox" "0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32" "12" "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 1 0 0 0 0 "" -1 -1 60 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "MMode" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxComboBox: ID_COMBOBOX4" "dialog-control-document" "" "combobox" 0 1 0 0 "18/12/2008" "wbComboBoxProxy" "wxEVT_COMMAND_COMBOBOX_SELECTED|OnMasterBoxSelected|NONE||PASL" "ID_COMBOBOX4" 10015 "" "wxComboBox" "wxComboBox" 1 0 "" "" "MasterBox" "N|Y" "N" "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 1 0 0 0 0 "" -1 -1 50 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbFlexGridSizerProxy" "" "" 3 1 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Server Password" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxTextCtrl: ID_TEXTCTRL1" "dialog-control-document" "" "textctrl" 0 1 0 0 "18/12/2008" "wbTextCtrlProxy" "wxEVT_COMMAND_TEXT_UPDATED|OnServerPasswordTextUpdated|NONE||PASL" "ID_TEXTCTRL1" 10017 "" "wxTextCtrl" "wxTextCtrl" 1 0 "" "" "ServerPassword" "" 0 "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "" -1 -1 100 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Dedicated" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxComboBox: ID_COMBOBOX5" "dialog-control-document" "" "combobox" 0 1 0 0 "18/12/2008" "wbComboBoxProxy" "wxEVT_COMMAND_COMBOBOX_SELECTED|OnDedBoxSelected|NONE||PASL" "ID_COMBOBOX5" 10018 "" "wxComboBox" "wxComboBox" 1 0 "" "" "DedBox" "N|Y" "N" "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 1 0 0 0 0 "" -1 -1 60 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "19/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Mode" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxComboBox: ID_COMBOBOX7" "dialog-control-document" "" "combobox" 0 1 0 0 "19/12/2008" "wbComboBoxProxy" "wxEVT_COMMAND_COMBOBOX_SELECTED|OnModeBoxSelected|NONE||PASL" "ID_COMBOBOX7" 10024 "" "wxComboBox" "wxComboBox" 1 0 "" "" "ModeBox" "FPS|SSP|RPG" "FPS" "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 1 0 0 0 0 "" -1 -1 65 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "19/12/2008" "wbFlexGridSizerProxy" "" "" 3 1 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "Spacer" "dialog-control-document" "" "spacer" 0 1 0 0 "19/12/2008" "wbSpacerProxy" 5 5 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxButton: ID_BUTTON3" "dialog-control-document" "" "dialogcontrol" 0 1 0 0 "19/12/2008" "wbButtonProxy" "wxEVT_COMMAND_BUTTON_CLICKED|OnServerLaunch|NONE||PASL" "ID_BUTTON3" 10019 "" "wxButton" "wxButton" 1 0 "" "" "ServerLaunch" "Launch" 0 "" "" "" "" "" "" "" "" "" "" "" "" 0 1 "<Any platform>" 0 0 0 0 0 0 0 0 0 "" -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "Spacer" "dialog-control-document" "" "spacer" 0 1 0 0 "19/12/2008" "wbSpacerProxy" 5 5 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxPanel: ID_PANEL5" "dialog-control-document" "" "panel" 0 1 0 0 "18/12/2008" "wbPanelProxy" "ID_PANEL5" 10010 "" "wxPanel" "wxPanel" 1 0 "" "" "" "Client" "" "" "" "E0DFE3" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "Tiled" 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 "" 1 -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "" 0 "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "18/12/2008" "wbFlexGridSizerProxy" "0" "" 1 2 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "19/12/2008" "wbFlexGridSizerProxy" "" "" 2 1 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "19/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "IP Address" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxTextCtrl: ID_TEXTCTRL2" "dialog-control-document" "" "textctrl" 0 1 0 0 "19/12/2008" "wbTextCtrlProxy" "wxEVT_COMMAND_TEXT_UPDATED|OnClientIPTextUpdated|NONE||PASL" "ID_TEXTCTRL2" 10020 "" "wxTextCtrl" "wxTextCtrl" 1 0 "" "" "ClientIP" "192.168.1.100" 0 "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "" -1 -1 120 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "19/12/2008" "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Password" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxTextCtrl: ID_TEXTCTRL3" "dialog-control-document" "" "textctrl" 0 1 0 0 "19/12/2008" "wbTextCtrlProxy" "wxEVT_COMMAND_TEXT_UPDATED|OnClientPasswordTextUpdated|NONE||PASL" "ID_TEXTCTRL3" 10022 "" "wxTextCtrl" "wxTextCtrl" 1 0 "" "" "ClientPassword" "" 0 "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "" -1 -1 100 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "19/12/2008" "wbFlexGridSizerProxy" "" "" 2 1 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxStaticBoxSizer H" "dialog-control-document" "" "sizer" 0 1 0 0 "wbStaticBoxSizerProxy" "wxID_ANY" -1 "Mode" "" "" "" "" 0 1 "wxStaticBox" "Horizontal" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "<Any platform>" "wxComboBox: ID_COMBOBOX8" "dialog-control-document" "" "combobox" 0 1 0 0 "wbComboBoxProxy" "wxEVT_COMMAND_COMBOBOX_SELECTED|OnCModeBoxSelected|NONE||PASL" "ID_COMBOBOX8" 10025 "" "wxComboBox" "wxComboBox" 1 0 "" "" "CModeBox" "FPS|SSP|RPG" "FPS" "" "" "" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "" 0 1 0 0 0 0 0 "" -1 -1 70 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxButton: ID_BUTTON4" "dialog-control-document" "" "dialogcontrol" 0 1 0 0 "wbButtonProxy" "wxEVT_COMMAND_BUTTON_CLICKED|OnClientLaunch|NONE||PASL" "ID_BUTTON4" 10023 "" "wxButton" "wxButton" 1 0 "" "" "ClientLaunch" "Launch" 0 "" "" "" "" "" "" "" "" "" "" "" "" 0 1 "<Any platform>" 0 0 0 0 0 0 0 0 0 "" -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "wxPanel: ID_PANEL6" "dialog-control-document" "" "panel" 0 1 0 0 "wbPanelProxy" "ID_PANEL6" 10026 "" "wxPanel" "wxPanel" 1 0 "" "" "" "MovieCube" "" "" "" "E0DFE3" "" "" 0 1 "<Any platform>" "" "" "" "" "" "" "Tiled" 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 "" 1 -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "" 0 "wxFlexGridSizer" "dialog-control-document" "" "sizer" 0 1 0 0 "wbFlexGridSizerProxy" "0" "" 1 1 0 0 "" "<Any platform>" "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "wxButton: ID_BUTTON5" "dialog-control-document" "" "dialogcontrol" 0 1 0 0 "wbButtonProxy" "wxEVT_COMMAND_BUTTON_CLICKED|OnMovieCubeButtonClick|NONE||PASL" "ID_BUTTON5" 10027 "" "wxButton" "wxButton" 1 0 "" "" "MovieCubeButton" "Launch" 0 "" "" "" "" "" "" "" "" "" "" "" "" 0 1 "<Any platform>" 0 0 0 0 0 0 0 0 0 "" -1 -1 -1 -1 "Centre" "Centre" 0 5 1 1 1 1 0 0 0 "" "" "Sources" "html-document" "" "sourcesfolder" 1 1 0 1 "Makefile" "source-editor-document" "Makefile" "source-editor" 0 0 1 0 "22/12/2008" "" "PASL.rc" "source-editor-document" "PASL.rc" "source-editor" 0 0 1 0 "17/12/2008" "" "makefile.gcc" "source-editor-document" "makefile.gcc" "source-editor" 0 0 1 0 "17/12/2008" "" "Images" "html-document" "" "bitmapsfolder" 1 1 0 1 "NoImage.xpm" "image-document" "NoImage.xpm" "image" 0 0 0 0 "22/12/2008" 100 "sandboxlogo.xpm" "image-document" "sandboxlogo.xpm" "image" 0 0 0 0 "22/12/2008" 100
sandboxgamemaker-2.7.1+dfsg/src/launcher/sandboxlogo.xpm0000664000175000017500000000235411400572314023310 0ustar showardshoward/* XPM */ static char * sandboxlogo_xpm[] = { "32 32 1 1", " c None", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "}; sandboxgamemaker-2.7.1+dfsg/src/launcher/makefile.gcc0000664000175000017500000000476111400572314022502 0ustar showardshoward### Begin DialogBlocks generated body ################################################################################ # Makefile generated by DialogBlocks # # # Available configurations: # release ################################################################################ CONFIG=release # release ifeq ($(CONFIG),release) WXWIN=C:/wxWidgets-2.8.10 GCCFLAGS= CXX=g++.exe LINKER=g++.exe CC=gcc.exe RESCOMP=windres.exe OUTPUTPATH=MinGWRelease OBJECTPATH=MinGWRelease BUILDPATHS=$(OBJECTPATH) CPPFLAGS= -fno-rtti -fno-pcc-struct-return -fstrict-aliasing -Wall -Wno-write-strings -D__WXMSW__ -D__GNUWIN32__ -D__WIN95__ -DUNICODE WARNINGFLAGS=-Wall -Wno-write-strings OPTFLAGS=-O2 DEBUGFLAGS= LINKERFLAGS=-Wl,--subsystem,windows -mwindows LIBS= -lwxmsw28u_richtext -lwxmsw28u_aui -lwxmsw28u_html -lwxmsw28u_xrc -lwxmsw28u_adv -lwxmsw28u_core -lwxbase28u -lwxbase28u_net -lwxbase28u_xml -lwxtiff -lwxjpeg -lwxpng -lwxzlib -lwxregexu -lwxexpat -lkernel32 -luser32 -lgdi32 -lcomdlg32 -lwinspool -lwinmm -lshell32 -lcomctl32 -lole32 -loleaut32 -luuid -lrpcrt4 -ladvapi32 -lwsock32 CPPINC=-I"$(WXWIN)/include" -I"$(WXWIN)/contrib/include" -I"$(WXWIN)/lib/gcc_lib/mswu" LIBPATH=-L"$(WXWIN)/lib/gcc_lib" RESPATH=--include-dir "$(WXWIN)/include" --include-dir "$(WXWIN)/contrib/include" --include-dir "$(WXWIN)/lib/gcc_lib/mswu" PROGRAM=PASL.exe RCFILEOBJ=PASL_rc.o RCFILESRC=PASL.rc endif OBJECTS=$(OBJECTPATH)/pasl.o $(OBJECTPATH)/paslapp.o $(OBJECTPATH)/$(RCFILEOBJ) all: $(BUILDPATHS) $(OUTPUTPATH)/$(PROGRAM) $(OBJECTPATH): -if not exist $(OBJECTPATH) mkdir $(OBJECTPATH) clean: -if exist $(OBJECTPATH)\*.o del $(OBJECTPATH)\*.o -if exist $(OBJECTPATH)\*.res del $(OBJECTPATH)\*.res -if exist $(OUTPUTPATH)\$(PROGRAM) del $(OUTPUTPATH)\$(PROGRAM) help: @echo "Usage: make -f makefile.gcc CONFIG=[release] [all|clean|help]" $(OUTPUTPATH)/$(PROGRAM): $(OBJECTS) $(LINKER) -o $@ $(OBJECTS) $(LIBPATH) $(LINKERFLAGS) $(LIBS) $(OBJECTPATH)/$(RCFILEOBJ): $(RCFILESRC) $(RESCOMP) --use-temp-file -i$< -o$@ $(RESPATH) --include-dir . --define NOPCH $(OBJECTPATH)/pasl.o: pasl.cpp pasl.h sandboxlogo.xpm NoImage.xpm $(CXX) -c -o $@ $(CPPFLAGS) $(GCCFLAGS) $(DEBUGFLAGS) $(OPTFLAGS) $(WARNINGFLAGS) $(CPPINC) pasl.cpp $(OBJECTPATH)/paslapp.o: paslapp.cpp paslapp.h pasl.h $(CXX) -c -o $@ $(CPPFLAGS) $(GCCFLAGS) $(DEBUGFLAGS) $(OPTFLAGS) $(WARNINGFLAGS) $(CPPINC) paslapp.cpp .PHONY: all clean ### End DialogBlocks generated body sandboxgamemaker-2.7.1+dfsg/src/READMELINUX0000664000175000017500000000174011400572342020141 0ustar showardshowardLinux Users, chances are you'll need to compile the server and the client from source. The source files are unfortunately in DOS format, so you'll need to search your distrution's package manager for a utility names 'tofrodos'. While it's harmless, the enet files WILL cause problems while in DOS format once that's done installing, just open a terminal and copy the following line into it, after changing your directory the src/ fromdos enet/* && fromdos enet/*/* && chmod +x enet/configure && make install for any subsequent builds, make clean and make install are all you'll need. Make sure you have the needed SDL libs installed. normal sdl, with sdl mixer, and sdl image, and probably other packages like smpeg and timidity to allow sdl_mixer to access additional audio formats. alternatively, if you wish, you can just type sh build.sh and it'll take care of pretty much everything for further information, take a look at the wiki http://kids.platinumarts.net/wikisandboxgamemaker-2.7.1+dfsg/src/sb/0000775000175000017500000000000011660234756017057 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/sb/extentity.cpp0000664000175000017500000000305711442705014021611 0ustar showardshoward#include "extentity.h" namespace Extentities { ObjectGenerator generator; HandlerFactory handler; void RegisterStdHandler() { puts("init: register Extentities"); handler.Register(NOTUSED); handler.Register(LIGHT); handler.Register(MAPMODEL); handler.Register(PLAYERSTART); handler.Register(ENVMAP); handler.Register(PARTICLES); handler.Register(MAPSOUND); handler.Register(SPOTLIGHT); handler.Register(TELEPORT); handler.Register(TELEDEST); handler.Register(MONSTER); handler.Register(JUMPPAD); handler.Register(BOX); handler.Register(BARREL); handler.Register(PLATFORM); handler.Register(ELEVATOR); handler.Register(WAYPOINT); handler.Register(CAMERA); handler.Register(DYNLIGHT); handler.Register(GENERIC); } extentity *NewEntity() { // return new Extentities::Extentity(); return generator.New(); } void DeleteEntity(extentity *e) { delete (Extentities::Extentity *)e; } HandlerFactory& Handler() { return handler; } ObjectGenerator& Generator() { return generator; } void Destroy() { return; } } sandboxgamemaker-2.7.1+dfsg/src/sb/objectgenerator.h0000664000175000017500000000072311442705014022373 0ustar showardshoward#ifndef SB_OBJECTGENERATOR_H_INCLUDED #define SB_OBJECTGENERATOR_H_INCLUDED template inline Base *NewObject() { return new Derived(); } template class ObjectGenerator { protected: typedef Base *(*ObjectPtr)(); ObjectPtr constructor; public: template void Init() { constructor = &NewObject; } Base* New() { return constructor(); } }; #endif // SB_OBJECTGENERATOR_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/sb/singleton.h0000664000175000017500000000043111442705014021214 0ustar showardshoward#ifndef SB_SINGELTON_H_INCLUDED #define SB_SINGELTON_H_INCLUDED template class Singleton { public: static T& Get () { static T inst; return inst; } private: Singleton( const Singleton& ) {} protected: Singleton () { } }; #endif // SB_SINGELTON_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/sb/README0000664000175000017500000000042311421064656017731 0ustar showardshowardclasses for command queuing: changelog: 20100708 *currently broken, changing access to QueuedCommandMgr::current 20100712 * TODO: *virtual gettype method for Action (exception handling on bad cast) *common entity lookup table *userdata for signals documentation: soon sandboxgamemaker-2.7.1+dfsg/src/sb/objectfactory.h0000664000175000017500000001111011442705014022044 0ustar showardshoward#ifndef SB_OBJECT_FACTORY_H_INCLUDED #define SB_OBJECT_FACTORY_H_INCLUDED #include "cube.h" //factory templates for registering types by an id (e.g. int or c-strings) //this is useful to create objects given by strings from cube script or for //writing handlers classes for entities which could be registered by using entity::type // ////usage: // ObjectFactory factory; // // factory.Register("identifier")); // // DerivedClass *dc = factory.Create("identifier"); // // factory.Unregister("identifier"); template class ObjectFactory; template inline BaseType *CreateObject() { return new Type(); } template inline BaseType *CreateObject(TypeParam param) { return new Type(param); } template class ObjectFactory { protected: typedef BaseType *(*CreateObjectFunc)(); hashtable creator; public: template bool Register(TypeID id) { if(creator.access(id)) { conoutf("ObjectFactory::Register: error - key found"); return false; } else { creator[id] = &CreateObject; } return true; } bool Unregister(TypeID id) { if(!creator.access(id)) { conoutf("ObjectFactory::Register: error - key not found"); return false; } return creator.remove(id); } BaseType* Create(TypeID id) { if(!*creator.access(id)) { conoutf("ObjectFactory::Create: not found"); return NULL; } else { return creator[id](); } } }; template class ObjectFactory { protected: typedef BaseType *(*CreateObjectFunc)(TypeParam); hashtable creator; public: template bool Register(TypeID id) { if(creator.access(id)) { conoutf("ObjectFactory::Register: error - key found"); return false; } else { creator[id] = &CreateObject< BaseType, TypeParam, Type >; } return true; } bool Unregister(TypeID id) { if(!creator.access(id)) { conoutf("ObjectFactory::Register: error - key not found"); return false; } return creator.remove(id); } BaseType* Create(TypeID id, TypeParam param) { if(!creator.access(id)) { conoutf("ObjectFactory::Create: not found"); return NULL; } else { return creator[id](param); } } }; template class ObjectFactory { protected: typedef BaseType *(*CreateObjectFunc)(); hashtable creator; public: template bool Register(const char* id) { const char* key = newstring(id); if(creator.access(key)) { conoutf("ObjectFactory::Register: error - key found"); return false; } else { creator[id] = &CreateObject; } return true; } bool Unregister(const char* id) { const char* key = newstring(id); if(!creator.access(key)) { conoutf("ObjectFactory::Unregister error - key not found"); return false; } return creator.remove(key); } BaseType* Create(const char* id) { const char* key = newstring(id); if(!creator.access(key)) { conoutf("ObjectFactory::Create: not found"); return NULL; } else { return creator[key](); } } }; template class ObjectFactory { protected: typedef BaseType *(*CreateObjectFunc)(); vector creator; public: template bool Register(int id) { if( creator.inrange(id) ) { if ( creator[id] ) { conoutf("ObjectFactory::Register: error - key found"); return false; } else { creator[id] = &CreateObject; return true; } } else { while( creator.length() <= id ) creator.add(NULL); creator[id] = &CreateObject; } return true; } bool Unregister(int id) { if(!creator[id]) { conoutf("ObjectFactory::Register: error - key not found"); return false; } creator[id] = NULL; return true; } BaseType* Create(int id) { conoutf("ObjectFactory::Create(int id)"); if(!creator.inrange(id) || !creator[id]) { conoutf("ObjectFactory::Create: not found"); return NULL; } else { conoutf("ObjectFactory::Create: found"); return creator[id](); } } }; #endif // SB_OBJECT_FACTORY_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/sb/handlerfactory.h0000664000175000017500000000500511442705014022221 0ustar showardshoward#ifndef SB_HANDLERFACTORY_H_INCLUDED #define SB_HANDLERFACTORY_H_INCLUDED #include "cube.h" //factory templates for handler classes //usefull for writing handler classes that implements entities or network messages // // //HandlerFactory factory; //factory.Register(LIGHT); //factory.Register(MAPMODEL); // ... //factory[e->type]->fixentity(); template class HandlerFactory { protected: hashtable handler; public: template bool Register(TypeID id) { if(handler.access(id)) { return false; } else { handler.access(id, new Type); } return true; } bool Unregister(TypeID id) { if(!handler.access(id)) { return false; } return handler.remove(id); } BaseType* operator[](TypeID id) { return handler.access(id) ? handler[id] : NULL; } const BaseType* operator[](TypeID id) const { return handler.access(id) ? handler[id] : NULL; } }; template class HandlerFactory { protected: vector handler; public: template bool Register(int id) { if( handler.inrange(id) ) { if ( handler[id] ) { return false; } else { handler[id] = new Type(); return true; } } else { while( handler.length() < id ) { handler.add(); } handler.add(new Type); } return true; } bool Unregister(int id) { if(!handler[id]) { return false; } delete handler[id]; handler[id] = NULL; return true; } BaseType* operator[](int id) { return handler.inrange(id) ? handler[id] : NULL; } const BaseType* operator[](int id) const { return handler.inrange(id) ? handler[id] : NULL; } }; template class HandlerFactory { protected: hashtable handler; public: template bool Register(const char* id) { const char* key = newstring(id); if(handler.access(key)) { return false; } else { handler.access(key, new Type); } return true; } bool Unregister(const char* id) { const char* key = newstring(id); if(!handler.access(key)) { return false; } return handler.remove(key); } BaseType* operator[](const char* id) { const char* key = newstring(id); return handler.access(key) ? handler[key] : NULL; } const BaseType* operator[](const char* id) const { const char* key = newstring(id); return handler.access(key) ? handler[key] : NULL; } }; #endif // SB_HANDLERFACTORY_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/sb/extentityhandler.h0000664000175000017500000001134511442705014022613 0ustar showardshoward#ifndef STATICENTITYHANDLER_H_INCLUDED #define STATICENTITYHANDLER_H_INCLUDED #include "cube.h" //Basic Handler Class for extentities //implements the entities namespcace from igame.h ///TODO: ///*do not query types in handlers, use caps ///*query caps in Teleport (for CAP_TELEDEST) ///*remove second text under entities //capilities of an entity enum EntityCap { CAP_NONE = 0, CAP_TELEPORT = 1 << 0, CAP_TELEDEST = 1 << 1, CAP_TRIGGER = 1 << 2, CAP_JUPPAD = 1 << 3, CAP_ATTACH = 1 << 4, CAP_PICKUP = 1 << 5 }; class EntityHandler { public: EntityHandler(); virtual ~EntityHandler(); virtual const char *getname(); virtual const char *getmodel(); virtual int *getmodelattr(extentity &e); virtual void fix(extentity &e); virtual bool hasradius(); virtual bool hasdir(extentity &e); virtual bool hascap(EntityCap cap); virtual bool info(extentity &e, char *buf); //printent virtual const char *info(entity &e); //entnameinfo virtual const int numattrs(); virtual void renderhelper(extentity &e, bool &color); virtual void renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp); virtual float getdropheight(entity &e); virtual bool checkmodelusage(extentity &e, int i); virtual void writeent(entity &e, char *buf); // write any additional data to disk (except for ET_ ents) virtual void readent(entity &e, char *buf); // read from disk, and init protected: char* typestring; char* model; bool radius; bool dir; int numattr; float dropheight; EntityCap cap; }; class EntityHandlerLight : public EntityHandler { public: EntityHandlerLight(); }; class EntityHandlerMapmodel : public EntityHandler { public: EntityHandlerMapmodel(); void renderhelper(extentity &e, bool &color); }; class EntityHandlerPlayerstart : public EntityHandler { public: EntityHandlerPlayerstart(); }; class EntityHandlerEnvmap : public EntityHandler { public: EntityHandlerEnvmap(); }; class EntityHandlerParticles : public EntityHandler { public: EntityHandlerParticles(); }; class EntityHandlerMapsound : public EntityHandler { public: EntityHandlerMapsound(); }; class EntityHandlerSpotlight : public EntityHandler { public: EntityHandlerSpotlight(); }; class EntityHandlerTeleport : public EntityHandler { public: EntityHandlerTeleport(); void renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp); int *getmodelattr(extentity &e); bool checkmodelusage(extentity &e, int i); void renderhelper(extentity &e, bool &color); }; class EntityHandlerTeledest : public EntityHandler { public: EntityHandlerTeledest(); void fix(extentity &e); void renderhelper(extentity &e, bool &color); void renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp); }; class EntityHandlerMonster : public EntityHandler { public: EntityHandlerMonster(); }; class EntityHandlerJumppad : public EntityHandler { public: EntityHandlerJumppad(); void renderhelper(extentity &e, bool &color); void renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp); }; ///TODO: Put all Movable Ents under a base class class EntityHandlerBox : public EntityHandler { public: EntityHandlerBox(); void fix(extentity& e); void renderhelper(extentity &e, bool &color); void renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp); int *getmodelattr(extentity &e); bool checkmodelusage(extentity &e, int i); }; class EntityHandlerBarrel : public EntityHandler { public: EntityHandlerBarrel(); }; class EntityHandlerPlatform : public EntityHandler { public: EntityHandlerPlatform(); void fix(extentity& e); void renderhelper(extentity &e, bool &color); void renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp); int *getmodelattr(extentity &e); bool checkmodelusage(extentity &e, int i); }; class EntityHandlerElevator : public EntityHandler { public: EntityHandlerElevator(); }; class EntityHandlerWaypoint : public EntityHandler { public: EntityHandlerWaypoint(); void fix(extentity& e); void renderhelper(extentity &e, bool &color); void renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp); }; class EntityHandlerCamera : public EntityHandler { public: EntityHandlerCamera(); void renderhelper(extentity &e, bool &color); void renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp); }; class EntityHandlerDynlight : public EntityHandler { public: EntityHandlerDynlight(); void renderhelper(extentity &e, bool &color); void renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp); }; class EntityHandlerGeneric : public EntityHandler { public: EntityHandlerGeneric(); void fix(extentity& e); void renderhelper(extentity &e, bool &color); }; #endif // STATICENTITYHANDLER_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/sb/qcscript.h0000664000175000017500000000365611421064656021065 0ustar showardshoward#ifndef QCSCRIPT_H_INCLUDED #define QCSCRIPT_H_INCLUDED #include "cube.h" #include "qcommand.h" //ActionDbg: use for debug reasons, will echo a string and the pointer address of the instance class ActionDbg : public Action { public: ActionDbg(const char *e); ~ActionDbg(); bool checktype(); bool process(); private: char* str; }; //ActionPack: empty Action for wrapping general scripting command (e.g echo) class ActionPack : public Action { public: ActionPack(const char* c); ~ActionPack(); bool process(); }; //ActionDelay: delays the execution of the script in the body n seconds class ActionDelay : public Action { public: ActionDelay(float sec, const char *c); ~ActionDelay(); void init(); bool process(); private: int millis; int start; }; //ActionWatch: waits until an alias has a specified value class ActionWatch : public Action { public: ActionWatch(const char* _alias, int _val, const char* c); ~ActionWatch(); bool process(); private: int val; char* alias; }; //ActionSigHandler: adds an signal handler to an signal, that is emmited by an Instance class ActionSigHandler : public Action { public: ActionSigHandler(const char* signal, const char* c); ~ActionSigHandler(); bool update(); bool process(); private: char* signal; }; class ActionChangeState : public Action { public: ActionChangeState(int i); ~ActionChangeState(); bool process(); private: int state; }; //ActionTest: test equal against an alias, if true body will be executed class ActionTest : public Action { public: ActionTest(const char* _alias, int _val, const char* c); ~ActionTest(); bool update(); bool process(); private: int val; char* alias; }; class ActionAtOnce : public Action { public: ActionAtOnce(const char* body); ~ActionAtOnce(); bool update(); bool process(); }; #endif // QCSCRIPT_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/0000775000175000017500000000000011660234754021616 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/instance.cpp0000664000175000017500000000434211442705014024117 0ustar showardshoward#include "entityscript/instance.h" namespace EntityScript { Instance::Instance(Script& s) : script(s) { //will not work as intened in derived types registercallback("default", "i"); registercallback("waiting"); //additional signals - if already registered, ignore hashtable &signals = script.getsignals(); enumeratekt(signals, const char *, _signal, const char *, _fmt, registercallback(_signal, _fmt)); int val = 10; emmitsignal("default", "i", val); } Instance::~Instance() { //dtor } void Instance::process() { if ( callbacks.last()->process() ) { //test exist callback waiting ? emmit : remove from execution stack callbacks.drop(); if ( callbacks.empty() ) emmitsignal("waiting"); } } //query key exist: signals.access(name) //query value: *signals.access(name) void Instance::registercallback(const char* name, const char* fmt) { //test if callback is given in script if ( script.getstate( name )) { if( ! signals.access( name )) { signals.access( name, new Signal(fmt)); } else { conoutf("Instance::registercallback: callback %s already registered", name); } } } void Instance::emmitsignal(const char* sig, const char *fmt, ...) { va_list args; va_start(args, fmt); Signal* signal = getsignal(sig); const char* body = script.getstate(sig); if ( ! signal || ! body ) return; signal->parseparams(args); va_end(args); callbacks.add( new ActionCallback(*this, *signal, body) ); } inline void Instance::emmitsignal(const char* sig) { emmitsignal(sig, NULL); } void Instance::emmitsignal(const char* sig, char** args, int num) { Signal* signal = getsignal(sig); const char* body = script.getstate(sig); if ( ! signal || ! body ) return; signal->parseparams(args, num); callbacks.add( new ActionCallback(*this, *signal, body) ); } const char* Instance::getsignalfmt(const char* signal) { return (*signals.access(signal))->getfmt(); } Signal* Instance::getsignal(const char* signal) { if (signals.access(signal)) return signals[signal]; else return NULL; } void Instance::getcallbackparam(int i) { callbacks.last()->getparam(i); } void Instance::debug() { conoutf("Instance::debug"); } } sandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/scriptmanager.cpp0000664000175000017500000000152311442705014025150 0ustar showardshoward#include "entityscript/scriptmanager.h" namespace EntityScript { ScriptManager::ScriptManager() {} ScriptManager::~ScriptManager() {} Instance* ScriptManager::Create(const char* type, const char* script_name) { Script* script = findscript(script_name); if (! script ) { return NULL; } return ObjectFactory::Create(type, *script); } void ScriptManager::newscript(const char* type, const char* name, const char* body) { char* key = newstring(name); if(!scripts.access(key)) { scripts.access(key, new Script(type, body)); } else { conoutf("[DEBUG] ScriptManager::newscript: script already exists - overwriting not implemented"); } } Script* ScriptManager::findscript(const char* name) { char* key = newstring(name); if(Script** script = scripts.access(key)) { return *script; } return NULL; } } sandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/action.cpp0000664000175000017500000000403111442705014023563 0ustar showardshoward#include "entityscript/action.h" namespace EntityScript { Action* current_action = NULL; Action::Action(const char *b) : parent(current_action), instance(current_action->getInstance()), proc_ptr(&Action::process_self), body(b) { // conoutf("Action::Action: parent: %p, instance"); } Action::Action(Instance& inst, const char *b) : parent(current_action), instance(inst), proc_ptr(&Action::process_self), body(b) { // conoutf("Action::Action: parent: %p, instance"); } Action::~Action() {} bool Action::process() { return (this->*proc_ptr)(); } bool Action::process_self() { if( update() ) { if ( body && action_lock() ) { execute(body); proc_ptr = &Action::process_children; action_unlock(); } else { proc_ptr = &Action::process_post; } } return false; } inline Instance& Action::getinstance() { return instance; } bool Action::process_children() { if ( pending.empty() ) { proc_ptr = &Action::process_post; return false; } if ( pending[0]->process() ) { delete pending.remove(0); } return false; } bool Action::process_post() { return true; } inline Instance& Action::getInstance() { return instance; } bool Action::update() { return true; } bool Action::action_lock() { if ( !current_action ) { current_action = this; return true; } return false; } bool Action::action_unlock() { if ( current_action == this ) { current_action = NULL; return true; } return false; } ActionCallback::ActionCallback(Instance& inst, Signal& sig, const char *b) : Action(inst, b), signal(sig) {} void ActionCallback::getparam(int i) { signal.getparam(i); } ICOMMAND(emmit, "sV", (char* sig, char** arg, int* num), { if (! current_action) { puts("no current action"); return; } current_action->getinstance().emmitsignal(sig, arg, *num); } ); ICOMMAND(param, "i", (int* i), { if (! current_action) { puts("no current action"); return; } current_action->getinstance().getcallbackparam(*i); } ); } sandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/script.cpp0000664000175000017500000000305111442705014023613 0ustar showardshoward#include "entityscript/script.h" namespace EntityScript { Script* current_script; Script::Script(const char* _type, const char* body) : type(newstring(_type)) { if ( script_lock() ) { execute(body); script_unlock(); } } Script::~Script() { delete[] type; } void Script::addstate(const char* signal, const char* body) { if(!states.access(signal)) { states.access( newstring(signal), newstring(body)); } else { conoutf("[DEBUG] Script::addstate: state already exists"); } } void Script::addsignal(const char* signal, const char* fmt) { if(!signals.access(signal)) { conoutf("Script::addsignal - adding custom signal: %s, %s", signal, fmt); signals.access( newstring(signal), newstring(fmt)); } else { conoutf("[DEBUG] Script::addsignal: signal already exists"); } } hashtable &Script::getsignals() { return signals; } const char* Script::getstate(const char* state) { return states.access(state) ? states[state] : NULL; } bool Script::script_lock() { if ( !current_script ) { current_script = this; return true; } return false; } bool Script::script_unlock() { if ( current_script == this ) { current_script = NULL; return true; } return false; } ICOMMAND(connect, "ss", (char* sig, char* body), { if(!current_script) { return; } current_script->addstate(sig, body); } ); ICOMMAND(callback, "ss", (char* sig, char* fmt), { if(!current_script) { return; } current_script->addsignal(sig, fmt); } ); } sandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/signal.cpp0000664000175000017500000000547111442705014023574 0ustar showardshoward#include "signal.h" namespace EntityScript { Signal::Signal(const char* _fmt) : fmt(newstring(_fmt && *_fmt ? _fmt : "")) { while(_fmt && *_fmt) switch(*_fmt++) { case 'i': { ident* id_var = new ident(ID_VAR, "param", 0, 0, 0, new int); params.add(id_var); break; } case 'f': { ident* id_float = new ident(ID_FVAR, "param", 0, 0, 0, new float); params.add(id_float); break; } case 's': ident* id_string = new ident(ID_SVAR, "param", newstring(""), new char*); *id_string->storage.s = NULL; params.add(id_string); break; } } const char* Signal::getfmt() { return fmt; } void Signal::getparam(int i) { if ( params.inrange (i) ) { switch(params[i]->type) { case ID_VAR: intret(*params[i]->storage.i); break; case ID_FVAR: floatret(*params[i]->storage.f); break; case ID_SVAR: result(*params[i]->storage.s); } } else { result(""); } } void Signal::parseparams(char* args) { const char* f = fmt; if(f) { int i = 0; while(*f) switch(*f++) { case 'i': { int val = va_arg(args, int); conoutf("Signal::parseparam: found %d", val); *params[i]->storage.i = val; break; } case 's': { char* val = va_arg(args, char*); conoutf("Signal::parseparam: found %s", val); if(*params[i]->storage.s) delete[] *params[i]->storage.s; *params[i]->storage.s = newstring(val); break; } case 'f': { float val = (float)va_arg(args, double); conoutf("Signal::parseparam: found %f", val); *params[i]->storage.f = val; break; } } } } void Signal::parseparams(char** args, int num) { const char *f = fmt; loopi(num) if(*f) { switch(*f) { case 'i': { conoutf("Signal::parseparam: found arg[%d] int %s", i+1, args[i+1]); ident *id = params[i]; *id->storage.i = atoi(args[i+1]); break; } case 's': { conoutf("Signal::parseparam: found char* %s", args[i+1]); if(*params[i]->storage.s) delete[] *params[i]->storage.s; *params[i]->storage.s = newstring(args[i+1]); break; } case 'f': { conoutf("Signal::parseparam: found float: %s", args[i+1]); *params[i]->storage.f = atof(args[i+1]); break; } } f++; } } Signal::~Signal() { delete[] fmt; params.deletecontents(); } } sandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/instance.h0000664000175000017500000000201511442705014023557 0ustar showardshoward#ifndef SB_ENTITYSCIPTINSTANCE_H #define SB_ENTITYSCIPTINSTANCE_H #include "cube.h" #include "entityscript/action.h" #include "entityscript/script.h" #include "entityscript/signal.h" ///TODO: //template instance //Template Types based Instance Type and Callbacks //create temporary new types based on definition ///TODO: move getcallbackparam into action namespace EntityScript { class ActionCallback; class Instance { Script& script; vector callbacks; hashtable signals; protected: void registercallback(const char* name, const char* fmt = NULL); Signal* getsignal(const char*); const char* getcallback(const char*); public: Instance(Script& s); virtual ~Instance(); void process(); void debug(); void emmitsignal(const char* sig, const char *fmt, ...); void emmitsignal(const char* sig); void emmitsignal(const char* sig, char**, int); const char* getsignalfmt(const char* sig); void getcallbackparam(int i); }; } #endif // SB_ENTITYSCIPTINSTANCE_H sandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/signal.h0000664000175000017500000000064311442705014023235 0ustar showardshoward#ifndef SB_ENTITYSCRIPT_SIGNAL_H #define SB_ENTITYSCRIPT_SIGNAL_H #include "cube.h" //should be also an action namespace EntityScript { class Signal { const char* fmt; vector params; public: Signal(const char* _fmt = NULL); ~Signal(); const char* getfmt(); void getparam(int i); void parseparams(char*); void parseparams(char**, int num); }; } #endif // SB_ENTITYSCRIPT_SIGNAL_H sandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/script.h0000664000175000017500000000115311442705014023261 0ustar showardshoward#ifndef SB_ENTITYSCRIPT_H_INCLUDED #define SB_ENTITYSCRIPT_H_INCLUDED #include "cube.h" namespace EntityScript { class Script { const char* type; bool script_lock(); bool script_unlock(); hashtable states; hashtable signals; public: Script(const char* type, const char* body); ~Script(); void addstate(const char* signal, const char* body); void addsignal(const char* signal, const char* fmt); hashtable &getsignals(); const char* getstate(const char* state); }; } #endif // SB_ENTITYSCRIPT_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/scriptmanager.h0000664000175000017500000000112011442705014024606 0ustar showardshoward#ifndef SB_ENTITYSCRIPTMANAGER_H #define SB_ENTITYSCRIPTMANAGER_H #include "cube.h" #include "objectfactory.h" #include "entityscript/script.h" #include "entityscript/instance.h" namespace EntityScript { class ScriptManager : public ObjectFactory< Instance (Script&), const char* > { hashtable scripts; public: ScriptManager(); ~ScriptManager(); Instance* Create(const char* type, const char* script); void newscript(const char* type, const char* name, const char* body); Script* findscript(const char* s); }; }; #endif // SB_ENTITYSCRIPTMANAGER_H sandboxgamemaker-2.7.1+dfsg/src/sb/entityscript/action.h0000664000175000017500000000175211442705014023237 0ustar showardshoward#ifndef SB_Action_H_INCLUDED #define SB_Action_H_INCLUDED #include "cube.h" #include "entityscript/instance.h" #include "entityscript/signal.h" namespace EntityScript { class Instance; //Action Interface class Action { Action* parent; Instance& instance; bool (Action::*proc_ptr)(); Instance& getInstance(); virtual bool process_self(); bool action_lock(); bool action_unlock(); public: Action(const char *body); Action(Instance& instance, const char *body); virtual ~Action(); bool process(); Instance& getinstance(); protected: const char* body; vector pending; virtual bool process_children(); virtual bool process_post(); virtual bool update(); }; //Action stays on top of an Action Chain, called as Callback Action class ActionCallback : public Action { Signal& signal; public: ActionCallback(Instance& instance, Signal& signal, const char *body); void getparam(int i); }; } #endif // SB_Action_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/sb/testscript.cpp0000664000175000017500000000227011442705014021754 0ustar showardshoward#include "cube.h" #include "entityscript/scriptmanager.h" #include "entityscript/instance.h" ////Test Script //test_def test tname [ // //buildt in signals // connect "default" [ echo execute state default, arg: (param 0)] // connect "waiting" [ echo EMMIT ARGTEST; emmit argtest 10 lala 20 10; echo END] // // //own signals // callback "argtest" "isi" // connect "argtest" [ echo callback argtest - args are (param 0) (param 1) (param 2) ] //] // //test_instance tname namespace EntityScript { class InstanceTest : public Instance { public: InstanceTest(Script& s) : Instance(s) {} ~InstanceTest() {} void process() {} void debug() { conoutf("InstanceTest"); } }; vector instances; ScriptManager manager; void TestInit() { manager.Register("test"); } void TestNewInstance(const char* s) { Instance* test = manager.Create("test", s); if ( test ) { test->debug(); for(int i = 0; i < 10; i++) test->process(); } } ICOMMAND(test_entityscript, "", (), TestInit()); ICOMMAND(test_def, "sss", (char* type, char* name, char* body), manager.newscript(type, name, body)); ICOMMAND(test_instance, "s", (char* s), TestNewInstance(s)); } sandboxgamemaker-2.7.1+dfsg/src/sb/extentity.h0000664000175000017500000000423411442705014021254 0ustar showardshoward#ifndef SB_EXTENTITY_H_INCLUDED #define SB_EXTENTITY_H_INCLUDED #include "cube.h" #include "handlerfactory.h" #include "objectgenerator.h" #include "extentityhandler.h" ///TODO: ///*add something like an adapter for Extentity, result should be something like: ///Exentities::Init(); ///which can be used to work with derived Extentity Types (newentity, delentity should know these types) /// ///*use HandlerFactory<...>::Register(int typeid, const char unique_name, bool check_unique_name = true) enum // static entity types { NOTUSED = ET_EMPTY, // entity slot not in use in map LIGHT = ET_LIGHT, // lightsource, attr1 = radius, attr2 = intensity MAPMODEL = ET_MAPMODEL, // attr1 = angle, attr2 = idx PLAYERSTART = ET_PLAYERSTART,// attr1 = angle, attr2 = team ENVMAP = ET_ENVMAP, // attr1 = radius PARTICLES = ET_PARTICLES, MAPSOUND = ET_SOUND, SPOTLIGHT = ET_SPOTLIGHT, TELEPORT = ET_GAMESPECIFIC, // attr1 = idx TELEDEST, // attr1 = angle, attr2 = idx MONSTER, // attr1 = angle, attr2 = monstertype JUMPPAD, // attr1 = zpush, attr2 = ypush, attr3 = xpush BOX, // attr1 = angle, attr2 = idx, attr3 = weight BARREL, // attr1 = angle, attr2 = idx, attr3 = weight, attr4 = health PLATFORM, // attr1 = angle, attr2 = idx, attr3 = tag, attr4 = speed ELEVATOR, // attr1 = angle, attr2 = idx, attr3 = tag, attr4 = speed WAYPOINT, CAMERA, //attr1 = pitch, attr2 = yaw, attr3 = focus DYNLIGHT, GENERIC, MAXBASICENTTYPES }; namespace Extentities { //just a placeholder for the moment, will store a reference to an object listed //in a map object registry or toc class Extentity : public extentity { public: virtual ~Extentity() {} }; extentity *NewEntity(); void RegisterStdHandler(); void DeleteEntity(extentity *e); void Destroy(); HandlerFactory& Handler(); ObjectGenerator& Generator(); template void Init() { Generator().Init(); RegisterStdHandler(); } } #endif // SB_EXTENTITY_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/sb/extentityhandler.cpp0000664000175000017500000002072611442705014023151 0ustar showardshoward#include "extentityhandler.h" #include "extentity.h" EntityHandler::EntityHandler() : typestring(newstring("none?")), model(newstring("")), radius(false), dir(false), numattr(0), dropheight(0), cap(CAP_NONE) {} EntityHandler::~EntityHandler() { delete[] typestring; delete[] model; } const char* EntityHandler::getname() { return typestring; } const char* EntityHandler::getmodel() { return model; } int* EntityHandler::getmodelattr(extentity &e) { return NULL; } void EntityHandler::fix(extentity &e) {} bool EntityHandler::hasradius() { return radius; } bool EntityHandler::hasdir(extentity &e) { return dir; } bool EntityHandler::hascap(EntityCap flag) { return cap&flag; } bool EntityHandler::info(extentity &e, char *buf) { return false; } const char* EntityHandler::info(entity &e) { return typestring; } const int EntityHandler::numattrs() { return numattr; } void EntityHandler::renderhelper(extentity &e, bool &color) {} void EntityHandler::renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp) {} float EntityHandler::getdropheight(entity &e) { return dropheight; } bool EntityHandler::checkmodelusage(extentity &e, int i) { return false; } void EntityHandler::writeent(entity &e, char *buf) {} // write any additional data to disk (except for ET_ ents) void EntityHandler::readent(entity &e, char *buf) {} // read from disk, and init EntityHandlerLight::EntityHandlerLight() { delete[] typestring; typestring = newstring("light"); radius = true; } EntityHandlerMapmodel::EntityHandlerMapmodel() { delete[] typestring; typestring = newstring("mapmodel"); dir = true; } void EntityHandlerMapmodel::renderhelper(extentity &e, bool &color) { vec direction; vecfromyawpitch(e.attr[0], 0, 1, 0, direction); renderentarrow(e, direction, 4); } EntityHandlerPlayerstart::EntityHandlerPlayerstart() { delete[] typestring; typestring = newstring("playerstart"); dir = true; } EntityHandlerMapsound::EntityHandlerMapsound() { delete[] typestring; typestring = newstring("mapsound"); radius = true; } EntityHandlerSpotlight::EntityHandlerSpotlight() { delete[] typestring; typestring = newstring("spotlight"); dir = true; } EntityHandlerEnvmap::EntityHandlerEnvmap() { delete[] typestring; typestring = newstring("envmap"); radius = true; } EntityHandlerParticles::EntityHandlerParticles() { delete[] typestring; typestring = newstring("particles"); } EntityHandlerTeleport::EntityHandlerTeleport() { numattr = 3; delete[] typestring; typestring = newstring("teleport"); dir = true; } void EntityHandlerTeleport::renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp) { pos.z += 3.0; formatstring(tmp)("Teledest Tag: %i\nModel: %s (%i)\nTag: %i", e.attr[0], mapmodelname(e.attr[1]), e.attr[1] ); } int *EntityHandlerTeleport::getmodelattr(extentity &e) { return &e.attr[1]; } bool EntityHandlerTeleport::checkmodelusage(extentity &e, int i) { if(e.attr[1] == 0) return false; return true; } ///TODO: query caps not type void EntityHandlerTeleport::renderhelper(extentity &e, bool &color) { vector &ents = entities::getents(); loopv(ents) if(ents[i]->type == TELEDEST && e.attr[0]==ents[i]->attr[1]) { renderentarrow(e, vec(ents[i]->o).sub(e.o).normalize(), e.o.dist(ents[i]->o)); break; } } EntityHandlerTeledest::EntityHandlerTeledest() { numattr = 2; cap = CAP_TELEDEST; delete[] typestring; typestring = newstring("teledest"); dir = true; } ///TODO: check namespace player1 void EntityHandlerTeledest::fix(extentity &e) { e.attr.pop(); e.attr.insert(0, game::iterdynents(0)->yaw); } void EntityHandlerTeledest::renderhelper(extentity &e, bool &color) { vec direction; vecfromyawpitch(e.attr[0], 0, 1, 0, direction); renderentarrow(e, direction, 4); } void EntityHandlerTeledest::renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp) { pos.z += 3; formatstring(tmp)("Yaw: %i\nTeleport Tag: %i\n", e.attr[0], e.attr[1] ); } EntityHandlerMonster::EntityHandlerMonster() { delete[] typestring; typestring = newstring("monster"); } EntityHandlerJumppad::EntityHandlerJumppad() { numattr = 3; cap = CAP_JUPPAD; delete[] typestring; typestring = newstring("jumppad"); dir = true; } void EntityHandlerJumppad::renderhelper(extentity &e, bool &color) { renderentarrow(e, vec((int)(char)e.attr[2]*10.0f, (int)(char)e.attr[1]*10.0f, e.attr[0]*12.5f).normalize(), 4); } void EntityHandlerJumppad::renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp) { pos.z += 4.5; formatstring(tmp)("Z: %i\nY: %i\nX: %i", e.attr[0], e.attr[1], e.attr[2] ); } EntityHandlerBox::EntityHandlerBox() { numattr = 4; delete[] typestring; typestring = newstring("box"); dir = true; } void EntityHandlerBox::fix(extentity& e) { e.attr.pop(); e.attr.insert(0, game::iterdynents(0)->yaw); } void EntityHandlerBox::renderhelper(extentity &e, bool &color) { vec direction; vecfromyawpitch(e.attr[0], 0, 1, 0, direction); renderentarrow(e, direction, 4); } void EntityHandlerBox::renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp) { pos.z += 6.0; formatstring(tmp)("Yaw: %i\nModel: %s (%i)\nWeight: %i\nHealth: %i", e.attr[0], mapmodelname(e.attr[1]), e.attr[1], e.attr[2], e.attr[3] ); } int *EntityHandlerBox::getmodelattr(extentity &e) { return &e.attr[1]; } bool EntityHandlerBox::checkmodelusage(extentity &e, int i) { return (e.attr[1] == i); } EntityHandlerBarrel::EntityHandlerBarrel() { delete[] typestring; typestring = newstring("barrel"); } EntityHandlerPlatform::EntityHandlerPlatform() { numattr = 4; delete[] typestring; typestring = newstring("platform"); dir = true; } void EntityHandlerPlatform::fix(extentity& e) { e.attr.pop(); e.attr.insert(0, game::iterdynents(0)->yaw); } void EntityHandlerPlatform::renderhelper(extentity &e, bool &color) { vec direction; vecfromyawpitch(e.attr[0], 0, 1, 0, direction); renderentarrow(e, direction, 4); } void EntityHandlerPlatform::renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp) { pos.z += 6.0; formatstring(tmp)("Yaw: %i\nModel: %s (%i)\nTag: %i\nSpeed: %i", e.attr[0], mapmodelname(e.attr[1]), e.attr[1], e.attr[2], e.attr[3] ); } int *EntityHandlerPlatform::getmodelattr(extentity &e) { return &e.attr[1]; } bool EntityHandlerPlatform::checkmodelusage(extentity &e, int i) { return (e.attr[1] == i); } EntityHandlerElevator::EntityHandlerElevator() { delete[] typestring; typestring = newstring("elevator"); } EntityHandlerWaypoint::EntityHandlerWaypoint() { numattr = 3; delete[] typestring; typestring = newstring("waypoint"); radius = true; dir = true; } void EntityHandlerWaypoint::fix(extentity& e) { e.attr[0] = (int)game::iterdynents(0)->yaw; if(!e.attr[1]) e.attr[1] = 25.0f; } void EntityHandlerWaypoint::renderhelper(extentity &e, bool &color) { renderentsphere(e, e.attr[1]); vec direction; vecfromyawpitch(e.attr[0], 0, 1, 0, direction); renderentarrow(e, direction, e.attr[1]); } void EntityHandlerWaypoint::renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp) { pos.z += 4.5f; formatstring(tmp)("Direction %i\nRadius %i", e.attr[0], e.attr[1] ); } EntityHandlerCamera::EntityHandlerCamera() { numattr = 3; delete[] typestring; typestring = newstring("camera"); } void EntityHandlerCamera::renderhelper(extentity &e, bool &color) { vec direction; vecfromyawpitch(e.attr[0], e.attr[1], 1, 0, direction); renderentarrow(e, direction, 4); } void EntityHandlerCamera::renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp) { pos.z += 7.5; formatstring(tmp)("Yaw: %i\nPitch: %i\nDistance: %i", e.attr[0], e.attr[1], e.attr[2] ); } EntityHandlerDynlight::EntityHandlerDynlight() { numattr = 5; delete[] typestring; typestring = newstring("dynlight"); radius = true; } void EntityHandlerDynlight::renderhelper(extentity &e, bool &color) { if(color) glColor3f(e.attr[1]/255.0f, e.attr[2]/255.0f, e.attr[3]/255.0f); renderentsphere(e, e.attr[0]); } void EntityHandlerDynlight::renderhelpertext(const extentity &e, int &colour, vec &pos, string &tmp) { pos.z += 9.0; formatstring(tmp)("Radius %i\n\fs\fRRed: %i\n\fJGreen: %i\n\fDBlue: %i\fr\nTag: %i", e.attr[0], e.attr[1], e.attr[2], e.attr[3], e.attr[4] ); } EntityHandlerGeneric::EntityHandlerGeneric() { numattr = 8; delete[] typestring; typestring = newstring("generic"); } void EntityHandlerGeneric::fix(extentity& e) { if(!e.attr[0]) e.attr[0] = 25.0f; } void EntityHandlerGeneric::renderhelper(extentity &e, bool &color) { renderentsphere(e, e.attr[0]); } sandboxgamemaker-2.7.1+dfsg/src/sb/exp_local.cpp0000664000175000017500000000237411442705014021523 0ustar showardshoward#include "cube.h" typedef hashtable identtable; extern identtable *idents; class localident; vector identtablestack; vector locals; void pushidentstack(identtable *table) { if(identtablestack.empty()) identtablestack.add(idents); identtablestack.add(table); idents = identtablestack.last(); } void popidentstack() { identtablestack.pop(); idents = identtablestack.last(); } class localident { public: localident(const char* _name) : name(newstring(_name)) { local = new identtable; pushidentstack(local); CCOMMAND(getname, "", (localident *self), result(self->getname())); CCOMMAND(setname, "s", (localident *self, char* s), self->setname(s)); popidentstack(); } identtable *local; const char* getname() { return name; } private: const char* name; float fval; float ival; void setname(const char* _name) { delete[] name; name = newstring(_name); } }; ICOMMAND(addlocal, "s", (char* name), { locals.add(new localident(name)); intret(locals.length() - 1); } ); ICOMMAND(local, "is", (int *i, char *s), { if ( ! locals.inrange(*i) ) return; pushidentstack(locals[*i]->local); const char* ret = executeret(s); popidentstack(); conoutf("TEST %s", ret); } ); sandboxgamemaker-2.7.1+dfsg/src/sb/ientities.cpp0000664000175000017500000000527311442705014021553 0ustar showardshoward#include "cube.h" #include "handlerfactory.h" #include "extentity.h" #include "extentityhandler.h" vector ents; namespace entities { extentity *newentity() { // return Extentities::Get().newentity(); // return new Extentities::Extentity(); return Extentities::NewEntity(); } void deleteentity(extentity *e) { // Extentities::Get().deleteentity(e); // delete (Extentities::Extentity *)e; Extentities::DeleteEntity(e); } void clearents() { // Extentities::Get().clearents(); // loopvrev(ents) { delete (Extentities::Extentity *) ents[i]; } loopvrev(ents) { Extentities::DeleteEntity(ents[i]); } ents.shrink(0); } vector &getents() { // return Extentities::Get().getents(); return ents; } ///TODO: editent depends on network code, we have to move this somewhere else :( //void editent(int i, bool local) //{ // //} const char *entnameinfo(entity &e) { // return Extentities::Handler()[e.type]->info(e); return Extentities::Handler()[e.type]->info(e); } const char *entname(int i) { return Extentities::Handler()[i]->getname(); } const int numattrs(int type) { return Extentities::Handler()[type]->numattrs(); } //we dont save additional entity data into the map, //all information will be stored in cfg files int extraentinfosize() { return 0; } void writeent(entity &e, char *buf) {} void readent(entity &e, char *buf) {} float dropheight(entity &e) { return Extentities::Handler()[e.type]->getdropheight(e); } void fixentity(extentity &e) { Extentities::Handler()[e.type]->fix(e); } void entradius(extentity &e, bool &color) { return Extentities::Handler()[e.type]->renderhelper(e, color); } ///TODO: no use for this at the moment, move it into the handlers later bool mayattach(extentity &e) { return false; } bool attachent(extentity &e, extentity &a) { return false; } bool printent(extentity &e, char *buf) { return Extentities::Handler()[e.type]->info(e, buf); } bool dirent(extentity &e) { return Extentities::Handler()[e.type]->hasdir(e); } bool radiusent(extentity &e) { return Extentities::Handler()[e.type]->hasradius(); } void renderhelpertext(extentity &e, int &colour, vec &pos, string &tmp) { return Extentities::Handler()[e.type]->renderhelpertext(e, colour, pos, tmp); } const char *entmodel(const entity &e) { return Extentities::Handler()[e.type]->getmodel(); } ///TODO: implement map model animation void animatemapmodel(const extentity &e, int &anim, int &basetime) {} int *getmodelattr(extentity &e) { return Extentities::Handler()[e.type]->getmodelattr(e); } bool checkmodelusage(extentity &e, int i) { return Extentities::Handler()[e.type]->checkmodelusage(e, i); } } sandboxgamemaker-2.7.1+dfsg/src/sb/qcommand.cpp0000664000175000017500000001353211421064656021361 0ustar showardshoward#include "qcommand.h" hashtable QueuedCommandMgr::queues; Instance* QueuedCommandMgr::current = NULL; QueuedState::QueuedState(const char* _body) : body(newstring(_body)) {} QueuedState::~QueuedState() { delete[] body; } QueuedCommand::QueuedCommand(const char *_id, const char *_body) : id(newstring(_id)) { states.add(new QueuedState(_body)); } void QueuedCommand::addstate(const char* _body) { states.add(new QueuedState(_body)); } const char* QueuedCommand::getbody(int i) { return states.inrange(i) ? states[i]->body : NULL; } QueuedCommand::~QueuedCommand() { delete[] id; } Child::Child() {} Child::~Child() { pending.deletecontents(); } void Child::pushback(Action* a) { if(a) { pending.add(a); } } void Child::popfront() { if(!pending.empty()) delete pending.remove(0); } Action* Child::front() { if(!pending.empty()) return pending[0]; else return NULL; } bool Child::update() { if(pending.empty()) { return true; } if(front()->update()) { popfront(); } return false; } ChildAtOnce::ChildAtOnce() {} ChildAtOnce::~ChildAtOnce() {} bool ChildAtOnce::update() { if(pending.empty()) { return true; } loopv(pending) { if(pending[i]->update()) { delete pending.remove(i); } } return false; } Instance::Instance(QueuedCommand& _queued) : queued(_queued), qcstate(0), state(INSTANCE_STATE_NONE) { registersignal("statechanged"); registersignal("finished"); } void Instance::init() { pushchild(new Child(), queued.getbody(qcstate) ); state = INSTANCE_STATE_RUNNING; } void Instance::pushchild(Child* child, const char* body) { if(child) { QueuedCommandMgr::current = this; stack.add(child); execute(body); QueuedCommandMgr::current = NULL; } } void Instance::process() { if ( stack.empty() ) { return; } changestate(); if( stack.last()->update() ) { delete stack.pop(); if( stack.empty () && state == INSTANCE_STATE_RUNNING) finished(); } } void Instance::reqchangestate(int i) { if(queued.getbody(i)) { qcstate = i; } } void Instance::pushaction(Action* action) { stack.last()->pushback(action); } void Instance::sighandler(const char* sig, const char* body) { if(!body || !sig) return; char* key = newstring(sig); Handler** hh = signals.access(key); if(hh) { signals[key]->sethandler(body); } } void Instance::registersignal(const char* id) { char* key = newstring(id); Handler** hh = signals.access(key); if(!hh) { conoutf("Instance::registersignal %p %s", this, id); signals.access(newstring(id), new Handler); } else { conoutf("Instance::registersignal: signal %s already registered", key); } } void Instance::changestate() { static int curstate = 0; if ( qcstate != curstate ) { emptystack(); pushchild(new Child, queued.getbody(qcstate)); curstate = qcstate; } } void Instance::finished() { state = INSTANCE_STATE_WAITING; emmitsignal("finished"); } void Instance::emmitsignal(const char* sig) { char* key = newstring(sig); if(signals[key]->gethandler()) { //conoutf("Instance::emmitsignal: %s", signals[key]->gethandlerdata() ); const char* body = signals[key]->gethandler(); defformatstring(s)("format [ %s ] %s", body, signals[key]->gethandlerdata()); const char* tmp = executeret(s); pushchild(new Child, tmp ); // pushchild(new Child, signals[key]->gethandler() ); } else { conoutf("Instance::emmitsignal: signal %s not registered", sig); } } void Instance::emptystack() { stack.deletecontents(); } Instance::~Instance() { emptystack(); } void QueuedCommandMgr::newqueue(const char* id, const char* a) { char* key = newstring(id); if(!queues.access(key)) { queues.access(key, new QueuedCommand(key,a)); } else { conoutf("[DEBUG] QueuedCommand already exists - overwriting not implemented"); } } QueuedCommand* QueuedCommandMgr::findqueued(const char* s) { char* key = newstring(s); if(QueuedCommand** cc = queues.access(key)) { return *cc; } return NULL; } Instance* QueuedCommandMgr::getcurrent() { return current ? current : NULL; } Handler::Handler() : body(NULL) {} Handler::~Handler() { delete[] body; } void Handler::sethandler(const char* s) { body = newstring(s); } const char* Handler::gethandler() { return body; } const char* Handler::gethandlerdata() { return "Handler::gethandlerdata"; } Action::Action(const char *s = NULL) : body(s && *s ? newstring(s): NULL), instance(*QueuedCommandMgr::getcurrent()), isinit(false) { instance.pushaction(this); } Action::~Action() { if(body) { delete[] body; } } bool Action::checktype() { return true; } void Action::init() { isinit = true; } bool Action::update() { if(!checktype()) return true; if(!isinit) init(); if(process()) { if (body) { instance.pushchild(new Child, body); } return true; } return false; } ICOMMAND(cq_new, "ss", (const char *id, char* body), QueuedCommandMgr::newqueue(id, body) ); ICOMMAND(cq_state, "ss", (const char *id, char* body), { QueuedCommand* c = QueuedCommandMgr::findqueued(id); if(c) { c->addstate(body); } } ); ICOMMAND(cq_self, "", (), { Instance* instance = QueuedCommandMgr::getcurrent(); defformatstring(s)("%p", instance); result(s); } ); ICOMMAND(cq_data, "", (), { Instance* instance = QueuedCommandMgr::getcurrent(); defformatstring(s)("%p", instance); result(s); } ); sandboxgamemaker-2.7.1+dfsg/src/sb/qcommand.h0000664000175000017500000000751211421064656021027 0ustar showardshoward#ifndef QCOMMAND_H_INCLUDED #define QCOMMAND_H_INCLUDED #include "cube.h" ///TODO: ///*remove Action from pending if checktype fails in constructor of Action class Instance; //Interface to action classes class Action { public: //constructor, one or more actions are contructed by an child object at the same time //and executed later, if you need a timer initialze it with init Action(const char *s); virtual ~Action(); //check if the action matches the instance type virtual bool checktype(); //init stuff here, called with first update virtual void init(); //wraps process and calls a new child, when finished //return true if done virtual bool update(); protected: //body of an child action, executed inside update, if process //returns true const char* body; //reference to the calling instance Instance& instance; //all the main stuff happpens here, return true if finished virtual bool process() = 0; ///TODO: need to call init, move call into Child::update bool isinit; }; //states can be changed by receiving signals or by scripts //instances can run class QueuedState { friend class QueuedCommand; public: //_body: script of the QueuedCommand QueuedState(const char* _body); ~QueuedState(); private: const char* body; }; class QueuedCommand { public: //id: id provided by hashtable in QueuedCommandMgr //body: body of the script (forwared to state 0) QueuedCommand(const char *_id, const char *_body); ~QueuedCommand(); //adds a new state (script) void addstate(const char* body); //returns the script of the current state const char* getbody(int i); private: //QueuedCommand id is untestet, managed by hashtable in QueuedCommandMgr const char* id; //States holding the script vector states; }; class Child { friend class Instance; public: Child(); ~Child(); protected: vector pending; void pushback(Action* a); void popfront(); Action* front(); virtual bool update(); }; class ChildAtOnce : public Child { public: ChildAtOnce(); ~ChildAtOnce(); bool update(); }; class Handler { public: Handler(); ~Handler(); void sethandler(const char* s); const char* gethandler(); const char* gethandlerdata(); private: char* body; }; enum { INSTANCE_STATE_NONE = 0, INSTANCE_STATE_WAITING, INSTANCE_STATE_RUNNING }; //base class of all kind of instances, used for character controls, entity controls ... class Instance { public: QueuedCommand& queued; Instance(QueuedCommand& _queued); virtual ~Instance(); void init(); void process(); void pushaction(Action* action); void pushchild(Child* child, const char* body); void reqchangestate(int i); //emmits a signal void emmitsignal(const char* name); //register a callback for the signal void sighandler(const char* sig, const char* action); protected: hashtable signals; vector stack; vector handler; int qcstate; int state; //registers a new signal name (use in constructor of derived instance) void registersignal(const char* id); //checks if the state was changed, calls the new state void changestate(); //queue is empty - finished void finished(); //cleanup and delete all stack elements void emptystack(); }; class QueuedCommandMgr { friend void Instance::pushchild(Child* child, const char* body); public: static void newqueue(const char* s, const char* a); static QueuedCommand* findqueued(const char* s); static Instance* getcurrent(); private: QueuedCommandMgr() {}; ~QueuedCommandMgr(); static hashtable queues; static Instance* current; }; #endif // QCOMMAND_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/sb/qcscript.cpp0000664000175000017500000000702211421064656021407 0ustar showardshoward#include "qcscript.h" ActionDbg::ActionDbg(const char *e) : Action(NULL), str(newstring(e)) {} ActionDbg::~ActionDbg() { delete[] str; } bool ActionDbg::checktype() { return true; } bool ActionDbg::process() { conoutf("From Instance(%p): %s", &instance, str); return true; } ICOMMAND(cq_dbg, "s", (const char* e), new ActionDbg(e); ); ActionPack::ActionPack(const char* c) : Action(c) {} ActionPack::~ActionPack() {} bool ActionPack::process() { return true; } ICOMMAND(cq_pack, "s", (const char* s), new ActionPack(s); ); ActionDelay::ActionDelay(float sec, const char *c) : Action(c), millis(int(sec)*1000), start(0) {} ActionDelay::~ActionDelay() {} void ActionDelay::init() { start = lastmillis; isinit = true; } bool ActionDelay::process() { if(lastmillis-start < millis) { return false; } return true; } ICOMMAND(cq_delay, "fs", (float *sec, const char* s), new ActionDelay(*sec, s); ); ActionWatch::ActionWatch(const char* _alias, int _val, const char* c ) : Action(c), val(_val), alias(newstring(_alias)) { if(!identexists(alias)) { delete[] alias; alias = NULL; conoutf("[DEBUG] ActionWatch::ActionWatch - alias %s not found", _alias); } } ActionWatch::~ActionWatch() { delete[] alias; } bool ActionWatch::process() { if(!alias) return true; ident *i = getident(alias); return ( i->type == ID_ALIAS && val == atoi(getalias(alias)) ) ? true : false; } ICOMMAND(cq_watch, "sis", (const char* s, int* i, const char* c), new ActionWatch(s, *i, c); ); ActionSigHandler::ActionSigHandler(const char* _signal, const char* c ) : Action(c), signal(newstring(_signal)){} ActionSigHandler::~ActionSigHandler() { delete[] signal; } bool ActionSigHandler::update() { if(!checktype()) return true; if(!isinit) init(); if (process() && body) { instance.sighandler(signal, body); } return true; } bool ActionSigHandler::process() { return true; } ICOMMAND(cq_sighandler, "ss", (const char* s, const char* c), new ActionSigHandler(s, c); ); ActionChangeState::ActionChangeState(int i) : Action(NULL), state(i) {} ActionChangeState::~ActionChangeState() {} bool ActionChangeState::process() { instance.reqchangestate(state); return true; } ICOMMAND(cq_changestate, "i", (int *i), new ActionChangeState(*i); ); ActionTest::ActionTest(const char* _alias, int _val, const char* c ) : Action(c), val(_val), alias(newstring(_alias)) { if(!identexists(alias)) { delete[] alias; alias = NULL; conoutf("[DEBUG] ActionTest::ActionTest - alias %s not found", _alias); } } ActionTest::~ActionTest() { delete[] alias; } bool ActionTest::update() { if(!checktype()) return true; if(!isinit) init(); if(process() && body) { instance.pushchild(new Child, body); } return true; } bool ActionTest::process() { if(!alias) return true; ident *i = getident(alias); return ( i->type == ID_ALIAS && val == atoi(getalias(alias)) ) ? true : false; } ICOMMAND(cq_test, "sis", (const char* s, int* i, const char* c), new ActionTest(s, *i, c); ); ActionAtOnce::ActionAtOnce(const char* body) : Action(body) {} ActionAtOnce::~ActionAtOnce() {} bool ActionAtOnce::update() { if(!checktype()) return true; if(!isinit) init(); if (body) { instance.pushchild(new ChildAtOnce, body); } return true; } bool ActionAtOnce::process() { return true; } ICOMMAND(cq_atonce, "s", (const char* body), new ActionAtOnce(body); ); sandboxgamemaker-2.7.1+dfsg/src/shared/0000775000175000017500000000000011660234756017721 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/shared/geom.h0000664000175000017500000013076611642642476021040 0ustar showardshowardstruct vec4; struct vec2; struct vec { union { struct { float x, y, z; }; struct { float r, g, b; }; float v[3]; }; vec() {} explicit vec(int a) : x(a), y(a), z(a) {} explicit vec(float a) : x(a), y(a), z(a) {} vec(float a, float b, float c) : x(a), y(b), z(c) {} explicit vec(int v[3]) : x(v[0]), y(v[1]), z(v[2]) {} explicit vec(float *v) : x(v[0]), y(v[1]), z(v[2]) {} explicit vec(const vec4 &v); explicit vec(const vec2 &v, float z = 0); vec(float yaw, float pitch) : x(-sinf(yaw)*cosf(pitch)), y(cosf(yaw)*cosf(pitch)), z(sinf(pitch)) {} float &operator[](int i) { return v[i]; } float operator[](int i) const { return v[i]; } vec &set(int i, float f) { v[i] = f; return *this; } bool operator==(const vec &o) const { return x == o.x && y == o.y && z == o.z; } bool operator!=(const vec &o) const { return x != o.x || y != o.y || z != o.z; } bool iszero() const { return x==0 && y==0 && z==0; } float squaredlen() const { return x*x + y*y + z*z; } float dot2(const vec &o) const { return x*o.x + y*o.y; } float dot(const vec &o) const { return x*o.x + y*o.y + z*o.z; } vec &mul(const vec &o) { x *= o.x; y *= o.y; z *= o.z; return *this; } vec &mul(float f) { x *= f; y *= f; z *= f; return *this; } vec &div(const vec &o) { x /= o.x; y /= o.y; z /= o.z; return *this; } vec &div(float f) { x /= f; y /= f; z /= f; return *this; } vec &add(const vec &o) { x += o.x; y += o.y; z += o.z; return *this; } vec &add(float f) { x += f; y += f; z += f; return *this; } vec &sub(const vec &o) { x -= o.x; y -= o.y; z -= o.z; return *this; } vec &sub(float f) { x -= f; y -= f; z -= f; return *this; } vec &neg2() { x = -x; y = -y; return *this; } vec &neg() { x = -x; y = -y; z = -z; return *this; } vec &min(const vec &o) { x = ::min(x, o.x); y = ::min(y, o.y); z = ::min(z, o.z); return *this; } vec &max(const vec &o) { x = ::max(x, o.x); y = ::max(y, o.y); z = ::max(z, o.z); return *this; } vec &min(float f) { x = ::min(x, f); y = ::min(y, f); z = ::min(z, f); return *this; } vec &max(float f) { x = ::max(x, f); y = ::max(y, f); z = ::max(z, f); return *this; } vec &clamp(float f, float h) { x = ::clamp(x, f, h); y = ::clamp(y, f, h); z = ::clamp(z, f, h); return *this; } float magnitude2() const { return sqrtf(dot2(*this)); } float magnitude() const { return sqrtf(squaredlen()); } vec &normalize() { div(magnitude()); return *this; } bool isnormalized() const { float m = squaredlen(); return (m>0.99f && m<1.01f); } float squaredist(const vec &e) const { return vec(*this).sub(e).squaredlen(); } float dist(const vec &e) const { vec t; return dist(e, t); } float dist(const vec &e, vec &t) const { t = *this; t.sub(e); return t.magnitude(); } bool reject(const vec &o, float r) { return x>o.x+r || xo.y+r || y vec &cross(const A &a, const B &b) { x = a.y*b.z-a.z*b.y; y = a.z*b.x-a.x*b.z; z = a.x*b.y-a.y*b.x; return *this; } vec &cross(const vec &o, const vec &a, const vec &b) { return cross(vec(a).sub(o), vec(b).sub(o)); } float scalartriple(const vec &a, const vec &b) const { return x*(a.y*b.z-a.z*b.y) + y*(a.z*b.x-a.x*b.z) + z*(a.x*b.y-a.y*b.x); } vec &reflectz(float rz) { z = 2*rz - z; return *this; } vec &reflect(const vec &n) { float k = 2*dot(n); x -= k*n.x; y -= k*n.y; z -= k*n.z; return *this; } vec &project(const vec &n) { float k = dot(n); x -= k*n.x; y -= k*n.y; z -= k*n.z; return *this; } vec &projectxydir(const vec &n) { if(n.z) z = -(x*n.x/n.z + y*n.y/n.z); return *this; } vec &projectxy(const vec &n) { float m = squaredlen(), k = dot(n); projectxydir(n); rescale(sqrtf(::max(m - k*k, 0.0f))); return *this; } vec &projectxy(const vec &n, float threshold) { float m = squaredlen(), k = ::min(dot(n), threshold); projectxydir(n); rescale(sqrtf(::max(m - k*k, 0.0f))); return *this; } vec &lerp(const vec &b, float t) { x += (b.x-x)*t; y += (b.y-y)*t; z += (b.z-z)*t; return *this; } vec &lerp(const vec &a, const vec &b, float t) { x = a.x + (b.x-a.x)*t; y = a.y + (b.y-a.y)*t; z = a.z + (b.z-a.z)*t; return *this; } vec &rescale(float k) { float mag = magnitude(); if(mag > 1e-6f) mul(k / mag); return *this; } vec &rotate_around_z(float c, float s) { float rx = x, ry = y; x = c*rx-s*ry; y = c*ry+s*rx; return *this; } vec &rotate_around_x(float c, float s) { float ry = y, rz = z; y = c*ry-s*rz; z = c*rz+s*ry; return *this; } vec &rotate_around_y(float c, float s) { float rx = x, rz = z; x = c*rx-s*rz; z = c*rz+s*rx; return *this; } vec &rotate_around_z(float angle) { return rotate_around_z(cosf(angle), sinf(angle)); } vec &rotate_around_x(float angle) { return rotate_around_x(cosf(angle), sinf(angle)); } vec &rotate_around_y(float angle) { return rotate_around_y(cosf(angle), sinf(angle)); } vec &rotate(float angle, const vec &d) { float c = cosf(angle), s = sinf(angle); return rotate(c, s, d); } vec &rotate(float c, float s, const vec &d) { *this = vec(x*(d.x*d.x*(1-c)+c) + y*(d.x*d.y*(1-c)-d.z*s) + z*(d.x*d.z*(1-c)+d.y*s), x*(d.y*d.x*(1-c)+d.z*s) + y*(d.y*d.y*(1-c)+c) + z*(d.y*d.z*(1-c)-d.x*s), x*(d.x*d.z*(1-c)-d.y*s) + y*(d.y*d.z*(1-c)+d.x*s) + z*(d.z*d.z*(1-c)+c)); return *this; } void orthogonal(const vec &d) { int i = fabs(d.x) > fabs(d.y) ? (fabs(d.x) > fabs(d.z) ? 0 : 2) : (fabs(d.y) > fabs(d.z) ? 1 : 2); v[i] = d[(i+1)%3]; v[(i+1)%3] = -d[i]; v[(i+2)%3] = 0; } void orthonormalize(vec &s, vec &t) const { s.sub(vec(*this).mul(dot(s))); t.sub(vec(*this).mul(dot(t))) .sub(vec(s).mul(s.dot(t))); } template float dist_to_bb(const T &min, const T &max) const { float sqrdist = 0; loopi(3) { if (v[i] < min[i]) { float delta = v[i]-min[i]; sqrdist += delta*delta; } else if(v[i] > max[i]) { float delta = max[i]-v[i]; sqrdist += delta*delta; } } return sqrtf(sqrdist); } template float dist_to_bb(const T &o, S size) const { return dist_to_bb(o, T(o).add(size)); } }; static inline bool htcmp(const vec &x, const vec &y) { return x == y; } static inline uint hthash(const vec &k) { union { uint i; float f; } x, y, z; x.f = k.x; y.f = k.y; z.f = k.z; uint v = x.i^y.i^z.i; return v + (v>>12); } struct vec4 { union { struct { float x, y, z, w; }; float v[4]; }; vec4() {} explicit vec4(const vec &p, float w = 0) : x(p.x), y(p.y), z(p.z), w(w) {} vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {} float &operator[](int i) { return v[i]; } float operator[](int i) const { return v[i]; } float dot3(const vec4 &o) const { return x*o.x + y*o.y + z*o.z; } float dot3(const vec &o) const { return x*o.x + y*o.y + z*o.z; } float dot(const vec4 &o) const { return dot3(o) + w*o.w; } float dot(const vec &o) const { return x*o.x + y*o.y + z*o.z + w; } float squaredlen() const { return dot(*this); } float magnitude() const { return sqrtf(squaredlen()); } float magnitude3() const { return sqrtf(dot3(*this)); } vec4 &normalize() { mul(1/magnitude()); return *this; } vec4 &lerp(const vec4 &b, float t) { x += (b.x-x)*t; y += (b.y-y)*t; z += (b.z-z)*t; w += (b.w-w)*t; return *this; } vec4 &lerp(const vec4 &a, const vec4 &b, float t) { x = a.x+(b.x-a.x)*t; y = a.y+(b.y-a.y)*t; z = a.z+(b.z-a.z)*t; w = a.w+(b.w-a.w)*t; return *this; } vec4 &mul3(float f) { x *= f; y *= f; z *= f; return *this; } vec4 &mul(float f) { mul3(f); w *= f; return *this; } vec4 &mul(const vec4 &o) { x *= o.x; y *= o.y; z *= o.z; w *= o.w; return *this; } vec4 &div3(float f) { x /= f; y /= f; z /= f; return *this; } vec4 &div(float f) { div3(f); w /= f; return *this; } vec4 &div(const vec4 &o) { x /= o.x; y /= o.y; z /= o.z; w /= o.w; return *this; } vec4 &add(const vec4 &o) { x += o.x; y += o.y; z += o.z; w += o.w; return *this; } vec4 &addw(float f) { w += f; return *this; } vec4 &sub(const vec4 &o) { x -= o.x; y -= o.y; z -= o.z; w -= o.w; return *this; } vec4 &subw(float f) { w -= f; return *this; } vec4 &neg3() { x = -x; y = -y; z = -z; return *this; } vec4 &neg() { neg3(); w = -w; return *this; } void setxyz(const vec &v) { x = v.x; y = v.y; z = v.z; } }; inline vec::vec(const vec4 &v) : x(v.x), y(v.y), z(v.z) {} struct vec2 { union { struct { float x, y; }; float v[2]; }; vec2() {} vec2(float x, float y) : x(x), y(y) {} explicit vec2(const vec &v) : x(v.x), y(v.y) {} explicit vec2(const vec4 &v) : x(v.x), y(v.y) {} float &operator[](int i) { return v[i]; } float operator[](int i) const { return v[i]; } bool operator==(const vec2 &o) const { return x == o.x && y == o.y; } bool operator!=(const vec2 &o) const { return x != o.x || y != o.y; } bool iszero() const { return x==0 && y==0; } float dot(const vec2 &o) const { return x*o.x + y*o.y; } float squaredlen() const { return dot(*this); } float magnitude() const { return sqrtf(squaredlen()); } vec2 &normalize() { mul(1/magnitude()); return *this; } float cross(const vec2 &o) const { return x*o.y - y*o.x; } vec2 &mul(float f) { x *= f; y *= f; return *this; } vec2 &mul(const vec2 &o) { x *= o.x; y *= o.y; return *this; } vec2 &div(float f) { x /= f; y /= f; return *this; } vec2 &div(const vec2 &o) { x /= o.x; y /= o.y; return *this; } vec2 &add(float f) { x += f; y += f; return *this; } vec2 &add(const vec2 &o) { x += o.x; y += o.y; return *this; } vec2 &sub(float f) { x -= f; y -= f; return *this; } vec2 &sub(const vec2 &o) { x -= o.x; y -= o.y; return *this; } vec2 &neg() { x = -x; y = -y; return *this; } }; inline vec::vec(const vec2 &v, float z) : x(v.x), y(v.y), z(z) {} static inline bool htcmp(const vec2 &x, const vec2 &y) { return x == y; } static inline uint hthash(const vec2 &k) { union { uint i; float f; } x, y; x.f = k.x; y.f = k.y; uint v = x.i^y.i; return v + (v>>12); } struct matrix3x3; struct matrix3x4; struct quat : vec4 { quat() {} quat(float x, float y, float z, float w) : vec4(x, y, z, w) {} quat(const vec &axis, float angle) { w = cosf(angle/2); float s = sinf(angle/2); x = s*axis.x; y = s*axis.y; z = s*axis.z; } explicit quat(const vec &v) { x = v.x; y = v.y; z = v.z; restorew(); } explicit quat(const matrix3x3 &m) { convertmatrix(m); } explicit quat(const matrix3x4 &m) { convertmatrix(m); } void restorew() { w = 1.0f-x*x-y*y-z*z; w = w<0 ? 0 : -sqrtf(w); } quat &add(const vec4 &o) { vec4::add(o); return *this; } quat &sub(const vec4 &o) { vec4::sub(o); return *this; } quat &mul(float k) { vec4::mul(k); return *this; } quat &mul(const quat &p, const quat &o) { x = p.w*o.x + p.x*o.w + p.y*o.z - p.z*o.y; y = p.w*o.y - p.x*o.z + p.y*o.w + p.z*o.x; z = p.w*o.z + p.x*o.y - p.y*o.x + p.z*o.w; w = p.w*o.w - p.x*o.x - p.y*o.y - p.z*o.z; return *this; } quat &mul(const quat &o) { return mul(quat(*this), o); } quat &invert() { neg3(); return *this; } void calcangleaxis(float &angle, vec &axis) { float rr = dot3(*this); if(rr>0) { angle = 2*acosf(w); axis = vec(x, y, z).mul(1/rr); } else { angle = 0; axis = vec(0, 0, 1); } } vec rotate(const vec &v) const { return vec().cross(*this, vec().cross(*this, v).add(vec(v).mul(w))).mul(2).add(v); } vec invertedrotate(const vec &v) const { return vec().cross(*this, vec().cross(*this, v).sub(vec(v).mul(w))).mul(2).add(v); } template void convertmatrix(const M &m) { float trace = m.a.x + m.b.y + m.c.z; if(trace>0) { float r = sqrtf(1 + trace), inv = 0.5f/r; w = 0.5f*r; x = (m.c.y - m.b.z)*inv; y = (m.a.z - m.c.x)*inv; z = (m.b.x - m.a.y)*inv; } else if(m.a.x > m.b.y && m.a.x > m.c.z) { float r = sqrtf(1 + m.a.x - m.b.y - m.c.z), inv = 0.5f/r; x = 0.5f*r; y = (m.b.x + m.a.y)*inv; z = (m.a.z + m.c.x)*inv; w = (m.c.y - m.b.z)*inv; } else if(m.b.y > m.c.z) { float r = sqrtf(1 + m.b.y - m.a.x - m.c.z), inv = 0.5f/r; x = (m.b.x + m.a.y)*inv; y = 0.5f*r; z = (m.c.y + m.b.z)*inv; w = (m.a.z - m.c.x)*inv; } else { float r = sqrtf(1 + m.c.z - m.a.x - m.b.y), inv = 0.5f/r; x = (m.a.z + m.c.x)*inv; y = (m.c.y + m.b.z)*inv; z = 0.5f*r; w = (m.b.x - m.a.y)*inv; } } }; struct dualquat { quat real, dual; dualquat() {} dualquat(const quat &q, const vec &p) : real(q), dual(0.5f*( p.x*q.w + p.y*q.z - p.z*q.y), 0.5f*(-p.x*q.z + p.y*q.w + p.z*q.x), 0.5f*( p.x*q.y - p.y*q.x + p.z*q.w), -0.5f*( p.x*q.x + p.y*q.y + p.z*q.z)) { } explicit dualquat(const quat &q) : real(q), dual(0, 0, 0, 0) {} explicit dualquat(const matrix3x4 &m); dualquat &mul(float k) { real.mul(k); dual.mul(k); return *this; } dualquat &add(const dualquat &d) { real.add(d.real); dual.add(d.dual); return *this; } dualquat &lerp(const dualquat &to, float t) { float k = real.dot(to.real) < 0 ? -t : t; real.mul(1-t).add(vec4(to.real).mul(k)); dual.mul(1-t).add(vec4(to.dual).mul(k)); return *this; } dualquat &lerp(const dualquat &from, const dualquat &to, float t) { float k = from.real.dot(to.real) < 0 ? -t : t; (real = from.real).mul(1-t).add(vec4(to.real).mul(k)); (dual = from.dual).mul(1-t).add(vec4(to.dual).mul(k)); return *this; } dualquat &invert() { real.invert(); dual.invert(); dual.sub(quat(real).mul(2*real.dot(dual))); return *this; } void mul(const dualquat &p, const dualquat &o) { real.mul(p.real, o.real); dual.mul(p.real, o.dual).add(quat().mul(p.dual, o.real)); } void mul(const dualquat &o) { mul(dualquat(*this), o); } void mulorient(const quat &q) { real.mul(q, quat(real)); dual.mul(quat(q).invert(), quat(dual)); } void mulorient(const quat &q, const dualquat &base) { quat trans; trans.mul(base.dual, quat(base.real).invert()); dual.mul(quat(q).invert(), quat(real).mul(trans).add(dual)); real.mul(q, quat(real)); dual.add(quat().mul(real, trans.invert())).sub(quat(real).mul(2*base.real.dot(base.dual))); } void normalize() { float invlen = 1/real.magnitude(); real.mul(invlen); dual.mul(invlen); } void translate(const vec &p) { dual.x += 0.5f*( p.x*real.w + p.y*real.z - p.z*real.y); dual.y += 0.5f*(-p.x*real.z + p.y*real.w + p.z*real.x); dual.z += 0.5f*( p.x*real.y - p.y*real.x + p.z*real.w); dual.w += -0.5f*( p.x*real.x + p.y*real.y + p.z*real.z); } void scale(float k) { dual.mul(k); } void fixantipodal(const dualquat &d) { if(real.dot(d.real) < 0) { real.neg(); dual.neg(); } } void accumulate(const dualquat &d, float k) { if(real.dot(d.real) < 0) k = -k; real.add(vec4(d.real).mul(k)); dual.add(vec4(d.dual).mul(k)); } vec transform(const vec &v) const { return vec().cross(real, vec().cross(real, v).add(vec(v).mul(real.w)).add(vec(dual))).add(vec(dual).mul(real.w)).sub(vec(real).mul(dual.w)).mul(2).add(v); } vec transposedtransform(const vec &v) const { return dualquat(*this).invert().transform(v); } vec transformnormal(const vec &v) const { return real.rotate(v); } vec transposedtransformnormal(const vec &v) const { return real.invertedrotate(v); } vec gettranslation() const { return vec().cross(real, dual).add(vec(dual).mul(real.w)).sub(vec(real).mul(dual.w)).mul(2); } }; struct matrix3x3 { vec a, b, c; matrix3x3() {} matrix3x3(const vec &a, const vec &b, const vec &c) : a(a), b(b), c(c) {} explicit matrix3x3(float angle, const vec &axis) { rotate(angle, axis); } explicit matrix3x3(const quat &q) { float x = q.x, y = q.y, z = q.z, w = q.w, tx = 2*x, ty = 2*y, tz = 2*z, txx = tx*x, tyy = ty*y, tzz = tz*z, txy = tx*y, txz = tx*z, tyz = ty*z, twx = w*tx, twy = w*ty, twz = w*tz; a = vec(1 - (tyy + tzz), txy - twz, txz + twy); b = vec(txy + twz, 1 - (txx + tzz), tyz - twx); c = vec(txz - twy, tyz + twx, 1 - (txx + tyy)); } void mul(const matrix3x3 &m, const matrix3x3 &n) { a = vec(n.a).mul(m.a.x).add(vec(n.b).mul(m.a.y)).add(vec(n.c).mul(m.a.z)); b = vec(n.a).mul(m.b.x).add(vec(n.b).mul(m.b.y)).add(vec(n.c).mul(m.b.z)); c = vec(n.a).mul(m.c.x).add(vec(n.b).mul(m.c.y)).add(vec(n.c).mul(m.c.z)); } void mul(const matrix3x3 &n) { mul(*this, n); } void multranspose(const matrix3x3 &m, const matrix3x3 &n) { a = vec(m.a.dot(n.a), m.a.dot(n.b), m.a.dot(n.c)); b = vec(m.b.dot(n.a), m.b.dot(n.b), m.b.dot(n.c)); c = vec(m.c.dot(n.a), m.c.dot(n.b), m.c.dot(n.c)); } void transposemul(const matrix3x3 &m, const matrix3x3 &n) { a = vec(n.a).mul(m.a.x).add(vec(n.b).mul(m.b.x)).add(vec(n.c).mul(m.c.x)); b = vec(n.a).mul(m.a.y).add(vec(n.b).mul(m.b.y)).add(vec(n.c).mul(m.c.y)); c = vec(n.a).mul(m.a.z).add(vec(n.b).mul(m.b.z)).add(vec(n.c).mul(m.c.z)); } void transpose(const matrix3x3 &o) { a = vec(o.a.x, o.b.x, o.c.x); b = vec(o.a.y, o.b.y, o.c.y); c = vec(o.a.z, o.b.z, o.c.z); } void rotate(float angle, const vec &axis) { rotate(cosf(angle), sinf(angle), axis); } void rotate(float ck, float sk, const vec &axis) { a = vec(axis.x*axis.x*(1-ck)+ck, axis.x*axis.y*(1-ck)-axis.z*sk, axis.x*axis.z*(1-ck)+axis.y*sk); b = vec(axis.y*axis.x*(1-ck)+axis.z*sk, axis.y*axis.y*(1-ck)+ck, axis.y*axis.z*(1-ck)-axis.x*sk); c = vec(axis.x*axis.z*(1-ck)-axis.y*sk, axis.y*axis.z*(1-ck)+axis.x*sk, axis.z*axis.z*(1-ck)+ck); } bool calcangleaxis(float &angle, vec &axis, float threshold = 1e-9f) { angle = acosf(clamp(0.5f*(a.x + b.y + c.z - 1), -1.0f, 1.0f)); if(angle <= 0) axis = vec(0, 0, 1); else if(angle < M_PI) { axis = vec(c.y - b.z, a.z - c.x, b.x - a.y); float r = axis.magnitude(); if(r <= threshold) return false; axis.mul(1/r); } else if(a.x >= b.y && a.x >= c.z) { float r = sqrtf(max(1 + a.x - b.y - c.z, 0.0f)); if(r <= threshold) return false; axis.x = 0.5f*r; axis.y = a.y/r; axis.z = a.z/r; } else if(b.y >= c.z) { float r = sqrtf(max(1 + b.y - a.x - c.z, 0.0f)); if(r <= threshold) return false; axis.y = 0.5f*r; axis.x = a.y/r; axis.z = b.z/r; } else { float r = sqrtf(max(1 + b.y - a.x - c.z, 0.0f)); if(r <= threshold) return false; axis.z = 0.5f*r; axis.x = a.z/r; axis.y = b.z/r; } return true; } vec transform(const vec &o) const { return vec(a.dot(o), b.dot(o), c.dot(o)); } vec transposedtransform(const vec &o) const { return vec(a.x*o.x + b.x*o.y + c.x*o.z, a.y*o.x + b.y*o.y + c.y*o.z, a.z*o.x + b.z*o.y + c.z*o.z); } }; struct matrix2x3 { vec a, b; matrix2x3() {} matrix2x3(const vec &a, const vec &b) : a(a), b(b) {} vec2 transform(const vec &o) const { return vec2(a.dot(o), b.dot(o)); } vec transposedtransform(const vec2 &o) const { return vec(a.x*o.x + b.x*o.y, a.y*o.x + b.y*o.y, a.z*o.x + b.z*o.y); } }; struct matrix3x4 { vec4 a, b, c; matrix3x4() {} matrix3x4(const vec4 &x, const vec4 &y, const vec4 &z) : a(x), b(y), c(z) {} matrix3x4(const matrix3x3 &rot, const vec &trans) : a(rot.a, trans.x), b(rot.b, trans.y), c(rot.c, trans.z) {} matrix3x4(const dualquat &d) { vec4 r = vec4(d.real).mul(1/d.real.squaredlen()), rr = vec4(r).mul(d.real); r.mul(2); float xy = r.x*d.real.y, xz = r.x*d.real.z, yz = r.y*d.real.z, wx = r.w*d.real.x, wy = r.w*d.real.y, wz = r.w*d.real.z; a = vec4(rr.w + rr.x - rr.y - rr.z, xy - wz, xz + wy, -(d.dual.w*r.x - d.dual.x*r.w + d.dual.y*r.z - d.dual.z*r.y)); b = vec4(xy + wz, rr.w + rr.y - rr.x - rr.z, yz - wx, -(d.dual.w*r.y - d.dual.x*r.z - d.dual.y*r.w + d.dual.z*r.x)); c = vec4(xz - wy, yz + wx, rr.w + rr.z - rr.x - rr.y, -(d.dual.w*r.z + d.dual.x*r.y - d.dual.y*r.x - d.dual.z*r.w)); } void mul(float k) { a.mul(k); b.mul(k); c.mul(k); } void scale(float k) { a.mul(k); b.mul(k); c.mul(k); } void translate(const vec &p) { a.w += p.x; b.w += p.y; c.w += p.z; } void transformedtranslate(const vec &p, float scale = 1) { a.w += a.dot3(p)*scale; b.w += b.dot3(p)*scale; c.w += c.dot3(p)*scale; } void accumulate(const matrix3x4 &m, float k) { a.add(vec4(m.a).mul(k)); b.add(vec4(m.b).mul(k)); c.add(vec4(m.c).mul(k)); } void normalize() { a.mul3(1/a.magnitude3()); b.mul3(1/b.magnitude3()); c.mul3(1/c.magnitude3()); } void lerp(const matrix3x4 &to, float t) { a.lerp(to.a, t); b.lerp(to.b, t); c.lerp(to.c, t); } void lerp(const matrix3x4 &from, const matrix3x4 &to, float t) { a.lerp(from.a, to.a, t); b.lerp(from.b, to.b, t); c.lerp(from.c, to.c, t); } void identity() { a = vec4(1, 0, 0, 0); b = vec4(0, 1, 0, 0); c = vec4(0, 0, 1, 0); } void mul(const matrix3x4 &m, const matrix3x4 &n) { a = vec4(n.a).mul(m.a.x).add(vec4(n.b).mul(m.a.y)).add(vec4(n.c).mul(m.a.z)).addw(m.a.w); b = vec4(n.a).mul(m.b.x).add(vec4(n.b).mul(m.b.y)).add(vec4(n.c).mul(m.b.z)).addw(m.b.w); c = vec4(n.a).mul(m.c.x).add(vec4(n.b).mul(m.c.y)).add(vec4(n.c).mul(m.c.z)).addw(m.c.w); } void mul(const matrix3x4 &n) { mul(*this, n); } void mul(const matrix3x3 &rot, const vec &trans, const matrix3x4 &o) { a = vec4(o.a).mul(rot.a.x).add(vec4(o.b).mul(rot.a.y)).add(vec4(o.c).mul(rot.a.z)).addw(trans.x); b = vec4(o.a).mul(rot.b.x).add(vec4(o.b).mul(rot.b.y)).add(vec4(o.c).mul(rot.b.z)).addw(trans.y); c = vec4(o.a).mul(rot.c.x).add(vec4(o.b).mul(rot.c.y)).add(vec4(o.c).mul(rot.c.z)).addw(trans.z); } void mulorient(const matrix3x3 &m) { vec ra = vec(a).mul(m.a.x).add(vec(b).mul(m.a.y)).add(vec(c).mul(m.a.z)), rb = vec(a).mul(m.b.x).add(vec(b).mul(m.b.y)).add(vec(c).mul(m.b.z)), rc = vec(a).mul(m.c.x).add(vec(b).mul(m.c.y)).add(vec(c).mul(m.c.z)); a.setxyz(ra); b.setxyz(rb); c.setxyz(rc); } void mulorient(const matrix3x3 &m, const dualquat &base) { vec trans = transformnormal(base.gettranslation()); translate(trans.sub(m.transform(trans))); mulorient(m); } void transpose(const matrix3x4 &o) { a = vec4(o.a.x, o.b.x, o.c.x, -(o.a.x*o.a.w + o.b.x*o.b.w + o.c.x*o.c.w)); b = vec4(o.a.y, o.b.y, o.c.y, -(o.a.y*o.a.w + o.b.y*o.b.w + o.c.y*o.c.w)); c = vec4(o.a.z, o.b.z, o.c.z, -(o.a.z*o.a.w + o.b.z*o.b.w + o.c.z*o.c.w)); } void transposemul(const matrix3x3 &rot, const vec &trans, const matrix3x4 &o) { a = vec4(o.a).mul(rot.a.x).add(vec4(o.b).mul(rot.b.x)).add(vec4(o.c).mul(rot.c.x)).addw(trans.x); b = vec4(o.a).mul(rot.a.y).add(vec4(o.b).mul(rot.b.y)).add(vec4(o.c).mul(rot.c.y)).addw(trans.y); c = vec4(o.a).mul(rot.a.z).add(vec4(o.b).mul(rot.b.z)).add(vec4(o.c).mul(rot.c.z)).addw(trans.z); } void transposemul(const matrix3x4 &m, const matrix3x4 &n) { float tx = m.a.x*m.a.w + m.b.x*m.b.w + m.c.x*m.c.w, ty = m.a.y*m.a.w + m.b.y*m.b.w + m.c.y*m.c.w, tz = m.a.z*m.a.w + m.b.z*m.b.w + m.c.z*m.c.w; a = vec4(n.a).mul(m.a.x).add(vec4(n.b).mul(m.b.x)).add(vec4(n.c).mul(m.c.x)).subw(tx); b = vec4(n.a).mul(m.a.y).add(vec4(n.b).mul(m.b.y)).add(vec4(n.c).mul(m.c.y)).subw(ty); c = vec4(n.a).mul(m.a.z).add(vec4(n.b).mul(m.b.z)).add(vec4(n.c).mul(m.c.z)).subw(tz); } void rotate(float angle, const vec &d) { rotate(cosf(angle), sinf(angle), d); } void rotate(float ck, float sk, const vec &d) { a = vec4(d.x*d.x*(1-ck)+ck, d.x*d.y*(1-ck)-d.z*sk, d.x*d.z*(1-ck)+d.y*sk, 0); b = vec4(d.y*d.x*(1-ck)+d.z*sk, d.y*d.y*(1-ck)+ck, d.y*d.z*(1-ck)-d.x*sk, 0); c = vec4(d.x*d.z*(1-ck)-d.y*sk, d.y*d.z*(1-ck)+d.x*sk, d.z*d.z*(1-ck)+ck, 0); } #define ROTVEC(V, m, n) \ { \ float m = V.m, n = V.n; \ V.m = m*ck + n*sk; \ V.n = n*ck - m*sk; \ } void rotate_around_x(float angle) { float ck = cosf(angle), sk = sinf(angle); ROTVEC(a, y, z); ROTVEC(b, y, z); ROTVEC(c, y, z); } void rotate_around_y(float angle) { float ck = cosf(angle), sk = sinf(angle); ROTVEC(a, z, x); ROTVEC(b, z, x); ROTVEC(c, z, x); } void rotate_around_z(float angle) { float ck = cosf(angle), sk = sinf(angle); ROTVEC(a, x, y); ROTVEC(b, x, y); ROTVEC(c, x, y); } #undef ROTVEC vec transform(const vec &o) const { return vec(a.dot(o), b.dot(o), c.dot(o)); } vec transposedtransform(const vec &o) const { vec p = o; p.x -= a.w; p.y -= b.w; p.z -= c.w; return vec(a.x*p.x + b.x*p.y + c.x*p.z, a.y*p.x + b.y*p.y + c.y*p.z, a.z*p.x + b.z*p.y + c.z*p.z); } vec transformnormal(const vec &o) const { return vec(a.dot3(o), b.dot3(o), c.dot3(o)); } vec transposedtransformnormal(const vec &o) const { return vec(a.x*o.x + b.x*o.y + c.x*o.z, a.y*o.x + b.y*o.y + c.y*o.z, a.z*o.x + b.z*o.y + c.z*o.z); } float getscale() const { return a.magnitude3(); } vec gettranslation() const { return vec(a.w, b.w, c.w); } }; inline dualquat::dualquat(const matrix3x4 &m) : real(m) { dual.x = 0.5f*( m.a.w*real.w + m.b.w*real.z - m.c.w*real.y); dual.y = 0.5f*(-m.a.w*real.z + m.b.w*real.w + m.c.w*real.x); dual.z = 0.5f*( m.a.w*real.y - m.b.w*real.x + m.c.w*real.w); dual.w = -0.5f*( m.a.w*real.x + m.b.w*real.y + m.c.w*real.z); } struct plane : vec { float offset; float dist(const vec &p) const { return dot(p)+offset; } bool operator==(const plane &p) const { return x==p.x && y==p.y && z==p.z && offset==p.offset; } bool operator!=(const plane &p) const { return x!=p.x || y!=p.y || z!=p.z || offset!=p.offset; } plane() {} plane(const vec &c, float off) : vec(c), offset(off) {} plane(const vec4 &p) : vec(p), offset(p.w) {} plane(int d, float off) { x = y = z = 0.0f; v[d] = 1.0f; offset = -off; } plane(float a, float b, float c, float d) : vec(a, b, c), offset(d) {} void toplane(const vec &n, const vec &p) { x = n.x; y = n.y; z = n.z; offset = -dot(p); } bool toplane(const vec &a, const vec &b, const vec &c) { cross(vec(b).sub(a), vec(c).sub(a)); float mag = magnitude(); if(!mag) return false; div(mag); offset = -dot(a); return true; } bool rayintersect(const vec &o, const vec &ray, float &dist) { float cosalpha = dot(ray); if(cosalpha==0) return false; float deltac = offset+dot(o); dist -= deltac/cosalpha; return true; } plane &reflectz(float rz) { offset += 2*rz*z; z = -z; return *this; } plane &invert() { neg(); offset = -offset; return *this; } plane &scale(float k) { mul(k); return *this; } plane &translate(const vec &p) { offset += dot(p); return *this; } plane &normalize() { float mag = magnitude(); div(mag); offset /= mag; return *this; } float zintersect(const vec &p) const { return -(x*p.x+y*p.y+offset)/z; } float zdelta(const vec &p) const { return -(x*p.x+y*p.y)/z; } float zdist(const vec &p) const { return p.z-zintersect(p); } }; struct triangle { vec a, b, c; triangle(const vec &a, const vec &b, const vec &c) : a(a), b(b), c(c) {} triangle() {} triangle &add(const vec &o) { a.add(o); b.add(o); c.add(o); return *this; } triangle &sub(const vec &o) { a.sub(o); b.sub(o); c.sub(o); return *this; } bool operator==(const triangle &t) const { return a == t.a && b == t.b && c == t.c; } }; /** Cube 2 uses 3 different linear coordinate systems which are oriented around each of the axis dimensions. So any point within the game can be defined by four coordinates: (d, x, y, z) d is the reference axis dimension x is the coordinate of the ROW dimension y is the coordinate of the COL dimension z is the coordinate of the reference dimension (DEPTH) typically, if d is not used, then it is implicitly the Z dimension. ie: d=z => x=x, y=y, z=z **/ // DIM: X=0 Y=1 Z=2. const int R[3] = {1, 2, 0}; // row const int C[3] = {2, 0, 1}; // col const int D[3] = {0, 1, 2}; // depth struct ivec { union { struct { int x, y, z; }; struct { int r, g, b; }; int v[3]; }; ivec() {} ivec(const vec &v) : x(int(v.x)), y(int(v.y)), z(int(v.z)) {} explicit ivec(int i) { x = ((i&1)>>0); y = ((i&2)>>1); z = ((i&4)>>2); } ivec(int a, int b, int c) : x(a), y(b), z(c) {} ivec(int d, int row, int col, int depth) { v[R[d]] = row; v[C[d]] = col; v[D[d]] = depth; } ivec(int i, int cx, int cy, int cz, int size) { x = cx+((i&1)>>0)*size; y = cy+((i&2)>>1)*size; z = cz+((i&4)>>2)*size; } vec tovec() const { return vec(x, y, z); } int toint() const { return (x>0?1:0) + (y>0?2:0) + (z>0?4:0); } int &operator[](int i) { return v[i]; } int operator[](int i) const { return v[i]; } //int idx(int i) { return v[i]; } bool operator==(const ivec &v) const { return x==v.x && y==v.y && z==v.z; } bool operator!=(const ivec &v) const { return x!=v.x || y!=v.y || z!=v.z; } bool iszero() const { return x==0 && y==0 && z==0; } ivec &shl(int n) { x<<= n; y<<= n; z<<= n; return *this; } ivec &shr(int n) { x>>= n; y>>= n; z>>= n; return *this; } ivec &mul(int n) { x *= n; y *= n; z *= n; return *this; } ivec &div(int n) { x /= n; y /= n; z /= n; return *this; } ivec &add(int n) { x += n; y += n; z += n; return *this; } ivec &sub(int n) { x -= n; y -= n; z -= n; return *this; } ivec &mul(const ivec &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } ivec &div(const ivec &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } ivec &add(const ivec &v) { x += v.x; y += v.y; z += v.z; return *this; } ivec &sub(const ivec &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } ivec &mask(int n) { x &= n; y &= n; z &= n; return *this; } ivec &neg() { return mul(-1); } ivec &min(const ivec &o) { x = ::min(x, o.x); y = ::min(y, o.y); z = ::min(z, o.z); return *this; } ivec &max(const ivec &o) { x = ::max(x, o.x); y = ::max(y, o.y); z = ::max(z, o.z); return *this; } ivec &min(int n) { x = ::min(x, n); y = ::min(y, n); z = ::min(z, n); return *this; } ivec &max(int n) { x = ::max(x, n); y = ::max(y, n); z = ::max(z, n); return *this; } ivec &abs() { x = ::abs(x); y = ::abs(y); z = ::abs(z); return *this; } ivec &cross(const ivec &a, const ivec &b) { x = a.y*b.z-a.z*b.y; y = a.z*b.x-a.x*b.z; z = a.x*b.y-a.y*b.x; return *this; } int dot(const ivec &o) const { return x*o.x + y*o.y + z*o.z; } float dist(const plane &p) const { return x*p.x + y*p.y + z*p.z + p.offset; } }; static inline bool htcmp(const ivec &x, const ivec &y) { return x == y; } static inline uint hthash(const ivec &k) { return k.x^k.y^k.z; } struct bvec { union { struct { uchar x, y, z; }; struct { uchar r, g, b; }; uchar v[3]; }; bvec() {} bvec(uchar x, uchar y, uchar z) : x(x), y(y), z(z) {} bvec(const vec &v) : x((uchar)((v.x+1)*255/2)), y((uchar)((v.y+1)*255/2)), z((uchar)((v.z+1)*255/2)) {} uchar &operator[](int i) { return v[i]; } uchar operator[](int i) const { return v[i]; } bool operator==(const bvec &v) const { return x==v.x && y==v.y && z==v.z; } bool operator!=(const bvec &v) const { return x!=v.x || y!=v.y || z!=v.z; } bool iszero() const { return x==0 && y==0 && z==0; } vec tovec() const { return vec(x*(2.0f/255.0f)-1.0f, y*(2.0f/255.0f)-1.0f, z*(2.0f/255.0f)-1.0f); } void lerp(const bvec &a, const bvec &b, float t) { x = uchar(a.x + (b.x-a.x)*t); y = uchar(a.y + (b.y-a.y)*t); z = uchar(a.z + (b.z-a.z)*t); } void flip() { x -= 128; y -= 128; z -= 128; } }; struct glmatrixf { float v[16]; glmatrixf() {} glmatrixf(const float *m) { memcpy(v, m, sizeof(v)); } glmatrixf(const vec4 &a, const vec4 &b, const vec4 &c, const vec4 &d = vec4(0, 0, 0, 1)) { v[0] = a.x; v[1] = b.x; v[2] = c.x; v[3] = d.x; v[4] = a.y; v[5] = b.y; v[6] = c.y; v[7] = d.y; v[8] = a.z; v[9] = b.z; v[10] = c.z; v[11] = d.z; v[12] = a.w; v[13] = b.w; v[14] = c.w; v[15] = d.w; } glmatrixf(const matrix3x4 &m) { v[0] = m.a.x; v[1] = m.b.x; v[2] = m.c.x; v[3] = 0.0f; v[4] = m.a.y; v[5] = m.b.y; v[6] = m.c.y; v[7] = 0.0f; v[8] = m.a.z; v[9] = m.b.z; v[10] = m.c.z; v[11] = 0.0f; v[12] = m.a.w; v[13] = m.b.w; v[14] = m.c.w; v[15] = 1.0f; } float operator[](int i) const { return v[i]; } float &operator[](int i) { return v[i]; } #define ROTVEC(A, B) \ { \ float a = A, b = B; \ A = a*c + b*s; \ B = b*c - a*s; \ } void rotate_around_x(float angle) { float c = cosf(angle), s = sinf(angle); ROTVEC(v[4], v[8]); ROTVEC(v[5], v[9]); ROTVEC(v[6], v[10]); } void rotate_around_y(float angle) { float c = cosf(angle), s = sinf(angle); ROTVEC(v[8], v[0]); ROTVEC(v[9], v[1]); ROTVEC(v[10], v[2]); } void rotate_around_z(float angle) { float c = cosf(angle), s = sinf(angle); ROTVEC(v[0], v[4]); ROTVEC(v[1], v[5]); ROTVEC(v[2], v[6]); } #undef ROTVEC void rotate(float c, float s, const vec &d) { vec c1(d.x*d.x*(1-c)+c, d.y*d.x*(1-c)+d.z*s, d.x*d.z*(1-c)-d.y*s), c2(d.x*d.y*(1-c)-d.z*s, d.y*d.y*(1-c)+c, d.y*d.z*(1-c)+d.x*s), c3(d.x*d.z*(1-c)+d.y*s, d.y*d.z*(1-c)-d.x*s, d.z*d.z*(1-c)+c); vec r1(v[0], v[4], v[8]); v[0] = r1.dot(c1); v[4] = r1.dot(c2); v[8] = r1.dot(c3); vec r2(v[1], v[5], v[9]); v[1] = r2.dot(c1); v[5] = r2.dot(c2); v[9] = r2.dot(c3); vec r3(v[2], v[6], v[10]); v[2] = r3.dot(c1); v[6] = r3.dot(c2); v[10] = r3.dot(c3); } void rotate(float angle, const vec &d) { float c = cosf(angle), s = sinf(angle); rotate(c, s, d); } #define MULMAT(row, col) \ v[col + row] = x[row]*y[col] + x[row + 4]*y[col + 1] + x[row + 8]*y[col + 2] + x[row + 12]*y[col + 3]; template void mul(const XT x[16], const YT y[16]) { MULMAT(0, 0); MULMAT(1, 0); MULMAT(2, 0); MULMAT(3, 0); MULMAT(0, 4); MULMAT(1, 4); MULMAT(2, 4); MULMAT(3, 4); MULMAT(0, 8); MULMAT(1, 8); MULMAT(2, 8); MULMAT(3, 8); MULMAT(0, 12); MULMAT(1, 12); MULMAT(2, 12); MULMAT(3, 12); } #undef MULMAT void mul(const glmatrixf &x, const glmatrixf &y) { mul(x.v, y.v); } void mul(const glmatrixf &y) { mul(glmatrixf(*this), y); } void identity() { static const float m[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; memcpy(v, m, sizeof(v)); } void translate(float x, float y, float z) { v[12] += x; v[13] += y; v[14] += z; } void translate(const vec &o) { translate(o.x, o.y, o.z); } void transformedtranslate(float x, float y, float z, float scale = 1) { v[12] += (x*v[0] + y*v[4] + z*v[8])*scale; v[13] += (x*v[1] + y*v[5] + z*v[9])*scale; v[14] += (x*v[2] + y*v[6] + z*v[10])*scale; } void transformedtranslate(const vec &p, float scale = 1) { transformedtranslate(p.x, p.y, p.z, scale); } void scale(float x, float y, float z) { v[0] *= x; v[1] *= x; v[2] *= x; v[3] *= x; v[4] *= y; v[5] *= y; v[6] *= y; v[7] *= y; v[8] *= z; v[9] *= z; v[10] *= z; v[11] *= z; } void reflectz(float z) { v[12] += 2*z*v[8]; v[13] += 2*z*v[9]; v[14] += 2*z*v[10]; v[15] += 2*z*v[11]; v[8] = -v[8]; v[9] = -v[9]; v[10] = -v[10]; v[11] = -v[11]; } void projective(float zscale = 0.5f, float zoffset = 0.5f) { loopi(2) loopj(4) v[i + j*4] = 0.5f*(v[i + j*4] + v[3 + j*4]); loopj(4) v[2 + j*4] = zscale*v[2 + j*4] + zoffset*v[3 + j*4]; } void transpose() { swap(v[1], v[4]); swap(v[2], v[8]); swap(v[3], v[12]); swap(v[6], v[9]); swap(v[7], v[13]); swap(v[11], v[14]); } void frustum(float left, float right, float bottom, float top, float znear, float zfar) { float width = right - left, height = top - bottom, zrange = znear - zfar; v[0] = 2*znear/width; v[4] = 0; v[8] = (right + left)/width; v[12] = 0; v[1] = 0; v[5] = 2*znear/height; v[9] = (top + bottom)/height; v[13] = 0; v[2] = 0; v[6] = 0; v[10] = (zfar + znear)/zrange; v[14] = 2*znear*zfar/zrange; v[3] = 0; v[7] = 0; v[11] = -1; v[15] = 0; } void perspective(float fovy, float aspect, float znear, float zfar) { float ydist = znear * tan(fovy/2*RAD), xdist = ydist * aspect; frustum(-xdist, xdist, -ydist, ydist, znear, zfar); } void clip(const plane &p, const glmatrixf &m) { float x = ((p.x<0 ? -1 : (p.x>0 ? 1 : 0)) + m.v[8]) / m.v[0], y = ((p.y<0 ? -1 : (p.y>0 ? 1 : 0)) + m.v[9]) / m.v[5], w = (1 + m.v[10]) / m.v[14], scale = 2 / (x*p.x + y*p.y - p.z + w*p.offset); memcpy(v, m.v, sizeof(v)); v[2] = p.x*scale; v[6] = p.y*scale; v[10] = p.z*scale + 1.0f; v[14] = p.offset*scale; } float transformx(const vec &p) const { return p.x*v[0] + p.y*v[4] + p.z*v[8] + v[12]; } float transformy(const vec &p) const { return p.x*v[1] + p.y*v[5] + p.z*v[9] + v[13]; } float transformz(const vec &p) const { return p.x*v[2] + p.y*v[6] + p.z*v[10] + v[14]; } float transformw(const vec &p) const { return p.x*v[3] + p.y*v[7] + p.z*v[11] + v[15]; } float transformx(const vec4 &p) const { return p.x*v[0] + p.y*v[4] + p.z*v[8] + p.w*v[12]; } float transformy(const vec4 &p) const { return p.x*v[1] + p.y*v[5] + p.z*v[9] + p.w*v[13]; } float transformz(const vec4 &p) const { return p.x*v[2] + p.y*v[6] + p.z*v[10] + p.w*v[14]; } float transformw(const vec4 &p) const { return p.x*v[3] + p.y*v[7] + p.z*v[11] + p.w*v[15]; } template void transform(const T &in, vec &out) const { out.x = transformx(in); out.y = transformy(in); out.z = transformz(in); } template void transform(const T &in, vec4 &out) const { out.x = transformx(in); out.y = transformy(in); out.z = transformz(in); out.w = transformw(in); } template vec perspectivetransform(const T &in) const { return vec(transformx(in), transformy(in), transformz(in)).div(transformw(in)); } void transformnormal(const vec &in, vec &out) const { out.x = in.x*v[0] + in.y*v[4] + in.z*v[8]; out.y = in.x*v[1] + in.y*v[5] + in.z*v[9]; out.z = in.x*v[2] + in.y*v[6] + in.z*v[10]; } void transposedtransform(const vec &in, vec &out) const { vec p(in.x - v[12], in.y - v[13], in.z - v[14]); out.x = p.x*v[0] + p.y*v[1] + p.z*v[2]; out.y = p.x*v[4] + p.y*v[5] + p.z*v[6]; out.z = p.x*v[8] + p.y*v[9] + p.z*v[10]; } void transposedtransformnormal(const vec &in, vec &out) const { out.x = in.x*v[0] + in.y*v[1] + in.z*v[2]; out.y = in.x*v[4] + in.y*v[5] + in.z*v[6]; out.z = in.x*v[8] + in.y*v[9] + in.z*v[10]; } void transposedtransform(const plane &in, plane &out) const { out.x = in.x*v[0] + in.y*v[1] + in.z*v[2] + in.offset*v[3]; out.y = in.x*v[4] + in.y*v[5] + in.z*v[6] + in.offset*v[7]; out.z = in.x*v[8] + in.y*v[9] + in.z*v[10] + in.offset*v[11]; out.offset = in.x*v[12] + in.y*v[13] + in.z*v[14] + in.offset*v[15]; } float getscale() const { return sqrtf(v[0]*v[0] + v[4]*v[4] + v[8]*v[8]); } vec gettranslation() const { return vec(v[12], v[13], v[14]); } vec4 getrow(int i) const { return vec4(v[i], v[i+4], v[i+8], v[i+12]); } vec4 getcolumn(int i) const { i *= 4; return vec4(v[i], v[i+1], v[i+2], v[i+3]); } float determinant() const; void adjoint(const glmatrixf &m); bool invert(const glmatrixf &m, float mindet = 1.0e-10f); }; extern bool raysphereintersect(const vec ¢er, float radius, const vec &o, const vec &ray, float &dist); extern bool rayrectintersect(const vec &b, const vec &s, const vec &o, const vec &ray, float &dist, int &orient); extern bool linecylinderintersect(const vec &from, const vec &to, const vec &start, const vec &end, float radius, float &dist); extern const vec2 sincos360[]; sandboxgamemaker-2.7.1+dfsg/src/shared/iengine.h0000664000175000017500000005431311642642476021520 0ustar showardshoward// the interface the game uses to access the engine extern int curtime; // current frame time extern int lastmillis; // last time extern int totalmillis; // total elapsed time extern uint totalsecs; extern int gamespeed, paused; extern bvec watercolor; extern char *version; enum { MATF_VOLUME_SHIFT = 0, MATF_CLIP_SHIFT = 3, MATF_FLAG_SHIFT = 5, MATF_VOLUME = 7 << MATF_VOLUME_SHIFT, MATF_CLIP = 3 << MATF_CLIP_SHIFT, MATF_FLAGS = 7 << MATF_FLAG_SHIFT }; enum // cube empty-space materials { MAT_AIR = 0, // the default, fill the empty space with air MAT_WATER = 1 << MATF_VOLUME_SHIFT, // fill with water, showing waves at the surface MAT_LAVA = 2 << MATF_VOLUME_SHIFT, // fill with lava MAT_GLASS = 3 << MATF_VOLUME_SHIFT, // behaves like clip but is blended blueish MAT_NOCLIP = 1 << MATF_CLIP_SHIFT, // collisions always treat cube as empty MAT_CLIP = 2 << MATF_CLIP_SHIFT, // collisions always treat cube as solid MAT_GAMECLIP = 3 << MATF_CLIP_SHIFT, // game specific clip material MAT_DEATH = 1 << MATF_FLAG_SHIFT, // force player suicide MAT_ALPHA = 4 << MATF_FLAG_SHIFT // alpha blended }; #define isliquid(mat) ((mat)==MAT_WATER || (mat)==MAT_LAVA) #define isclipped(mat) ((mat)==MAT_GLASS) #define isdeadly(mat) ((mat)==MAT_LAVA) extern void lightent(extentity &e, float height = 8.0f); extern void lightreaching(const vec &target, vec &color, vec &dir, bool fast = false, extentity *e = 0, float ambient = 0.1f); extern entity *brightestlight(const vec &target, const vec &dir); enum { RAY_BB = 1, RAY_POLY = 3, RAY_ALPHAPOLY = 7, RAY_ENTS = 9, RAY_CLIPMAT = 16, RAY_SKIPFIRST = 32, RAY_EDITMAT = 64, RAY_SHADOW = 128, RAY_PASS = 256, RAY_SKIPSKY = 512 }; extern float raycube (const vec &o, const vec &ray, float radius = 0, int mode = RAY_CLIPMAT, int size = 0, extentity *t = 0); extern float raycubepos(const vec &o, const vec &ray, vec &hit, float radius = 0, int mode = RAY_CLIPMAT, int size = 0); extern float rayfloor (const vec &o, vec &floor, int mode = 0, float radius = 0); extern bool raycubelos(const vec &o, const vec &dest, vec &hitpos); extern int thirdperson; extern bool isthirdperson(); extern bool settexture(const char *name, int clamp = 0); extern void scaledscreenshot(char *filename, int format, int x = 0, int y = 0); //offtools: reload on receiving textures (replace dummy texture: notexture) extern void reloadslot(int n); // octaedit enum { EDIT_FACE = 0, EDIT_TEX, EDIT_MAT, EDIT_FLIP, EDIT_COPY, EDIT_PASTE, EDIT_ROTATE, EDIT_REPLACE, EDIT_DELCUBE, EDIT_REMIP }; struct selinfo { int corner; int cx, cxs, cy, cys; ivec o, s; int grid, orient; selinfo() : corner(0), cx(0), cxs(0), cy(0), cys(0), o(0, 0, 0), s(0, 0, 0), grid(8), orient(0) {} int size() const { return s.x*s.y*s.z; } int us(int d) const { return s[d]*grid; } bool operator==(const selinfo &sel) const { return o==sel.o && s==sel.s && grid==sel.grid && orient==sel.orient; } }; struct editinfo; extern editinfo *localedit; extern bool editmode; extern bool packeditinfo(editinfo *e, int &inlen, uchar *&outbuf, int &outlen); extern bool unpackeditinfo(editinfo *&e, const uchar *inbuf, int inlen, int outlen); extern void freeeditinfo(editinfo *&e); extern void pruneundos(int maxremain = 0); extern bool noedit(bool view = false, bool msg = true); extern void toggleedit(bool force = true); extern void mpeditface(int dir, int mode, selinfo &sel, bool local); extern void mpedittex(int tex, int allfaces, selinfo &sel, bool local); extern void mpeditmat(int matid, int filter, selinfo &sel, bool local); extern void mpflip(selinfo &sel, bool local); extern void mpcopy(editinfo *&e, selinfo &sel, bool local); extern void mppaste(editinfo *&e, selinfo &sel, bool local); extern void mprotate(int cw, selinfo &sel, bool local); extern void mpreplacetex(int oldtex, int newtex, bool insel, selinfo &sel, bool local); extern void mpdelcube(selinfo &sel, bool local); extern void mpremip(bool local); // command extern int variable(const char *name, int min, int cur, int max, int *storage, identfun fun, int flags); extern float fvariable(const char *name, float min, float cur, float max, float *storage, identfun fun, int flags); extern char *svariable(const char *name, const char *cur, char **storage, identfun fun, int flags); extern void setvar(const char *name, int i, bool dofunc = true, bool doclamp = true); extern void setfvar(const char *name, float f, bool dofunc = true, bool doclamp = true); extern void setsvar(const char *name, const char *str, bool dofunc = true); extern void setvarchecked(ident *id, int val); extern void setfvarchecked(ident *id, float val); extern void setsvarchecked(ident *id, const char *val); extern void touchvar(const char *name); extern int getvar(const char *name); extern int getvarmin(const char *name); extern int getvarmax(const char *name); extern bool identexists(const char *name); extern ident *getident(const char *name); extern ident *newident(const char *name, int flags = 0); extern bool addcommand(const char *name, identfun fun, const char *narg); extern uint *compilecode(const char *p); extern void executeret(const uint *code, tagval &result); extern void executeret(const char *p, tagval &result); extern char *executeret(const char *p); extern int execute(const uint *code); extern int execute(const char *p); extern bool execfile(const char *cfgfile, bool msg = true); extern void alias(const char *name, const char *action); extern void alias(const char *name, tagval &v); extern const char *getalias(const char *name); extern void writeescapedstring(stream *f, const char *s); // console enum { CON_INFO = 1<<0, CON_WARN = 1<<1, CON_ERROR = 1<<2, CON_DEBUG = 1<<3, CON_INIT = 1<<4, CON_ECHO = 1<<5 }; extern void conoutf(const char *s, ...); extern void conoutf(int type, const char *s, ...); extern void conoutfv(int type, const char *fmt, va_list args); extern void setlogfile(const char *fname); extern void closelogfile(); extern void logoutfv(const char *fmt, va_list args); extern void logoutf(const char *fmt, ...); // menus #ifndef NEWGUI extern vec menuinfrontofplayer(); extern void newgui(char *name, char *contents, char *header = NULL); extern void showgui(const char *name); extern int cleargui(int n = 0); #endif // octa extern int lookupmaterial(const vec &o); static inline bool insideworld(const vec &o) { extern int worldsize; return o.x>=0 && o.x=0 && o.y=0 && o.z &found); extern void mpeditent(int i, const vec &o, int type, int *attrs, bool local); extern vec getselpos(); extern int getworldsize(); extern int getmapversion(); extern void renderentcone(const extentity &e, const vec &dir, float radius, float angle); extern void renderentarrow(const extentity &e, const vec &dir, float radius); extern void renderentattachment(const extentity &e); extern void renderentsphere(const extentity &e, float radius); extern void renderentring(const extentity &e, float radius, int axis = 0); // main extern void fatal(const char *s, ...); extern void keyrepeat(bool on); // rendertext extern bool setfont(const char *name); extern void pushfont(); extern bool popfont(); extern void gettextres(int &w, int &h); extern void draw_text(const char *str, int left, int top, int r = 255, int g = 255, int b = 255, int a = 255, int cursor = -1, int maxwidth = -1); extern void draw_textf(const char *fstr, int left, int top, ...); extern int text_width(const char *str); extern void text_bounds(const char *str, int &width, int &height, int maxwidth = -1); extern int text_visible(const char *str, int hitx, int hity, int maxwidth); extern void text_pos(const char *str, int cursor, int &cx, int &cy, int maxwidth); // renderva enum { DL_SHRINK = 1<<0, DL_EXPAND = 1<<1, DL_FLASH = 1<<2 }; extern void adddynlight(const vec &o, float radius, const vec &color, int fade = 0, int peak = 0, int flags = 0, float initradius = 0, const vec &initcolor = vec(0, 0, 0), physent *owner = NULL); extern void dynlightreaching(const vec &target, vec &color, vec &dir, bool hud = false); extern void removetrackeddynlights(physent *owner = NULL); // rendergl extern physent *camera1; extern vec worldpos, camdir, camright, camup; extern void disablezoom(); extern vec calcavatarpos(const vec &pos, float dist); extern void damageblend(int n); extern void damagecompass(int n, const vec &loc); extern vec minimapcenter, minimapradius, minimapscale; extern void bindminimap(); extern void setnotextureshader(); extern void setdefaultshader(); extern void setlineshader(); // renderparticles enum { PART_BLOOD = 0, PART_WATER, PART_SMOKE, PART_STEAM, PART_FLAME, PART_FIREBALL1, PART_FIREBALL2, PART_FIREBALL3, PART_STREAK, PART_LIGHTNING, PART_EXPLOSION, PART_EXPLOSION_BLUE, PART_SPARK, PART_EDIT, PART_MUZZLE_FLASH, PART_MUZZLE_FLASH2, PART_MUZZLE_FLASH3, PART_HUD_ICON, PART_HUD_ICON_GREY, PART_TEXT, PART_METER, PART_METER_VS, PART_SNOW, PART_LEAVES, PART_LENS_FLARE }; extern int emitmillis; extern bool canaddparticles(); extern void regular_particle_splash(int type, int num, int fade, const vec &p, int color = 0xFFFFFF, float size = 1.0f, int radius = 150, int gravity = 2, int delay = 0); extern void regular_particle_flame(int type, const vec &p, float radius, float height, int color, int density = 3, float scale = 2.0f, float speed = 200.0f, float fade = 600.0f, int gravity = -15); extern void particle_splash(int type, int num, int fade, const vec &p, int color = 0xFFFFFF, float size = 1.0f, int radius = 150, int gravity = 2); extern void particle_trail(int type, int fade, const vec &from, const vec &to, int color = 0xFFFFFF, float size = 1.0f, int gravity = 20); extern void particle_text(const vec &s, const char *t, int type, int fade = 2000, int color = 0xFFFFFF, float size = 2.0f, int gravity = 0); extern void particle_textcopy(const vec &s, const char *t, int type, int fade = 2000, int color = 0xFFFFFF, float size = 2.0f, int gravity = 0); extern void particle_icon(const vec &s, int ix, int iy, int type, int fade = 2000, int color = 0xFFFFFF, float size = 2.0f, int gravity = 0); extern void particle_meter(const vec &s, float val, int type, int fade = 1, int color = 0xFFFFFF, int color2 = 0xFFFFF, float size = 2.0f); extern void particle_flare(const vec &p, const vec &dest, int fade, int type, int color = 0xFFFFFF, float size = 0.28f, physent *owner = NULL); extern void particle_fireball(const vec &dest, float max, int type, int fade = -1, int color = 0xFFFFFF, float size = 4.0f); extern void removetrackedparticles(physent *owner = NULL); extern void regularshape(int type, int radius, int color, int dir, int num, int fade, const vec &p, float size = 4.0f, float vel = 200.0f, int gravity = 2 ); extern void regularlensflare(vec o, uchar r, uchar g, uchar b, bool sun = false, bool sparkle = false, int sizemod = 100); // decal enum { DECAL_EMPTY = 0, DECAL_BURN, //activate when colision detection for particles are improved DECAL_STAIN, DECAL_RIPPLE, DECAL_LEAVES, DECAL_MAX }; extern void adddecal(int type, const vec ¢er, const vec &surface, float radius, const bvec &color = bvec(0xFF, 0xFF, 0xFF), int info = 0); // worldio extern string mpath, mname; extern bool load_world(const char *mname, const char *cname = NULL); extern bool save_world(const char *mname, bool nolms = false, bool octa = false); extern void getmapfilenames(const char *cname, bool fall = true); extern uint getmapcrc(); extern bool loadents(const char *fname, vector &ents, uint *crc = NULL); // physics extern void moveplayer(physent *pl, int moveres, bool local); extern bool moveplayer(physent *pl, int moveres, bool local, int curtime); extern bool collide(physent *d, const vec &dir = vec(0, 0, 0), float cutoff = 0.0f, bool playercol = true); extern bool bounce(physent *d, float secs, float elasticity, float waterfric); extern bool bounce(physent *d, float elasticity, float waterfric); extern void avoidcollision(physent *d, const vec &dir, physent *obstacle, float space); extern bool overlapsdynent(const vec &o, float radius); extern bool movecamera(physent *pl, const vec &dir, float dist, float stepdist); extern void physicsframe(); extern void dropenttofloor(entity *e); extern bool droptofloor(vec &o, float radius, float height); extern void vecfromyawpitch(float yaw, float pitch, int move, int strafe, vec &m); extern void vectoyawpitch(const vec &v, float &yaw, float &pitch); extern bool moveplatform(physent *p, const vec &dir); extern void updatephysstate(physent *d); extern void cleardynentcache(); extern void updatedynentcache(physent *d); extern bool entinmap(dynent *d, bool avoidplayers = false); extern void findplayerspawn(dynent *d, int forceent = -1, int tag = 0); // sound extern int playsound(int n, const vec *loc = NULL, extentity *ent = NULL, int loops = 0, int fade = 0, int chanid = -1, int radius = 0, int expire = -1); extern int playsoundname(const char *s, const vec *loc = NULL, int vol = 0, int loops = 0, int fade = 0, int chanid = -1, int radius = 0, int expire = -1); extern bool stopsound(int n, int chanid, int fade = 0); extern void stopsounds(); extern void initsound(); // rendermodel enum { MDL_CULL_VFC = 1<<0, MDL_CULL_DIST = 1<<1, MDL_CULL_OCCLUDED = 1<<2, MDL_CULL_QUERY = 1<<3, MDL_SHADOW = 1<<4, MDL_DYNSHADOW = 1<<5, MDL_LIGHT = 1<<6, MDL_DYNLIGHT = 1<<7, MDL_FULLBRIGHT = 1<<8, MDL_NORENDER = 1<<9, MDL_LIGHT_FAST = 1<<10, MDL_HUD = 1<<11, MDL_GHOST = 1<<12 }; struct model; struct modelattach { const char *tag, *name; int anim, basetime; vec *pos; model *m; modelattach() : tag(NULL), name(NULL), anim(-1), basetime(0), pos(NULL), m(NULL) {} modelattach(const char *tag, const char *name, int anim = -1, int basetime = 0) : tag(tag), name(name), anim(anim), basetime(basetime), pos(NULL), m(NULL) {} modelattach(const char *tag, vec *pos) : tag(tag), name(NULL), anim(-1), basetime(0), pos(pos), m(NULL) {} }; extern void startmodelbatches(); extern void endmodelbatches(); extern void rendermodel(entitylight *light, const char *mdl, int anim, const vec &o, float yaw = 0, float pitch = 0, float roll = 0, int cull = MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED | MDL_LIGHT, dynent *d = NULL, modelattach *a = NULL, int basetime = 0, int basetime2 = 0, float trans = 1, int colour = 0xFFFFFF); extern void abovemodel(vec &o, const char *mdl); extern void rendershadow(dynent *d); extern void renderclient(dynent *d, const char *mdlname, modelattach *attachments, int hold, int attack, int attackdelay, int lastaction, int lastpain, float fade = 1, bool ragdoll = false, int colour = 0xFFFFFF); extern void interpolateorientation(dynent *d, float &interpyaw, float &interppitch); extern void setbbfrommodel(dynent *d, const char *mdl); extern const char *mapmodelname(int i); extern model *loadmodel(const char *name, int i = -1, bool msg = false); extern void preloadmodel(const char *name); extern void flushpreloadedmodels(); // ragdoll extern void ragdolladdvel(dynent *d, vec &vel); extern void moveragdoll(dynent *d); extern void cleanragdoll(dynent *d); // server #define MAXCLIENTS 128 // DO NOT set this any higher #define MAXTRANS 5000 // max amount of data to swallow in 1 go extern int maxclients; enum { DISC_NONE = 0, DISC_EOP, DISC_CN, DISC_KICK, DISC_TAGT, DISC_IPBAN, DISC_PRIVATE, DISC_MAXCLIENTS, DISC_TIMEOUT, DISC_OVERFLOW, DISC_NUM }; extern void *getclientinfo(int i); extern ENetPeer *getclientpeer(int i); extern ENetPacket *sendf(int cn, int chan, const char *format, ...); extern ENetPacket *sendfile(int cn, int chan, stream *file, const char *format = "", ...); extern void sendpacket(int cn, int chan, ENetPacket *packet, int exclude = -1); extern void flushserver(bool force); extern int getnumclients(); extern uint getclientip(int n); extern void putint(ucharbuf &p, int n); extern void putint(packetbuf &p, int n); extern void putint(vector &p, int n); extern int getint(ucharbuf &p); extern void putuint(ucharbuf &p, int n); extern void putuint(packetbuf &p, int n); extern void putuint(vector &p, int n); extern int getuint(ucharbuf &p); extern void putfloat(ucharbuf &p, float f); extern void putfloat(packetbuf &p, float f); extern void putfloat(vector &p, float f); extern float getfloat(ucharbuf &p); extern void sendstring(const char *t, ucharbuf &p); extern void sendstring(const char *t, packetbuf &p); extern void sendstring(const char *t, vector &p); extern void getstring(char *t, ucharbuf &p, int len = MAXTRANS); extern void filtertext(char *dst, const char *src, bool whitespace = true, int len = sizeof(string)-1); extern void localconnect(); extern void localdisconnect(bool cleanup = true); extern void disconnect_client(int n, int reason); extern void kicknonlocalclients(int reason = DISC_NONE); extern bool hasnonlocalclients(); extern bool haslocalclients(); extern void sendserverinforeply(ucharbuf &p); extern bool requestmaster(const char *req); extern bool requestmasterf(const char *fmt, ...); // client extern void sendclientpacket(ENetPacket *packet, int chan); extern void flushclient(); extern void disconnect(bool async = false, bool cleanup = true); extern bool isconnected(bool attempt = false); extern const ENetAddress *connectedpeer(); extern bool multiplayer(bool msg = true); extern void neterr(const char *s, bool disc = true); extern void gets2c(); // crypto extern void genprivkey(const char *seed, vector &privstr, vector &pubstr); extern bool hashstring(const char *str, char *result, int maxlen); extern void answerchallenge(const char *privstr, const char *challenge, vector &answerstr); extern void *parsepubkey(const char *pubstr); extern void freepubkey(void *pubkey); extern void *genchallenge(void *pubkey, const void *seed, int seedlen, vector &challengestr); extern void freechallenge(void *answer); extern bool checkchallenge(const char *answerstr, void *correct); // 3dgui struct Texture; struct VSlot; extern Texture *textureload(const char *name, int clamp = 0, bool mipit = true, bool msg = true); extern bool settexture(Texture *&tex); enum { EDITORFOCUSED = 1, EDITORUSED, EDITORFOREVER }; #ifndef NEWGUI enum { G3D_DOWN = 1, G3D_UP = 2, G3D_PRESSED = 4, G3D_ROLLOVER = 8, G3D_DRAGGED = 16 }; struct g3d_gui { virtual ~g3d_gui() {} virtual void start(int starttime, float basescale, int *tab = NULL, bool allowinput = true) = 0; virtual void end() = 0; virtual int text(const char *text, int color, const char *icon = NULL) = 0; int textf(const char *fmt, int color, const char *icon = NULL, ...) { defvformatstring(str, icon, fmt); return text(str, color, icon); } virtual int button(const char *text, int color, const char *icon = NULL) = 0; int buttonf(const char *fmt, int color, const char *icon = NULL, ...) { defvformatstring(str, icon, fmt); return button(str, color, icon); } virtual int title(const char *text, int color, const char *icon = NULL) = 0; int titlef(const char *fmt, int color, const char *icon = NULL, ...) { defvformatstring(str, icon, fmt); return title(str, color, icon); } virtual void background(int color, int parentw = 0, int parenth = 0) = 0; virtual void pushlist(int align = -1) {} virtual void poplist() {} virtual void allowautotab(bool on) = 0; virtual bool shouldtab() { return false; } virtual void tab(const char *name = NULL, int color = 0) = 0; virtual int image(Texture *t, float scale, bool overlaid = false) = 0; virtual int texture(VSlot &vslot, float scale, bool overlaid = true) = 0; virtual void slider(int &val, int vmin, int vmax, int color, char *label = NULL, bool reverse = false) = 0; virtual void separator() = 0; virtual void progress(float percent) = 0; virtual void strut(float size) = 0; virtual void space(float size) = 0; virtual char *keyfield(const char *name, int color, int length, int height = 0, const char *initval = NULL, int initmode = EDITORFOCUSED) = 0; virtual char *field(const char *name, int color, int length, int height = 0, const char *initval = NULL, int initmode = EDITORFOCUSED) = 0; virtual void textbox(const char *text, int width, int height, int color = 0xFFFFFF) = 0; virtual void mergehits(bool on) = 0; }; struct g3d_callback { virtual ~g3d_callback() {} int starttime() { return totalmillis; } virtual void gui(g3d_gui &g, bool firstpass) = 0; }; enum { GUI_2D = 1<<0, GUI_FOLLOW = 1<<1, GUI_FORCE_2D = 1<<2, GUI_BOTTOM = 1<<3 }; extern void g3d_addgui(g3d_callback *cb, vec &origin, int flags = 0); extern bool g3d_movecursor(int dx, int dy); extern void g3d_cursorpos(float &x, float &y); extern void g3d_resetcursor(); extern void g3d_limitscale(float scale); #endif extern vector entgroup; extern int efocus, enthover, entorient; //rendergl #define RENDERPUSHX 8.0f #define RENDERPUSHZ 0.1f extern void renderdir(vec &o, float yaw, float pitch, bool nf = true); extern void renderradius(vec &o, float height, float radius, bool nf = true); extern bool shadowmapping, reflecting, envmapping, minimapping, glaring; extern int refracting; #define rendernormally (!shadowmapping && !envmapping && !reflecting && !minimapping && !refracting && !glaring) //water sandboxgamemaker-2.7.1+dfsg/src/shared/stream.cpp0000664000175000017500000011154211660231276021716 0ustar showardshoward#include "cube.h" ///////////////////////// character conversion /////////////// int iscubeprint(int c) { static const char flags[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; return flags[c]; } int cube2uni(int c) { static const int conv[256] = { 0, 192, 193, 194, 195, 196, 197, 198, 199, 9, 10, 11, 12, 13, 200, 201, 202, 203, 204, 205, 206, 207, 209, 210, 211, 212, 213, 214, 216, 217, 218, 219, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 220, 221, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 241, 242, 243, 244, 245, 246, 248, 249, 250, 251, 252, 253, 255, 0x104, 0x105, 0x106, 0x107, 0x10C, 0x10D, 0x10E, 0x10F, 0x118, 0x119, 0x11A, 0x11B, 0x11E, 0x11F, 0x130, 0x131, 0x141, 0x142, 0x143, 0x144, 0x147, 0x148, 0x150, 0x151, 0x152, 0x153, 0x158, 0x159, 0x15A, 0x15B, 0x15E, 0x15F, 0x160, 0x161, 0x164, 0x165, 0x16E, 0x16F, 0x170, 0x171, 0x178, 0x179, 0x17A, 0x17B, 0x17C, 0x17D, 0x17E, 0x404, 0x411, 0x413, 0x414, 0x416, 0x417, 0x418, 0x419, 0x41B, 0x41F, 0x423, 0x424, 0x426, 0x427, 0x428, 0x429, 0x42A, 0x42B, 0x42C, 0x42D, 0x42E, 0x42F, 0x431, 0x432, 0x433, 0x434, 0x436, 0x437, 0x438, 0x439, 0x43A, 0x43B, 0x43C, 0x43D, 0x43F, 0x442, 0x444, 0x446, 0x447, 0x448, 0x449, 0x44A, 0x44B, 0x44C, 0x44D, 0x44E, 0x44F, 0x454, 0x490, 0x491 }; return conv[c]; } int uni2cube(int c) { static const int offsets[256] = { 0, 256, 658, 658, 512, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, }; static const int chars[878] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 12, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 14, 15, 16, 17, 18, 19, 20, 21, 0, 22, 23, 24, 25, 26, 27, 0, 28, 29, 30, 31, 127, 128, 0, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 0, 146, 147, 148, 149, 150, 151, 0, 152, 153, 154, 155, 156, 157, 0, 158, 0, 0, 0, 0, 159, 160, 161, 162, 0, 0, 0, 0, 163, 164, 165, 166, 0, 0, 0, 0, 0, 0, 0, 0, 167, 168, 169, 170, 0, 0, 171, 172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 173, 174, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 175, 176, 177, 178, 0, 0, 179, 180, 0, 0, 0, 0, 0, 0, 0, 181, 182, 183, 184, 0, 0, 0, 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, 192, 0, 0, 193, 194, 0, 0, 0, 0, 0, 0, 0, 0, 195, 196, 197, 198, 0, 0, 0, 0, 0, 0, 199, 200, 201, 202, 203, 204, 205, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 206, 83, 73, 21, 74, 0, 0, 0, 0, 0, 0, 0, 65, 207, 66, 208, 209, 69, 210, 211, 212, 213, 75, 214, 77, 72, 79, 215, 80, 67, 84, 216, 217, 88, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 97, 228, 229, 230, 231, 101, 232, 233, 234, 235, 236, 237, 238, 239, 111, 240, 112, 99, 241, 121, 242, 120, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 0, 141, 0, 0, 253, 115, 105, 145, 106, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 254, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; return uint(c) <= 0xFFFF ? chars[offsets[c>>8] + (c&0xFF)] : 0; } int decodeutf8(uchar *dstbuf, uchar *srcbuf, int len, int *carry) { uchar *dst = dstbuf, *src = srcbuf, *end = &srcbuf[len]; if(dstbuf == srcbuf) { for(uchar *end4 = &srcbuf[len&~3]; src < end4; src += 4) if(*(int *)src & 0x80808080) goto decode; for(; src < end; src++) if(*src & 0x80) goto decode; if(carry) *carry += len; return len; } decode: dst += src - srcbuf; while(src < end) { int c = *src++; if(c < 0x80) *dst++ = c; else if(c >= 0xC0) { int uni; if(c >= 0xE0) { if(c >= 0xF0) { if(c >= 0xF8) { if(c >= 0xFC) { if(c >= 0xFE) continue; uni = c&1; if(end - src < 5) break; c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); } else { uni = c&3; if(end - src < 4) break; } c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); } else { uni = c&7; if(end - src < 3) break; } c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); } else { uni = c&0xF; if(end - src < 2) break; } c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); } else { uni = c&0x1F; if(end - src < 1) break; } c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); c = uni2cube(uni); if(!c) continue; *dst++ = c; } } if(carry) *carry += src - srcbuf; return dst - dstbuf; } int encodeutf8(uchar *dstbuf, int dstlen, uchar *srcbuf, int srclen, int *carry) { uchar *dst = dstbuf, *dstend = &dstbuf[dstlen], *src = srcbuf, *srcend = &srcbuf[srclen]; for(uchar *end4 = &srcbuf[min(srclen, dstlen)&~3]; src < end4; src += 4, dst += 4) { int c = *(int *)src; if(c & 0x80808080) goto encode; *(int *)dst = c; } encode: while((srclen = srcend - src) > 0 && (dstlen = dstend - dst) > 0) { int c; for(uchar *end = &src[min(srclen, dstlen)]; !((c = *src) & 0x80);) { *dst++ = c; if(++src >= end) goto done; } while(c & 0x80) { int uni = cube2uni(c); if(uni <= 0x7F) { if(dstlen < 1) goto done; *dst++ = uni; goto uni1; } else if(uni <= 0x7FF) { if(dstlen < 2) goto done; *dst++ = 0xC0 | (uni>>6); goto uni2; } else if(uni <= 0xFFFF) { if(dstlen < 3) goto done; *dst++ = 0xE0 | (uni>>12); goto uni3; } else if(uni <= 0x1FFFFF) { if(dstlen < 4) goto done; *dst++ = 0xF0 | (uni>>18); goto uni4; } else if(uni <= 0x3FFFFFF) { if(dstlen < 5) goto done; *dst++ = 0xF8 | (uni>>24); goto uni5; } else if(uni <= 0x7FFFFFFF) { if(dstlen < 6) goto done; *dst++ = 0xFC | (uni>>30); goto uni6; } else goto uni1; uni6: *dst++ = 0x80 | ((uni>>24)&0x3F); uni5: *dst++ = 0x80 | ((uni>>18)&0x3F); uni4: *dst++ = 0x80 | ((uni>>12)&0x3F); uni3: *dst++ = 0x80 | ((uni>>6)&0x3F); uni2: *dst++ = 0x80 | (uni&0x3F); uni1: if(++src >= srcend) goto done; c = *src; } } done: if(carry) *carry += src - srcbuf; return dst - dstbuf; } ///////////////////////// file system /////////////////////// #ifdef WIN32 #include #else #include #include #include #include #endif string homedir = ""; vector packagedirs; char *makerelpath(const char *dir, const char *file, const char *prefix, const char *cmd) { static string tmp; if(prefix) copystring(tmp, prefix); else tmp[0] = '\0'; if(file[0]=='<') { const char *end = strrchr(file, '>'); if(end) { size_t len = strlen(tmp); copystring(&tmp[len], file, min(sizeof(tmp)-len, size_t(end+2-file))); file = end+1; } } if(cmd) concatstring(tmp, cmd); if(dir) { defformatstring(pname)("%s/%s", dir, file); concatstring(tmp, pname); } else concatstring(tmp, file); return tmp; } char *path(char *s) { for(char *curpart = s;;) { char *endpart = strchr(curpart, '&'); if(endpart) *endpart = '\0'; if(curpart[0]=='<') { char *file = strrchr(curpart, '>'); if(!file) return s; curpart = file+1; } for(char *t = curpart; (t = strpbrk(t, "/\\")); *t++ = PATHDIV); for(char *prevdir = NULL, *curdir = s;;) { prevdir = curdir[0]==PATHDIV ? curdir+1 : curdir; curdir = strchr(prevdir, PATHDIV); if(!curdir) break; if(prevdir+1==curdir && prevdir[0]=='.') { memmove(prevdir, curdir+1, strlen(curdir+1)+1); curdir = prevdir; } else if(curdir[1]=='.' && curdir[2]=='.' && curdir[3]==PATHDIV) { if(prevdir+2==curdir && prevdir[0]=='.' && prevdir[1]=='.') continue; memmove(prevdir, curdir+4, strlen(curdir+4)+1); curdir = prevdir; } } if(endpart) { *endpart = '&'; curpart = endpart+1; } else break; } return s; } char *path(const char *s, bool copy) { static string tmp; copystring(tmp, s); path(tmp); return tmp; } const char *parentdir(const char *directory) { const char *p = directory + strlen(directory); while(p > directory && *p != '/' && *p != '\\') p--; static string parent; size_t len = p-directory+1; copystring(parent, directory, len); return parent; } bool fileexists(const char *path, const char *mode) { bool exists = true; if(mode[0]=='w' || mode[0]=='a') path = parentdir(path); #ifdef WIN32 if(GetFileAttributes(path) == INVALID_FILE_ATTRIBUTES) exists = false; #else if(access(path, R_OK | (mode[0]=='w' || mode[0]=='a' ? W_OK : 0)) == -1) exists = false; #endif return exists; } bool createdir(const char *path) { size_t len = strlen(path); if(path[len-1]==PATHDIV) { static string strip; path = copystring(strip, path, len); } #ifdef WIN32 return CreateDirectory(path, NULL)!=0; #else return mkdir(path, 0777)==0; #endif } //__offtools__ simple directory check (no other file attributes) bool isdir(char *file) { path(file); #ifdef WIN32 if(GetFileAttributes(file) & FILE_ATTRIBUTE_DIRECTORY) return true; #else struct stat attr; if(-1 != stat(file, &attr)) { if(attr.st_mode & S_IFDIR) { return true; } } #endif return false; } size_t fixpackagedir(char *dir) { path(dir); size_t len = strlen(dir); if(len > 0 && dir[len-1] != PATHDIV) { dir[len] = PATHDIV; dir[len+1] = '\0'; } return len; } bool subhomedir(char *dst, int len, const char *src) { const char *sub = strstr(src, "$HOME"); if(!sub) sub = strchr(src, '~'); if(sub && sub-src < len) { #ifdef WIN32 char home[MAX_PATH+1]; home[0] = '\0'; if(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, home) != S_OK || !home[0]) return false; #else const char *home = getenv("HOME"); if(!home || !home[0]) return false; #endif dst[sub-src] = '\0'; concatstring(dst, home); concatstring(dst, sub+(*sub == '~' ? 1 : strlen("$HOME"))); } return true; } const char *sethomedir(const char *dir) { string pdir; copystring(pdir, dir); if(!subhomedir(pdir, sizeof(pdir), dir) || !fixpackagedir(pdir)) return NULL; copystring(homedir, pdir); return homedir; } const char *addpackagedir(const char *dir) { string pdir; copystring(pdir, dir); if(!subhomedir(pdir, sizeof(pdir), dir) || !fixpackagedir(pdir)) return NULL; return packagedirs.add(newstring(pdir)); } const char *findfile(const char *filename, const char *mode) { static string s; if(homedir[0]) { formatstring(s)("%s%s", homedir, filename); if(fileexists(s, mode)) return s; if(mode[0]=='w' || mode[0]=='a') { string dirs; copystring(dirs, s); char *dir = strchr(dirs[0]==PATHDIV ? dirs+1 : dirs, PATHDIV); while(dir) { *dir = '\0'; if(!fileexists(dirs, "r") && !createdir(dirs)) return s; *dir = PATHDIV; dir = strchr(dir+1, PATHDIV); } return s; } } if(mode[0]=='w' || mode[0]=='a') return filename; loopv(packagedirs) { formatstring(s)("%s%s", packagedirs[i], filename); if(fileexists(s, mode)) return s; } return filename; } bool listdir(const char *dir, bool rel, const char *ext, vector &files) { int extsize = ext ? (int)strlen(ext)+1 : 0; string dirname; copystring(dirname, dir); path(dirname); #ifdef WIN32 defformatstring(pathname)(rel ? ".\\%s\\*.%s" : "%s\\*.%s", dirname, ext ? ext : "*"); WIN32_FIND_DATA FindFileData; HANDLE Find = FindFirstFile(pathname, &FindFileData); if(Find != INVALID_HANDLE_VALUE) { do { files.add(newstring(FindFileData.cFileName, (int)strlen(FindFileData.cFileName) - extsize)); } while(FindNextFile(Find, &FindFileData)); FindClose(Find); return true; } #else defformatstring(pathname)(rel ? "./%s" : "%s", dirname); DIR *d = opendir(pathname); if(d) { struct dirent *de; while((de = readdir(d)) != NULL) { if(!ext) files.add(newstring(de->d_name)); else { int namelength = (int)strlen(de->d_name) - extsize; if(namelength > 0 && de->d_name[namelength] == '.' && strncmp(de->d_name+namelength+1, ext, extsize-1)==0) files.add(newstring(de->d_name, namelength)); } } closedir(d); return true; } #endif else return false; } int listfiles(const char *dir, const char *ext, vector &files) { int dirs = 0; if(listdir(dir, true, ext, files)) dirs++; string s; if(homedir[0]) { formatstring(s)("%s%s", homedir, dir); if(listdir(s, false, ext, files)) dirs++; } loopv(packagedirs) { formatstring(s)("%s%s", packagedirs[i], dir); if(listdir(s, false, ext, files)) dirs++; } #ifndef STANDALONE dirs += listzipfiles(dir, ext, files); #endif return dirs; } #ifndef STANDALONE static int rwopsseek(SDL_RWops *rw, int pos, int whence) { stream *f = (stream *)rw->hidden.unknown.data1; if((!pos && whence==SEEK_CUR) || f->seek(pos, whence)) return (int)f->tell(); return -1; } static int rwopsread(SDL_RWops *rw, void *buf, int size, int nmemb) { stream *f = (stream *)rw->hidden.unknown.data1; return f->read(buf, size*nmemb)/size; } static int rwopswrite(SDL_RWops *rw, const void *buf, int size, int nmemb) { stream *f = (stream *)rw->hidden.unknown.data1; return f->write(buf, size*nmemb)/size; } static int rwopsclose(SDL_RWops *rw) { return 0; } SDL_RWops *stream::rwops() { SDL_RWops *rw = SDL_AllocRW(); if(!rw) return NULL; rw->hidden.unknown.data1 = this; rw->seek = rwopsseek; rw->read = rwopsread; rw->write = rwopswrite; rw->close = rwopsclose; return rw; } #endif stream::offset stream::size() { offset pos = tell(), endpos; if(pos < 0 || !seek(0, SEEK_END)) return -1; endpos = tell(); return pos == endpos || seek(pos, SEEK_SET) ? endpos : -1; } bool stream::getline(char *str, int len) { loopi(len-1) { if(read(&str[i], 1) != 1) { str[i] = '\0'; return i > 0; } else if(str[i] == '\n') { str[i+1] = '\0'; return true; } } if(len > 0) str[len-1] = '\0'; return true; } int stream::printf(const char *fmt, ...) { char buf[512]; char *str = buf; va_list args; #if defined(WIN32) && !defined(__GNUC__) va_start(args, fmt); size_t len = _vscprintf(fmt, args); if(len >= sizeof(buf)) str = new char[len+1]; _vsnprintf(str, len+1, fmt, args); va_end(args); #else va_start(args, fmt); size_t len = vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); if(len >= sizeof(buf)) { str = new char[len+1]; va_start(args, fmt); vsnprintf(str, len+1, fmt, args); va_end(args); } #endif int n = write(str, len); if(str != buf) delete[] str; return n; } struct filestream : stream { FILE *file; filestream() : file(NULL) {} ~filestream() { close(); } bool open(const char *name, const char *mode) { if(file) return false; file = fopen(name, mode); return file!=NULL; } bool opentemp(const char *name, const char *mode) { if(file) return false; #ifdef WIN32 file = fopen(name, mode); #else file = tmpfile(); #endif return file!=NULL; } void close() { if(file) { fclose(file); file = NULL; } } bool end() { return feof(file)!=0; } offset tell() { #ifdef WIN32 #ifdef __GNUC__ return ftello64(file); #else return _ftelli64(file); #endif #else return ftello(file); #endif } bool seek(offset pos, int whence) { #ifdef WIN32 #ifdef __GNUC__ return fseeko64(file, pos, whence) >= 0; #else return _fseeki64(file, pos, whence) >= 0; #endif #else return fseeko(file, pos, whence) >= 0; #endif } int read(void *buf, int len) { return (int)fread(buf, 1, len, file); } int write(const void *buf, int len) { return (int)fwrite(buf, 1, len, file); } int getchar() { return fgetc(file); } bool putchar(int c) { return fputc(c, file)!=EOF; } bool getline(char *str, int len) { return fgets(str, len, file)!=NULL; } bool putstring(const char *str) { return fputs(str, file)!=EOF; } int printf(const char *fmt, ...) { va_list v; va_start(v, fmt); int result = vfprintf(file, fmt, v); va_end(v); return result; } }; #ifndef STANDALONE VAR(dbggz, 0, 0, 1); #endif struct gzstream : stream { enum { MAGIC1 = 0x1F, MAGIC2 = 0x8B, BUFSIZE = 16384, OS_UNIX = 0x03 }; enum { F_ASCII = 0x01, F_CRC = 0x02, F_EXTRA = 0x04, F_NAME = 0x08, F_COMMENT = 0x10, F_RESERVED = 0xE0 }; stream *file; z_stream zfile; uchar *buf; bool reading, writing, autoclose; uint crc; int headersize; gzstream() : file(NULL), buf(NULL), reading(false), writing(false), autoclose(false), crc(0), headersize(0) { zfile.zalloc = NULL; zfile.zfree = NULL; zfile.opaque = NULL; zfile.next_in = zfile.next_out = NULL; zfile.avail_in = zfile.avail_out = 0; } ~gzstream() { close(); } void writeheader() { uchar header[] = { MAGIC1, MAGIC2, Z_DEFLATED, 0, 0, 0, 0, 0, 0, OS_UNIX }; file->write(header, sizeof(header)); } void readbuf(int size = BUFSIZE) { if(!zfile.avail_in) zfile.next_in = (Bytef *)buf; size = min(size, int(&buf[BUFSIZE] - &zfile.next_in[zfile.avail_in])); int n = file->read(zfile.next_in + zfile.avail_in, size); if(n > 0) zfile.avail_in += n; } int readbyte(int size = BUFSIZE) { if(!zfile.avail_in) readbuf(size); if(!zfile.avail_in) return 0; zfile.avail_in--; return *(uchar *)zfile.next_in++; } void skipbytes(int n) { while(n > 0 && zfile.avail_in > 0) { int skipped = min(n, (int)zfile.avail_in); zfile.avail_in -= skipped; zfile.next_in += skipped; n -= skipped; } if(n <= 0) return; file->seek(n, SEEK_CUR); } bool checkheader() { readbuf(10); if(readbyte() != MAGIC1 || readbyte() != MAGIC2 || readbyte() != Z_DEFLATED) return false; int flags = readbyte(); if(flags & F_RESERVED) return false; skipbytes(6); if(flags & F_EXTRA) { int len = readbyte(512); len |= readbyte(512)<<8; skipbytes(len); } if(flags & F_NAME) while(readbyte(512)); if(flags & F_COMMENT) while(readbyte(512)); if(flags & F_CRC) skipbytes(2); headersize = int(file->tell() - zfile.avail_in); return zfile.avail_in > 0 || !file->end(); } bool open(stream *f, const char *mode, bool needclose, int level) { if(file) return false; for(; *mode; mode++) { if(*mode=='r') { reading = true; break; } else if(*mode=='w') { writing = true; break; } } if(reading) { if(inflateInit2(&zfile, -MAX_WBITS) != Z_OK) reading = false; } else if(writing && deflateInit2(&zfile, level, Z_DEFLATED, -MAX_WBITS, min(MAX_MEM_LEVEL, 8), Z_DEFAULT_STRATEGY) != Z_OK) writing = false; if(!reading && !writing) return false; autoclose = needclose; file = f; crc = crc32(0, NULL, 0); buf = new uchar[BUFSIZE]; if(reading) { if(!checkheader()) { stopreading(); return false; } } else if(writing) writeheader(); return true; } uint getcrc() { return crc; } void finishreading() { if(!reading) return; #ifndef STANDALONE if(dbggz) { uint checkcrc = 0, checksize = 0; loopi(4) checkcrc |= uint(readbyte()) << (i*8); loopi(4) checksize |= uint(readbyte()) << (i*8); if(checkcrc != crc) conoutf(CON_DEBUG, "gzip crc check failed: read %X, calculated %X", checkcrc, crc); if(checksize != zfile.total_out) conoutf(CON_DEBUG, "gzip size check failed: read %d, calculated %d", checksize, zfile.total_out); } #endif } void stopreading() { if(!reading) return; inflateEnd(&zfile); reading = false; } void finishwriting() { if(!writing) return; for(;;) { int err = zfile.avail_out > 0 ? deflate(&zfile, Z_FINISH) : Z_OK; if(err != Z_OK && err != Z_STREAM_END) break; flush(); if(err == Z_STREAM_END) break; } uchar trailer[8] = { crc&0xFF, (crc>>8)&0xFF, (crc>>16)&0xFF, (crc>>24)&0xFF, zfile.total_in&0xFF, (zfile.total_in>>8)&0xFF, (zfile.total_in>>16)&0xFF, (zfile.total_in>>24)&0xFF }; file->write(trailer, sizeof(trailer)); } void stopwriting() { if(!writing) return; deflateEnd(&zfile); writing = false; } void close() { if(reading) finishreading(); stopreading(); if(writing) finishwriting(); stopwriting(); DELETEA(buf); if(autoclose) DELETEP(file); } bool end() { return !reading && !writing; } offset tell() { return reading ? zfile.total_out : (writing ? zfile.total_in : -1); } bool seek(offset pos, int whence) { if(writing || !reading) return false; if(whence == SEEK_END) { uchar skip[512]; while(read(skip, sizeof(skip)) == sizeof(skip)); return !pos; } else if(whence == SEEK_CUR) pos += zfile.total_out; if(pos >= (offset)zfile.total_out) pos -= zfile.total_out; else if(pos < 0 || !file->seek(headersize, SEEK_SET)) return false; else { if(zfile.next_in && zfile.total_in <= uint(zfile.next_in - buf)) { zfile.avail_in += zfile.total_in; zfile.next_in -= zfile.total_in; } else { zfile.avail_in = 0; zfile.next_in = NULL; } inflateReset(&zfile); crc = crc32(0, NULL, 0); } uchar skip[512]; while(pos > 0) { int skipped = (int)min(pos, (offset)sizeof(skip)); if(read(skip, skipped) != skipped) { stopreading(); return false; } pos -= skipped; } return true; } int read(void *buf, int len) { if(!reading || !buf || !len) return 0; zfile.next_out = (Bytef *)buf; zfile.avail_out = len; while(zfile.avail_out > 0) { if(!zfile.avail_in) { readbuf(BUFSIZE); if(!zfile.avail_in) { stopreading(); break; } } int err = inflate(&zfile, Z_NO_FLUSH); if(err == Z_STREAM_END) { crc = crc32(crc, (Bytef *)buf, len - zfile.avail_out); finishreading(); stopreading(); return len - zfile.avail_out; } else if(err != Z_OK) { stopreading(); break; } } crc = crc32(crc, (Bytef *)buf, len - zfile.avail_out); return len - zfile.avail_out; } bool flush() { if(zfile.next_out && zfile.avail_out < BUFSIZE) { if(file->write(buf, BUFSIZE - zfile.avail_out) != int(BUFSIZE - zfile.avail_out)) return false; } zfile.next_out = buf; zfile.avail_out = BUFSIZE; return true; } int write(const void *buf, int len) { if(!writing || !buf || !len) return 0; zfile.next_in = (Bytef *)buf; zfile.avail_in = len; while(zfile.avail_in > 0) { if(!zfile.avail_out && !flush()) { stopwriting(); break; } int err = deflate(&zfile, Z_NO_FLUSH); if(err != Z_OK) { stopwriting(); break; } } crc = crc32(crc, (Bytef *)buf, len - zfile.avail_in); return len - zfile.avail_in; } }; struct utf8stream : stream { enum { BUFSIZE = 4096 }; stream *file; offset pos; int bufread, bufcarry, buflen; bool reading, writing, autoclose; uchar buf[4096]; utf8stream() : file(NULL), pos(0), bufread(0), bufcarry(0), buflen(0), reading(false), writing(false), autoclose(false) { } ~utf8stream() { close(); } bool readbuf(int size = BUFSIZE) { if(bufread >= bufcarry) { if(bufcarry > 0 && bufcarry < buflen) memmove(buf, &buf[bufcarry], buflen - bufcarry); buflen -= bufcarry; bufread = bufcarry = 0; } int n = file->read(&buf[buflen], min(size, BUFSIZE - buflen)); if(n <= 0) return false; buflen += n; int carry = bufcarry; bufcarry += decodeutf8(&buf[bufcarry], &buf[bufcarry], buflen-bufcarry, &carry); if(carry > bufcarry && carry < buflen) { memmove(&buf[bufcarry], &buf[carry], buflen - carry); buflen -= carry - bufcarry; } return true; } bool checkheader() { int n = file->read(buf, 3); if(n == 3 && buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF) return true; buflen = n; return false; } bool open(stream *f, const char *mode, bool needclose) { if(file) return false; for(; *mode; mode++) { if(*mode=='r') { reading = true; break; } else if(*mode=='w') { writing = true; break; } } if(!reading && !writing) return false; autoclose = needclose; file = f; return true; } void finishreading() { if(!reading) return; } void stopreading() { if(!reading) return; reading = false; } void stopwriting() { if(!writing) return; writing = false; } void close() { stopreading(); stopwriting(); if(autoclose) DELETEP(file); } bool end() { return !reading && !writing; } offset tell() { return reading || writing ? pos : -1; } bool seek(offset off, int whence) { if(writing || !reading) return false; if(whence == SEEK_END) { uchar skip[512]; while(read(skip, sizeof(skip)) == sizeof(skip)); return !off; } else if(whence == SEEK_CUR) off += pos; if(off >= pos) off -= pos; else if(off < 0 || !file->seek(0, SEEK_SET)) return false; else { bufread = bufcarry = buflen = 0; pos = 0; checkheader(); } uchar skip[512]; while(off > 0) { int skipped = (int)min(off, (offset)sizeof(skip)); if(read(skip, skipped) != skipped) { stopreading(); return false; } off -= skipped; } return true; } int read(void *dst, int len) { if(!reading || !dst || !len) return 0; int next = 0; while(next < len) { if(bufread >= bufcarry) { if(readbuf(BUFSIZE)) continue; stopreading(); break; } int n = min(len - next, bufcarry - bufread); memcpy(&((uchar *)dst)[next], &buf[bufread], n); next += n; bufread += n; } pos += next; return next; } bool getline(char *dst, int len) { if(!reading || !dst || !len) return false; --len; int next = 0; while(next < len) { if(bufread >= bufcarry) { if(readbuf(BUFSIZE)) continue; stopreading(); if(!next) return false; break; } int n = min(len - next, bufcarry - bufread); uchar *endline = (uchar *)memchr(&buf[bufread], '\n', n); if(endline) { n = endline+1 - &buf[bufread]; len = next + n; } memcpy(&((uchar *)dst)[next], &buf[bufread], n); next += n; bufread += n; } dst[next] = '\0'; pos += next; return true; } int write(const void *src, int len) { if(!writing || !src || !len) return 0; uchar dst[512]; int next = 0; while(next < len) { int carry = 0, n = encodeutf8(dst, sizeof(dst), &((uchar *)src)[next], len - next, &carry); if(n > 0 && file->write(dst, n) != n) { stopwriting(); break; } next += carry; } pos += next; return next; } }; stream *openrawfile(const char *filename, const char *mode) { const char *found = findfile(filename, mode); if(!found) return NULL; filestream *file = new filestream; if(!file->open(found, mode)) { delete file; return NULL; } return file; } stream *openfile(const char *filename, const char *mode) { #ifndef STANDALONE stream *s = openzipfile(filename, mode); if(s) return s; #endif return openrawfile(filename, mode); } stream *opentempfile(const char *name, const char *mode) { const char *found = findfile(name, mode); filestream *file = new filestream; if(!file->opentemp(found ? found : name, mode)) { delete file; return NULL; } return file; } stream *opengzfile(const char *filename, const char *mode, stream *file, int level) { stream *source = file ? file : openfile(filename, mode); if(!source) return NULL; gzstream *gz = new gzstream; if(!gz->open(source, mode, !file, level)) { if(!file) delete source; return NULL; } return gz; } stream *openutf8file(const char *filename, const char *mode, stream *file) { stream *source = file ? file : openfile(filename, mode); if(!source) return NULL; utf8stream *utf8 = new utf8stream; if(!utf8->open(source, mode, !file)) { if(!file) delete source; return NULL; } return utf8; } char *loadfile(const char *fn, int *size, bool utf8) { stream *f = openfile(fn, "rb"); if(!f) return NULL; int len = (int)f->size(); if(len <= 0) { delete f; return NULL; } char *buf = new char[len+1]; if(!buf) { delete f; return NULL; } int offset = 0; if(utf8 && len >= 3) { if(f->read(buf, 3) != 3) { delete f; delete[] buf; return NULL; } if(((uchar *)buf)[0] == 0xEF && ((uchar *)buf)[1] == 0xBB && ((uchar *)buf)[2] == 0xBF) len -= 3; else offset += 3; } int rlen = f->read(&buf[offset], len-offset); delete f; if(rlen != len-offset) { delete[] buf; return NULL; } if(utf8) len = decodeutf8((uchar *)buf, (uchar *)buf, len); buf[len] = '\0'; if(size!=NULL) *size = len; return buf; } sandboxgamemaker-2.7.1+dfsg/src/shared/ents.h0000664000175000017500000001666711655776736021100 0ustar showardshoward// this file defines static map entities ("entity") and dynamic entities (players/monsters, "dynent") // the gamecode extends these types to add game specific functionality // ET_*: the only static entity types dictated by the engine... rest are gamecode dependent enum { ET_EMPTY=0, ET_LIGHT, ET_MAPMODEL, ET_PLAYERSTART, ET_ENVMAP, ET_PARTICLES, ET_SOUND, ET_SPOTLIGHT, ET_GAMESPECIFIC }; struct entity // persistent map entity { vec o; // position vector attr; // attributes uchar type; // type is one of the above }; struct entitylight { vec color, dir; int millis; entitylight() : color(1, 1, 1), dir(0, 0, 1), millis(-1) {} }; struct extentity : entity // part of the entity that doesn't get saved to disk { enum { F_NOVIS = 1<<0, F_NOSHADOW = 1<<1, F_NOCOLLIDE = 1<<2, F_ANIM = 1<<3 }; uchar spawned, inoctanode, visible, flags; // the only dynamic state of a map entity entitylight light; extentity *attached; extentity() : visible(false), flags(0), attached(NULL) {} }; #define MAXENTS 10000 //extern vector ents; // map entities enum { CS_ALIVE = 0, CS_DEAD, CS_SPAWNING, CS_LAGGED, CS_EDITING, CS_SPECTATOR }; enum { PHYS_FLOAT = 0, PHYS_FALL, PHYS_SLIDE, PHYS_SLOPE, PHYS_FLOOR, PHYS_STEP_UP, PHYS_STEP_DOWN, PHYS_BOUNCE }; enum { ENT_PLAYER = 0, ENT_AI, ENT_INANIMATE, ENT_CAMERA, ENT_BOUNCE }; enum { COLLIDE_AABB = 0, COLLIDE_OBB, COLLIDE_ELLIPSE }; struct physent // base entity type, can be affected by physics { vec o, vel, falling; // origin, velocity vec deltapos, newpos; // movement interpolation float yaw, pitch, roll; float maxspeed, jumpvel; // cubes per second, 100 for player int timeinair; float radius, eyeheight, aboveeye; // bounding box size float xradius, yradius, zmargin; vec floor; // the normal of floor the dynent is on int inwater; bool jumping, flying; char move, strafe, altitude; uchar physstate; // one of PHYS_* above uchar state, editstate; // one of CS_* above uchar type; // one of ENT_* above uchar collidetype; // one of COLLIDE_* above bool blocked; // used by physics to signal ai int lastjump; physent() : o(0, 0, 0), deltapos(0, 0, 0), newpos(0, 0, 0), yaw(0), pitch(0), roll(0), maxspeed(100), jumpvel(200.0f), radius(4.1f), eyeheight(14), aboveeye(1), xradius(4.1f), yradius(4.1f), zmargin(0), state(CS_ALIVE), editstate(CS_ALIVE), type(ENT_PLAYER), collidetype(COLLIDE_ELLIPSE), blocked(false), lastjump(0) { reset(); } void resetinterp() { newpos = o; deltapos = vec(0, 0, 0); } void reset() { inwater = 0; timeinair = 0; strafe = move = altitude = 0; physstate = PHYS_FALL; vel = falling = vec(0, 0, 0); floor = vec(0, 0, 1); } vec feetpos(float offset = 0) const { return vec(o).add(vec(0, 0, offset - eyeheight)); } vec headpos(float offset = 0) const { return vec(o).add(vec(0, 0, offset)); } bool maymove() const { return timeinair || physstate < PHYS_FLOOR || vel.squaredlen() > 1e-4f || deltapos.squaredlen() > 1e-4f; } }; enum { ANIM_DEAD = 0, ANIM_DYING, ANIM_IDLE, ANIM_FORWARD, ANIM_BACKWARD, ANIM_LEFT, ANIM_RIGHT, ANIM_HOLD1, ANIM_HOLD2, ANIM_HOLD3, ANIM_HOLD4, ANIM_HOLD5, ANIM_HOLD6, ANIM_HOLD7, ANIM_ATTACK1, ANIM_ATTACK2, ANIM_ATTACK3, ANIM_ATTACK4, ANIM_ATTACK5, ANIM_ATTACK6, ANIM_ATTACK7, ANIM_PAIN, ANIM_JUMP, ANIM_SINK, ANIM_SWIM, ANIM_EDIT, ANIM_LAG, ANIM_TAUNT, ANIM_WIN, ANIM_LOSE, ANIM_GUN_IDLE, ANIM_GUN_SHOOT, ANIM_VWEP_IDLE, ANIM_VWEP_SHOOT, ANIM_SHIELD, ANIM_POWERUP, ANIM_MAPMODEL, ANIM_TRIGGER, NUMANIMS }; static const char * const animnames[] = { "dead", "dying", "idle", "forward", "backward", "left", "right", "hold 1", "hold 2", "hold 3", "hold 4", "hold 5", "hold 6", "hold 7", "attack 1", "attack 2", "attack 3", "attack 4", "attack 5", "attack 6", "attack 7", "pain", "jump", "sink", "swim", "edit", "lag", "taunt", "win", "lose", "gun idle", "gun shoot", "vwep idle", "vwep shoot", "shield", "powerup", "mapmodel", "trigger" }; #define ANIM_ALL 0x7F #define ANIM_INDEX 0x7F #define ANIM_LOOP (1<<7) #define ANIM_START (1<<8) #define ANIM_END (1<<9) #define ANIM_REVERSE (1<<10) #define ANIM_CLAMP (ANIM_START|ANIM_END) #define ANIM_DIR 0x780 #define ANIM_SECONDARY 11 #define ANIM_NOSKIN (1<<22) #define ANIM_SETTIME (1<<23) #define ANIM_FULLBRIGHT (1<<24) #define ANIM_REUSE (1<<25) #define ANIM_NORENDER (1<<26) #define ANIM_RAGDOLL (1<<27) #define ANIM_SETSPEED (1<<28) #define ANIM_NOPITCH (1<<29) #define ANIM_GHOST (1<<30) #define ANIM_FLAGS (0x1FF<<22) struct animinfo // description of a character's animation { int anim, frame, range, basetime; float speed; uint varseed; animinfo() : anim(0), frame(0), range(0), basetime(0), speed(100.0f), varseed(0) { } bool operator==(const animinfo &o) const { return frame==o.frame && range==o.range && (anim&(ANIM_SETTIME|ANIM_DIR))==(o.anim&(ANIM_SETTIME|ANIM_DIR)) && (anim&ANIM_SETTIME || basetime==o.basetime) && speed==o.speed; } bool operator!=(const animinfo &o) const { return frame!=o.frame || range!=o.range || (anim&(ANIM_SETTIME|ANIM_DIR))!=(o.anim&(ANIM_SETTIME|ANIM_DIR)) || (!(anim&ANIM_SETTIME) && basetime!=o.basetime) || speed!=o.speed; } }; struct animinterpinfo // used for animation blending of animated characters { animinfo prev, cur; int lastswitch; void *lastmodel; animinterpinfo() : lastswitch(-1), lastmodel(NULL) {} }; #define MAXANIMPARTS 3 struct occludequery; struct ragdolldata; struct dynent : physent // animated characters, or characters that can receive input { bool k_left, k_right, k_up, k_down; // see input code bool k_rise, k_des; //direct up/down, movement entitylight light; animinterpinfo animinterp[MAXANIMPARTS]; ragdolldata *ragdoll; occludequery *query; int occluded, lastrendered; //__tha__ gestures // bool animate; // int animation; dynent() : ragdoll(NULL), query(NULL), occluded(0), lastrendered(0) { reset(); } ~dynent() { #ifndef STANDALONE extern void cleanragdoll(dynent *d); if(ragdoll) cleanragdoll(this); #endif } void stopmoving() { k_left = k_right = k_up = k_down = k_des = k_rise = jumping = false; move = strafe = altitude = 0; } void reset() { physent::reset(); stopmoving(); // animate = false; // animation = -1; } vec abovehead() { return vec(o).add(vec(0, 0, aboveeye+4)); } }; extern int efocus, enthover, entorient; sandboxgamemaker-2.7.1+dfsg/src/shared/command.h0000664000175000017500000003347211544613354021515 0ustar showardshoward// script binding functionality enum { VAL_NULL = 0, VAL_INT, VAL_FLOAT, VAL_STR, VAL_ANY, VAL_CODE, VAL_MACRO, VAL_IDENT }; enum { CODE_NOP = 0, CODE_POP, CODE_ENTER, CODE_EXIT, CODE_VAL, CODE_VALI, CODE_MACRO, CODE_BOOL, CODE_BLOCK, CODE_COMPILE, CODE_FORCE, CODE_RESULT, CODE_IDENT, CODE_IDENTU, CODE_COM, CODE_COMD, CODE_COMC, CODE_COMV, CODE_CONC, CODE_CONCW, CODE_CONCM, CODE_DOWN, CODE_SVAR, CODE_SVAR1, CODE_IVAR, CODE_IVAR1, CODE_IVAR2, CODE_IVAR3, CODE_FVAR, CODE_FVAR1, CODE_LOOKUP, CODE_LOOKUPU, CODE_ALIAS, CODE_ALIASU, CODE_CALL, CODE_CALLU, CODE_PRINT, CODE_OP_MASK = 0x3F, CODE_RET = 6, CODE_RET_MASK = 0xC0, /* return type flags */ RET_NULL = VAL_NULL< x ? IDF_READONLY : 0)) { storage.i = s; } // ID_FVAR ident(int t, const char *n, float m, float x, float *s, void *f = NULL, int flags = 0) : type(t), name(n), minvalf(m), maxvalf(x), fun((identfun)f), flags(flags | (m > x ? IDF_READONLY : 0)) { storage.f = s; } // ID_SVAR ident(int t, const char *n, char **s, void *f = NULL, int flags = 0) : type(t), name(n), fun((identfun)f), flags(flags) { storage.s = s; } // ID_ALIAS ident(int t, const char *n, char *a, int flags) : type(t), name(n), valtype(VAL_STR), code(NULL), stack(NULL), flags(flags) { val.s = a; } ident(int t, const char *n, int a, int flags) : type(t), name(n), valtype(VAL_INT), code(NULL), stack(NULL), flags(flags) { val.i = a; } ident(int t, const char *n, float a, int flags) : type(t), name(n), valtype(VAL_FLOAT), code(NULL), stack(NULL), flags(flags) { val.f = a; } ident(int t, const char *n, int flags) : type(t), name(n), valtype(VAL_NULL), code(NULL), stack(NULL), flags(flags) {} ident(int t, const char *n, const tagval &v, int flags) : type(t), name(n), valtype(v.type), code(NULL), stack(NULL), flags(flags) { val = v; } // ID_COMMAND ident(int t, const char *n, const char *args, uint argmask, void *f = NULL, int flags = 0) : type(t), name(n), args(args), argmask(argmask), fun((identfun)f), flags(flags) {} void changed() { if(fun) fun(); } void setval(const tagval &v) { valtype = v.type; val = v; } void setval(const identstack &v) { valtype = v.valtype; val = v.val; } void nullval() { if(valtype==VAL_STR) delete[] val.s; valtype = VAL_NULL; } float getfloat() const; int getint() const; const char *getstr() const; void getval(tagval &v) const; }; static inline bool htcmp(const char *key, const ident &id) { return !strcmp(key, id.name); } extern void addident(ident *id); extern const char *intstr(int v); extern void intret(int v); extern const char *floatstr(float v); extern void floatret(float v); extern void result(tagval &v); extern void result(const char *s); static inline int parseint(const char *s) { return int(strtol(s, NULL, 0)); } static inline float parsefloat(const char *s) { // not all platforms (windows) can parse hexadecimal integers via strtod char *end; double val = strtod(s, &end); return val || end==s || (*end!='x' && *end!='X') ? float(val) : float(parseint(s)); } static inline const char *getstr(const identval &v, int type) { switch(type) { case VAL_STR: case VAL_MACRO: return v.s; case VAL_INT: return intstr(v.i); case VAL_FLOAT: return floatstr(v.f); default: return ""; } } inline const char *tagval::getstr() const { return ::getstr(*this, type); } inline const char *ident::getstr() const { return ::getstr(val, valtype); } static inline int getint(const identval &v, int type) { switch(type) { case VAL_INT: return v.i; case VAL_FLOAT: return int(v.f); case VAL_STR: case VAL_MACRO: return parseint(v.s); default: return 0; } } inline int tagval::getint() const { return ::getint(*this, type); } inline int ident::getint() const { return ::getint(val, valtype); } static inline float getfloat(const identval &v, int type) { switch(type) { case VAL_FLOAT: return v.f; case VAL_INT: return float(v.i); case VAL_STR: case VAL_MACRO: return parsefloat(v.s); default: return 0.0f; } } inline float tagval::getfloat() const { return ::getfloat(*this, type); } inline float ident::getfloat() const { return ::getfloat(val, valtype); } inline void ident::getval(tagval &v) const { switch(valtype) { case VAL_STR: case VAL_MACRO: v.setstr(newstring(val.s)); break; case VAL_INT: v.setint(val.i); break; case VAL_FLOAT: v.setfloat(val.f); break; default: v.setnull(); break; } } // nasty macros for registering script functions, abuses globals to avoid excessive infrastructure #define COMMANDN(name, fun, nargs) static bool __dummy_##fun = addcommand(#name, (identfun)fun, nargs) #define COMMAND(name, nargs) COMMANDN(name, name, nargs) #define _VAR(name, global, min, cur, max, persist) int global = variable(#name, min, cur, max, &global, NULL, persist) #define VARN(name, global, min, cur, max) _VAR(name, global, min, cur, max, 0) #define VARNP(name, global, min, cur, max) _VAR(name, global, min, cur, max, IDF_PERSIST) #define VARNR(name, global, min, cur, max) _VAR(name, global, min, cur, max, IDF_OVERRIDE) #define VAR(name, min, cur, max) _VAR(name, name, min, cur, max, 0) #define VARP(name, min, cur, max) _VAR(name, name, min, cur, max, IDF_PERSIST) #define VARR(name, min, cur, max) _VAR(name, name, min, cur, max, IDF_OVERRIDE) #define _VARF(name, global, min, cur, max, body, persist) void var_##name(); int global = variable(#name, min, cur, max, &global, var_##name, persist); void var_##name() { body; } #define VARFN(name, global, min, cur, max, body) _VARF(name, global, min, cur, max, body, 0) #define VARF(name, min, cur, max, body) _VARF(name, name, min, cur, max, body, 0) #define VARFP(name, min, cur, max, body) _VARF(name, name, min, cur, max, body, IDF_PERSIST) #define VARFR(name, min, cur, max, body) _VARF(name, name, min, cur, max, body, IDF_OVERRIDE) #define VARFW(name, min, cur, max, body) _VARF(name, name, min, cur, max, body, IDF_OVERRIDE|IDF_WORLD) #define _HVAR(name, global, min, cur, max, persist) int global = variable(#name, min, cur, max, &global, NULL, persist | IDF_HEX) #define HVARN(name, global, min, cur, max) _HVAR(name, global, min, cur, max, 0) #define HVARNP(name, global, min, cur, max) _HVAR(name, global, min, cur, max, IDF_PERSIST) #define HVARNR(name, global, min, cur, max) _HVAR(name, global, min, cur, max, IDF_OVERRIDE) #define HVAR(name, min, cur, max) _HVAR(name, name, min, cur, max, 0) #define HVARP(name, min, cur, max) _HVAR(name, name, min, cur, max, IDF_PERSIST) #define HVARR(name, min, cur, max) _HVAR(name, name, min, cur, max, IDF_OVERRIDE) #define _HVARF(name, global, min, cur, max, body, persist) void var_##name(); int global = variable(#name, min, cur, max, &global, var_##name, persist | IDF_HEX); void var_##name() { body; } #define HVARFN(name, global, min, cur, max, body) _HVARF(name, global, min, cur, max, body, 0) #define HVARF(name, min, cur, max, body) _HVARF(name, name, min, cur, max, body, 0) #define HVARFP(name, min, cur, max, body) _HVARF(name, name, min, cur, max, body, IDF_PERSIST) #define HVARFR(name, min, cur, max, body) _HVARF(name, name, min, cur, max, body, IDF_OVERRIDE) #define _FVAR(name, global, min, cur, max, persist) float global = fvariable(#name, min, cur, max, &global, NULL, persist) #define FVARN(name, global, min, cur, max) _FVAR(name, global, min, cur, max, 0) #define FVARNP(name, global, min, cur, max) _FVAR(name, global, min, cur, max, IDF_PERSIST) #define FVARNR(name, global, min, cur, max) _FVAR(name, global, min, cur, max, IDF_OVERRIDE) #define FVAR(name, min, cur, max) _FVAR(name, name, min, cur, max, 0) #define FVARP(name, min, cur, max) _FVAR(name, name, min, cur, max, IDF_PERSIST) #define FVARR(name, min, cur, max) _FVAR(name, name, min, cur, max, IDF_OVERRIDE) #define _FVARF(name, global, min, cur, max, body, persist) void var_##name(); float global = fvariable(#name, min, cur, max, &global, var_##name, persist); void var_##name() { body; } #define FVARFN(name, global, min, cur, max, body) _FVARF(name, global, min, cur, max, body, 0) #define FVARF(name, min, cur, max, body) _FVARF(name, name, min, cur, max, body, 0) #define FVARFP(name, min, cur, max, body) _FVARF(name, name, min, cur, max, body, IDF_PERSIST) #define FVARFR(name, min, cur, max, body) _FVARF(name, name, min, cur, max, body, IDF_OVERRIDE) #define _SVAR(name, global, cur, persist) char *global = svariable(#name, cur, &global, NULL, persist) #define SVARN(name, global, cur) _SVAR(name, global, cur, 0) #define SVARNP(name, global, cur) _SVAR(name, global, cur, IDF_PERSIST) #define SVARNR(name, global, cur) _SVAR(name, global, cur, IDF_OVERRIDE) #define SVAR(name, cur) _SVAR(name, name, cur, 0) #define SVARO(name, cur) _SVAR(name, name, cur, IDF_READONLY) #define SVARP(name, cur) _SVAR(name, name, cur, IDF_PERSIST) #define SVARR(name, cur) _SVAR(name, name, cur, IDF_OVERRIDE) #define _SVARF(name, global, cur, body, persist) void var_##name(); char *global = svariable(#name, cur, &global, var_##name, persist); void var_##name() { body; } #define SVARFN(name, global, cur, body) _SVARF(name, global, cur, body, 0) #define SVARF(name, cur, body) _SVARF(name, name, cur, body, 0) #define SVARFP(name, cur, body) _SVARF(name, name, cur, body, IDF_PERSIST) #define SVARFR(name, cur, body) _SVARF(name, name, cur, body, IDF_OVERRIDE) // anonymous inline commands, uses nasty template trick with line numbers to keep names unique #define _ICOMMAND(cmdname, name, nargs, proto, b) template struct cmdname; template<> struct cmdname<__LINE__> { static bool init; static void run proto; }; bool cmdname<__LINE__>::init = addcommand(name, (identfun)cmdname<__LINE__>::run, nargs); void cmdname<__LINE__>::run proto \ { b; } #define ICOMMANDNAME(name) _icmd_##name #define ICOMMAND(name, nargs, proto, b) _ICOMMAND(ICOMMANDNAME(name), #name, nargs, proto, b) #define ICOMMANDSNAME _icmds_ #define ICOMMANDS(name, nargs, proto, b) _ICOMMAND(ICOMMANDSNAME, name, nargs, proto, b) #define _IFVAR(n, m, c, x, b, p) \ struct var_##n : ident \ { \ var_##n() : ident(ID_FVAR, #n, m, c, x, &val.f, NULL, p) \ { \ addident(name, this); \ } \ float operator()() { return val.f; } \ b \ } n #define IVAR(n, m, c, x) _IVAR(n, m, c, x, , 0) #define IVARF(n, m, c, x, b) _IVAR(n, m, c, x, void changed() { b; }, 0,) #define IVARP(n, m, c, x) _IVAR(n, m, c, x, , IDF_PERSIST) #define IVARR(n, m, c, x) _IVAR(n, m, c, x, , IDF_OVERRIDE) #define IVARFP(n, m, c, x, b) _IVAR(n, m, c, x, void changed() { b; }, IDF_PERSIST) #define IVARFR(n, m, c, x, b) _IVAR(n, m, c, x, void changed() { b; }, IDF_OVERRIDE) #define IFVAR(n, m, c, x) _IFVAR(n, m, c, x, , 0) #define IFVARF(n, m, c, x, b) _IFVAR(n, m, c, x, void changed() { b; }, 0) #define IFVARP(n, m, c, x) _IFVAR(n, m, c, x, , IDF_PERSIST) #define IFVARR(n, m, c, x) _IFVAR(n, m, c, x, , IDF_OVERRIDE) #define IFVARFP(n, m, c, x, b) _IFVAR(n, m, c, x, void changed() { b; }, IDF_PERSIST) #define IFVARFR(n, m, c, x, b) _IFVAR(n, m, c, x, void changed() { b; }, IDF_OVERRIDE) sandboxgamemaker-2.7.1+dfsg/src/shared/geom.cpp0000664000175000017500000006774011642642476021374 0ustar showardshoward #include "cube.h" static inline float det2x2(float a, float b, float c, float d) { return a*d - b*c; } static inline float det3x3(float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3) { return a1 * det2x2(b2, b3, c2, c3) - b1 * det2x2(a2, a3, c2, c3) + c1 * det2x2(a2, a3, b2, b3); } float glmatrixf::determinant() const { float a1 = v[0], a2 = v[1], a3 = v[2], a4 = v[3], b1 = v[4], b2 = v[5], b3 = v[6], b4 = v[7], c1 = v[8], c2 = v[9], c3 = v[10], c4 = v[11], d1 = v[12], d2 = v[13], d3 = v[14], d4 = v[15]; return a1 * det3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4) - b1 * det3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4) + c1 * det3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4) - d1 * det3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4); } void glmatrixf::adjoint(const glmatrixf &m) { float a1 = m.v[0], a2 = m.v[1], a3 = m.v[2], a4 = m.v[3], b1 = m.v[4], b2 = m.v[5], b3 = m.v[6], b4 = m.v[7], c1 = m.v[8], c2 = m.v[9], c3 = m.v[10], c4 = m.v[11], d1 = m.v[12], d2 = m.v[13], d3 = m.v[14], d4 = m.v[15]; v[0] = det3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4); v[1] = -det3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4); v[2] = det3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4); v[3] = -det3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4); v[4] = -det3x3(b1, b3, b4, c1, c3, c4, d1, d3, d4); v[5] = det3x3(a1, a3, a4, c1, c3, c4, d1, d3, d4); v[6] = -det3x3(a1, a3, a4, b1, b3, b4, d1, d3, d4); v[7] = det3x3(a1, a3, a4, b1, b3, b4, c1, c3, c4); v[8] = det3x3(b1, b2, b4, c1, c2, c4, d1, d2, d4); v[9] = -det3x3(a1, a2, a4, c1, c2, c4, d1, d2, d4); v[10] = det3x3(a1, a2, a4, b1, b2, b4, d1, d2, d4); v[11] = -det3x3(a1, a2, a4, b1, b2, b4, c1, c2, c4); v[12] = -det3x3(b1, b2, b3, c1, c2, c3, d1, d2, d3); v[13] = det3x3(a1, a2, a3, c1, c2, c3, d1, d2, d3); v[14] = -det3x3(a1, a2, a3, b1, b2, b3, d1, d2, d3); v[15] = det3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3); } bool glmatrixf::invert(const glmatrixf &m, float mindet) { float a1 = m.v[0], b1 = m.v[4], c1 = m.v[8], d1 = m.v[12]; adjoint(m); float det = a1*v[0] + b1*v[1] + c1*v[2] + d1*v[3]; // float det = m.determinant(); if(fabs(det) < mindet) return false; float invdet = 1/det; loopi(16) v[i] *= invdet; return true; } bool raysphereintersect(const vec ¢er, float radius, const vec &o, const vec &ray, float &dist) { vec c(center); c.sub(o); float v = c.dot(ray), inside = radius*radius - c.squaredlen(); if(inside<0 && v<0) return false; float d = inside + v*v; if(d<0) return false; dist = v - sqrt(d); return true; } bool rayrectintersect(const vec &b, const vec &s, const vec &o, const vec &ray, float &dist, int &orient) { loop(d, 3) if(ray[d]) { int dc = ray[d]<0 ? 1 : 0; float pdist = (b[d]+s[d]*dc - o[d]) / ray[d]; vec v(ray); v.mul(pdist).add(o); if(v[R[d]] >= b[R[d]] && v[R[d]] <= b[R[d]]+s[R[d]] && v[C[d]] >= b[C[d]] && v[C[d]] <= b[C[d]]+s[C[d]]) { dist = pdist; orient = 2*d+dc; return true; } } return false; } bool linecylinderintersect(const vec &from, const vec &to, const vec &start, const vec &end, float radius, float &dist) { vec d(end), m(from), n(to); d.sub(start); m.sub(start); n.sub(from); float md = m.dot(d), nd = n.dot(d), dd = d.squaredlen(); if(md < 0 && md + nd < 0) return false; if(md > dd && md + nd > dd) return false; float nn = n.squaredlen(), mn = m.dot(n), a = dd*nn - nd*nd, k = m.squaredlen() - radius*radius, c = dd*k - md*md; if(fabs(a) < 0.005f) { if(c > 0) return false; if(md < 0) dist = -mn / nn; else if(md > dd) dist = (nd - mn) / nn; else dist = 0; return true; } else if(c > 0) { float b = dd*mn - nd*md, discrim = b*b - a*c; if(discrim < 0) return false; dist = (-b - sqrtf(discrim)) / a; } else dist = 0; float offset = md + dist*nd; if(offset < 0) { if(nd <= 0) return false; dist = -md / nd; if(k + dist*(2*mn + dist*nn) > 0) return false; } else if(offset > dd) { if(nd >= 0) return false; dist = (dd - md) / nd; if(k + dd - 2*md + dist*(2*(mn-nd) + dist*nn) > 0) return false; } return dist >= 0 && dist <= 1; } extern const vec2 sincos360[721] = { vec2(1.00000000, 0.00000000), vec2(0.99984770, 0.01745241), vec2(0.99939083, 0.03489950), vec2(0.99862953, 0.05233596), vec2(0.99756405, 0.06975647), vec2(0.99619470, 0.08715574), // 0 vec2(0.99452190, 0.10452846), vec2(0.99254615, 0.12186934), vec2(0.99026807, 0.13917310), vec2(0.98768834, 0.15643447), vec2(0.98480775, 0.17364818), vec2(0.98162718, 0.19080900), // 6 vec2(0.97814760, 0.20791169), vec2(0.97437006, 0.22495105), vec2(0.97029573, 0.24192190), vec2(0.96592583, 0.25881905), vec2(0.96126170, 0.27563736), vec2(0.95630476, 0.29237170), // 12 vec2(0.95105652, 0.30901699), vec2(0.94551858, 0.32556815), vec2(0.93969262, 0.34202014), vec2(0.93358043, 0.35836795), vec2(0.92718385, 0.37460659), vec2(0.92050485, 0.39073113), // 18 vec2(0.91354546, 0.40673664), vec2(0.90630779, 0.42261826), vec2(0.89879405, 0.43837115), vec2(0.89100652, 0.45399050), vec2(0.88294759, 0.46947156), vec2(0.87461971, 0.48480962), // 24 vec2(0.86602540, 0.50000000), vec2(0.85716730, 0.51503807), vec2(0.84804810, 0.52991926), vec2(0.83867057, 0.54463904), vec2(0.82903757, 0.55919290), vec2(0.81915204, 0.57357644), // 30 vec2(0.80901699, 0.58778525), vec2(0.79863551, 0.60181502), vec2(0.78801075, 0.61566148), vec2(0.77714596, 0.62932039), vec2(0.76604444, 0.64278761), vec2(0.75470958, 0.65605903), // 36 vec2(0.74314483, 0.66913061), vec2(0.73135370, 0.68199836), vec2(0.71933980, 0.69465837), vec2(0.70710678, 0.70710678), vec2(0.69465837, 0.71933980), vec2(0.68199836, 0.73135370), // 42 vec2(0.66913061, 0.74314483), vec2(0.65605903, 0.75470958), vec2(0.64278761, 0.76604444), vec2(0.62932039, 0.77714596), vec2(0.61566148, 0.78801075), vec2(0.60181502, 0.79863551), // 48 vec2(0.58778525, 0.80901699), vec2(0.57357644, 0.81915204), vec2(0.55919290, 0.82903757), vec2(0.54463904, 0.83867057), vec2(0.52991926, 0.84804810), vec2(0.51503807, 0.85716730), // 54 vec2(0.50000000, 0.86602540), vec2(0.48480962, 0.87461971), vec2(0.46947156, 0.88294759), vec2(0.45399050, 0.89100652), vec2(0.43837115, 0.89879405), vec2(0.42261826, 0.90630779), // 60 vec2(0.40673664, 0.91354546), vec2(0.39073113, 0.92050485), vec2(0.37460659, 0.92718385), vec2(0.35836795, 0.93358043), vec2(0.34202014, 0.93969262), vec2(0.32556815, 0.94551858), // 66 vec2(0.30901699, 0.95105652), vec2(0.29237170, 0.95630476), vec2(0.27563736, 0.96126170), vec2(0.25881905, 0.96592583), vec2(0.24192190, 0.97029573), vec2(0.22495105, 0.97437006), // 72 vec2(0.20791169, 0.97814760), vec2(0.19080900, 0.98162718), vec2(0.17364818, 0.98480775), vec2(0.15643447, 0.98768834), vec2(0.13917310, 0.99026807), vec2(0.12186934, 0.99254615), // 78 vec2(0.10452846, 0.99452190), vec2(0.08715574, 0.99619470), vec2(0.06975647, 0.99756405), vec2(0.05233596, 0.99862953), vec2(0.03489950, 0.99939083), vec2(0.01745241, 0.99984770), // 84 vec2(0.00000000, 1.00000000), vec2(-0.01745241, 0.99984770), vec2(-0.03489950, 0.99939083), vec2(-0.05233596, 0.99862953), vec2(-0.06975647, 0.99756405), vec2(-0.08715574, 0.99619470), // 90 vec2(-0.10452846, 0.99452190), vec2(-0.12186934, 0.99254615), vec2(-0.13917310, 0.99026807), vec2(-0.15643447, 0.98768834), vec2(-0.17364818, 0.98480775), vec2(-0.19080900, 0.98162718), // 96 vec2(-0.20791169, 0.97814760), vec2(-0.22495105, 0.97437006), vec2(-0.24192190, 0.97029573), vec2(-0.25881905, 0.96592583), vec2(-0.27563736, 0.96126170), vec2(-0.29237170, 0.95630476), // 102 vec2(-0.30901699, 0.95105652), vec2(-0.32556815, 0.94551858), vec2(-0.34202014, 0.93969262), vec2(-0.35836795, 0.93358043), vec2(-0.37460659, 0.92718385), vec2(-0.39073113, 0.92050485), // 108 vec2(-0.40673664, 0.91354546), vec2(-0.42261826, 0.90630779), vec2(-0.43837115, 0.89879405), vec2(-0.45399050, 0.89100652), vec2(-0.46947156, 0.88294759), vec2(-0.48480962, 0.87461971), // 114 vec2(-0.50000000, 0.86602540), vec2(-0.51503807, 0.85716730), vec2(-0.52991926, 0.84804810), vec2(-0.54463904, 0.83867057), vec2(-0.55919290, 0.82903757), vec2(-0.57357644, 0.81915204), // 120 vec2(-0.58778525, 0.80901699), vec2(-0.60181502, 0.79863551), vec2(-0.61566148, 0.78801075), vec2(-0.62932039, 0.77714596), vec2(-0.64278761, 0.76604444), vec2(-0.65605903, 0.75470958), // 126 vec2(-0.66913061, 0.74314483), vec2(-0.68199836, 0.73135370), vec2(-0.69465837, 0.71933980), vec2(-0.70710678, 0.70710678), vec2(-0.71933980, 0.69465837), vec2(-0.73135370, 0.68199836), // 132 vec2(-0.74314483, 0.66913061), vec2(-0.75470958, 0.65605903), vec2(-0.76604444, 0.64278761), vec2(-0.77714596, 0.62932039), vec2(-0.78801075, 0.61566148), vec2(-0.79863551, 0.60181502), // 138 vec2(-0.80901699, 0.58778525), vec2(-0.81915204, 0.57357644), vec2(-0.82903757, 0.55919290), vec2(-0.83867057, 0.54463904), vec2(-0.84804810, 0.52991926), vec2(-0.85716730, 0.51503807), // 144 vec2(-0.86602540, 0.50000000), vec2(-0.87461971, 0.48480962), vec2(-0.88294759, 0.46947156), vec2(-0.89100652, 0.45399050), vec2(-0.89879405, 0.43837115), vec2(-0.90630779, 0.42261826), // 150 vec2(-0.91354546, 0.40673664), vec2(-0.92050485, 0.39073113), vec2(-0.92718385, 0.37460659), vec2(-0.93358043, 0.35836795), vec2(-0.93969262, 0.34202014), vec2(-0.94551858, 0.32556815), // 156 vec2(-0.95105652, 0.30901699), vec2(-0.95630476, 0.29237170), vec2(-0.96126170, 0.27563736), vec2(-0.96592583, 0.25881905), vec2(-0.97029573, 0.24192190), vec2(-0.97437006, 0.22495105), // 162 vec2(-0.97814760, 0.20791169), vec2(-0.98162718, 0.19080900), vec2(-0.98480775, 0.17364818), vec2(-0.98768834, 0.15643447), vec2(-0.99026807, 0.13917310), vec2(-0.99254615, 0.12186934), // 168 vec2(-0.99452190, 0.10452846), vec2(-0.99619470, 0.08715574), vec2(-0.99756405, 0.06975647), vec2(-0.99862953, 0.05233596), vec2(-0.99939083, 0.03489950), vec2(-0.99984770, 0.01745241), // 174 vec2(-1.00000000, 0.00000000), vec2(-0.99984770, -0.01745241), vec2(-0.99939083, -0.03489950), vec2(-0.99862953, -0.05233596), vec2(-0.99756405, -0.06975647), vec2(-0.99619470, -0.08715574), // 180 vec2(-0.99452190, -0.10452846), vec2(-0.99254615, -0.12186934), vec2(-0.99026807, -0.13917310), vec2(-0.98768834, -0.15643447), vec2(-0.98480775, -0.17364818), vec2(-0.98162718, -0.19080900), // 186 vec2(-0.97814760, -0.20791169), vec2(-0.97437006, -0.22495105), vec2(-0.97029573, -0.24192190), vec2(-0.96592583, -0.25881905), vec2(-0.96126170, -0.27563736), vec2(-0.95630476, -0.29237170), // 192 vec2(-0.95105652, -0.30901699), vec2(-0.94551858, -0.32556815), vec2(-0.93969262, -0.34202014), vec2(-0.93358043, -0.35836795), vec2(-0.92718385, -0.37460659), vec2(-0.92050485, -0.39073113), // 198 vec2(-0.91354546, -0.40673664), vec2(-0.90630779, -0.42261826), vec2(-0.89879405, -0.43837115), vec2(-0.89100652, -0.45399050), vec2(-0.88294759, -0.46947156), vec2(-0.87461971, -0.48480962), // 204 vec2(-0.86602540, -0.50000000), vec2(-0.85716730, -0.51503807), vec2(-0.84804810, -0.52991926), vec2(-0.83867057, -0.54463904), vec2(-0.82903757, -0.55919290), vec2(-0.81915204, -0.57357644), // 210 vec2(-0.80901699, -0.58778525), vec2(-0.79863551, -0.60181502), vec2(-0.78801075, -0.61566148), vec2(-0.77714596, -0.62932039), vec2(-0.76604444, -0.64278761), vec2(-0.75470958, -0.65605903), // 216 vec2(-0.74314483, -0.66913061), vec2(-0.73135370, -0.68199836), vec2(-0.71933980, -0.69465837), vec2(-0.70710678, -0.70710678), vec2(-0.69465837, -0.71933980), vec2(-0.68199836, -0.73135370), // 222 vec2(-0.66913061, -0.74314483), vec2(-0.65605903, -0.75470958), vec2(-0.64278761, -0.76604444), vec2(-0.62932039, -0.77714596), vec2(-0.61566148, -0.78801075), vec2(-0.60181502, -0.79863551), // 228 vec2(-0.58778525, -0.80901699), vec2(-0.57357644, -0.81915204), vec2(-0.55919290, -0.82903757), vec2(-0.54463904, -0.83867057), vec2(-0.52991926, -0.84804810), vec2(-0.51503807, -0.85716730), // 234 vec2(-0.50000000, -0.86602540), vec2(-0.48480962, -0.87461971), vec2(-0.46947156, -0.88294759), vec2(-0.45399050, -0.89100652), vec2(-0.43837115, -0.89879405), vec2(-0.42261826, -0.90630779), // 240 vec2(-0.40673664, -0.91354546), vec2(-0.39073113, -0.92050485), vec2(-0.37460659, -0.92718385), vec2(-0.35836795, -0.93358043), vec2(-0.34202014, -0.93969262), vec2(-0.32556815, -0.94551858), // 246 vec2(-0.30901699, -0.95105652), vec2(-0.29237170, -0.95630476), vec2(-0.27563736, -0.96126170), vec2(-0.25881905, -0.96592583), vec2(-0.24192190, -0.97029573), vec2(-0.22495105, -0.97437006), // 252 vec2(-0.20791169, -0.97814760), vec2(-0.19080900, -0.98162718), vec2(-0.17364818, -0.98480775), vec2(-0.15643447, -0.98768834), vec2(-0.13917310, -0.99026807), vec2(-0.12186934, -0.99254615), // 258 vec2(-0.10452846, -0.99452190), vec2(-0.08715574, -0.99619470), vec2(-0.06975647, -0.99756405), vec2(-0.05233596, -0.99862953), vec2(-0.03489950, -0.99939083), vec2(-0.01745241, -0.99984770), // 264 vec2(-0.00000000, -1.00000000), vec2(0.01745241, -0.99984770), vec2(0.03489950, -0.99939083), vec2(0.05233596, -0.99862953), vec2(0.06975647, -0.99756405), vec2(0.08715574, -0.99619470), // 270 vec2(0.10452846, -0.99452190), vec2(0.12186934, -0.99254615), vec2(0.13917310, -0.99026807), vec2(0.15643447, -0.98768834), vec2(0.17364818, -0.98480775), vec2(0.19080900, -0.98162718), // 276 vec2(0.20791169, -0.97814760), vec2(0.22495105, -0.97437006), vec2(0.24192190, -0.97029573), vec2(0.25881905, -0.96592583), vec2(0.27563736, -0.96126170), vec2(0.29237170, -0.95630476), // 282 vec2(0.30901699, -0.95105652), vec2(0.32556815, -0.94551858), vec2(0.34202014, -0.93969262), vec2(0.35836795, -0.93358043), vec2(0.37460659, -0.92718385), vec2(0.39073113, -0.92050485), // 288 vec2(0.40673664, -0.91354546), vec2(0.42261826, -0.90630779), vec2(0.43837115, -0.89879405), vec2(0.45399050, -0.89100652), vec2(0.46947156, -0.88294759), vec2(0.48480962, -0.87461971), // 294 vec2(0.50000000, -0.86602540), vec2(0.51503807, -0.85716730), vec2(0.52991926, -0.84804810), vec2(0.54463904, -0.83867057), vec2(0.55919290, -0.82903757), vec2(0.57357644, -0.81915204), // 300 vec2(0.58778525, -0.80901699), vec2(0.60181502, -0.79863551), vec2(0.61566148, -0.78801075), vec2(0.62932039, -0.77714596), vec2(0.64278761, -0.76604444), vec2(0.65605903, -0.75470958), // 306 vec2(0.66913061, -0.74314483), vec2(0.68199836, -0.73135370), vec2(0.69465837, -0.71933980), vec2(0.70710678, -0.70710678), vec2(0.71933980, -0.69465837), vec2(0.73135370, -0.68199836), // 312 vec2(0.74314483, -0.66913061), vec2(0.75470958, -0.65605903), vec2(0.76604444, -0.64278761), vec2(0.77714596, -0.62932039), vec2(0.78801075, -0.61566148), vec2(0.79863551, -0.60181502), // 318 vec2(0.80901699, -0.58778525), vec2(0.81915204, -0.57357644), vec2(0.82903757, -0.55919290), vec2(0.83867057, -0.54463904), vec2(0.84804810, -0.52991926), vec2(0.85716730, -0.51503807), // 324 vec2(0.86602540, -0.50000000), vec2(0.87461971, -0.48480962), vec2(0.88294759, -0.46947156), vec2(0.89100652, -0.45399050), vec2(0.89879405, -0.43837115), vec2(0.90630779, -0.42261826), // 330 vec2(0.91354546, -0.40673664), vec2(0.92050485, -0.39073113), vec2(0.92718385, -0.37460659), vec2(0.93358043, -0.35836795), vec2(0.93969262, -0.34202014), vec2(0.94551858, -0.32556815), // 336 vec2(0.95105652, -0.30901699), vec2(0.95630476, -0.29237170), vec2(0.96126170, -0.27563736), vec2(0.96592583, -0.25881905), vec2(0.97029573, -0.24192190), vec2(0.97437006, -0.22495105), // 342 vec2(0.97814760, -0.20791169), vec2(0.98162718, -0.19080900), vec2(0.98480775, -0.17364818), vec2(0.98768834, -0.15643447), vec2(0.99026807, -0.13917310), vec2(0.99254615, -0.12186934), // 348 vec2(0.99452190, -0.10452846), vec2(0.99619470, -0.08715574), vec2(0.99756405, -0.06975647), vec2(0.99862953, -0.05233596), vec2(0.99939083, -0.03489950), vec2(0.99984770, -0.01745241), // 354 vec2(1.00000000, 0.00000000), vec2(0.99984770, 0.01745241), vec2(0.99939083, 0.03489950), vec2(0.99862953, 0.05233596), vec2(0.99756405, 0.06975647), vec2(0.99619470, 0.08715574), // 360 vec2(0.99452190, 0.10452846), vec2(0.99254615, 0.12186934), vec2(0.99026807, 0.13917310), vec2(0.98768834, 0.15643447), vec2(0.98480775, 0.17364818), vec2(0.98162718, 0.19080900), // 366 vec2(0.97814760, 0.20791169), vec2(0.97437006, 0.22495105), vec2(0.97029573, 0.24192190), vec2(0.96592583, 0.25881905), vec2(0.96126170, 0.27563736), vec2(0.95630476, 0.29237170), // 372 vec2(0.95105652, 0.30901699), vec2(0.94551858, 0.32556815), vec2(0.93969262, 0.34202014), vec2(0.93358043, 0.35836795), vec2(0.92718385, 0.37460659), vec2(0.92050485, 0.39073113), // 378 vec2(0.91354546, 0.40673664), vec2(0.90630779, 0.42261826), vec2(0.89879405, 0.43837115), vec2(0.89100652, 0.45399050), vec2(0.88294759, 0.46947156), vec2(0.87461971, 0.48480962), // 384 vec2(0.86602540, 0.50000000), vec2(0.85716730, 0.51503807), vec2(0.84804810, 0.52991926), vec2(0.83867057, 0.54463904), vec2(0.82903757, 0.55919290), vec2(0.81915204, 0.57357644), // 390 vec2(0.80901699, 0.58778525), vec2(0.79863551, 0.60181502), vec2(0.78801075, 0.61566148), vec2(0.77714596, 0.62932039), vec2(0.76604444, 0.64278761), vec2(0.75470958, 0.65605903), // 396 vec2(0.74314483, 0.66913061), vec2(0.73135370, 0.68199836), vec2(0.71933980, 0.69465837), vec2(0.70710678, 0.70710678), vec2(0.69465837, 0.71933980), vec2(0.68199836, 0.73135370), // 402 vec2(0.66913061, 0.74314483), vec2(0.65605903, 0.75470958), vec2(0.64278761, 0.76604444), vec2(0.62932039, 0.77714596), vec2(0.61566148, 0.78801075), vec2(0.60181502, 0.79863551), // 408 vec2(0.58778525, 0.80901699), vec2(0.57357644, 0.81915204), vec2(0.55919290, 0.82903757), vec2(0.54463904, 0.83867057), vec2(0.52991926, 0.84804810), vec2(0.51503807, 0.85716730), // 414 vec2(0.50000000, 0.86602540), vec2(0.48480962, 0.87461971), vec2(0.46947156, 0.88294759), vec2(0.45399050, 0.89100652), vec2(0.43837115, 0.89879405), vec2(0.42261826, 0.90630779), // 420 vec2(0.40673664, 0.91354546), vec2(0.39073113, 0.92050485), vec2(0.37460659, 0.92718385), vec2(0.35836795, 0.93358043), vec2(0.34202014, 0.93969262), vec2(0.32556815, 0.94551858), // 426 vec2(0.30901699, 0.95105652), vec2(0.29237170, 0.95630476), vec2(0.27563736, 0.96126170), vec2(0.25881905, 0.96592583), vec2(0.24192190, 0.97029573), vec2(0.22495105, 0.97437006), // 432 vec2(0.20791169, 0.97814760), vec2(0.19080900, 0.98162718), vec2(0.17364818, 0.98480775), vec2(0.15643447, 0.98768834), vec2(0.13917310, 0.99026807), vec2(0.12186934, 0.99254615), // 438 vec2(0.10452846, 0.99452190), vec2(0.08715574, 0.99619470), vec2(0.06975647, 0.99756405), vec2(0.05233596, 0.99862953), vec2(0.03489950, 0.99939083), vec2(0.01745241, 0.99984770), // 444 vec2(0.00000000, 1.00000000), vec2(-0.01745241, 0.99984770), vec2(-0.03489950, 0.99939083), vec2(-0.05233596, 0.99862953), vec2(-0.06975647, 0.99756405), vec2(-0.08715574, 0.99619470), // 450 vec2(-0.10452846, 0.99452190), vec2(-0.12186934, 0.99254615), vec2(-0.13917310, 0.99026807), vec2(-0.15643447, 0.98768834), vec2(-0.17364818, 0.98480775), vec2(-0.19080900, 0.98162718), // 456 vec2(-0.20791169, 0.97814760), vec2(-0.22495105, 0.97437006), vec2(-0.24192190, 0.97029573), vec2(-0.25881905, 0.96592583), vec2(-0.27563736, 0.96126170), vec2(-0.29237170, 0.95630476), // 462 vec2(-0.30901699, 0.95105652), vec2(-0.32556815, 0.94551858), vec2(-0.34202014, 0.93969262), vec2(-0.35836795, 0.93358043), vec2(-0.37460659, 0.92718385), vec2(-0.39073113, 0.92050485), // 468 vec2(-0.40673664, 0.91354546), vec2(-0.42261826, 0.90630779), vec2(-0.43837115, 0.89879405), vec2(-0.45399050, 0.89100652), vec2(-0.46947156, 0.88294759), vec2(-0.48480962, 0.87461971), // 474 vec2(-0.50000000, 0.86602540), vec2(-0.51503807, 0.85716730), vec2(-0.52991926, 0.84804810), vec2(-0.54463904, 0.83867057), vec2(-0.55919290, 0.82903757), vec2(-0.57357644, 0.81915204), // 480 vec2(-0.58778525, 0.80901699), vec2(-0.60181502, 0.79863551), vec2(-0.61566148, 0.78801075), vec2(-0.62932039, 0.77714596), vec2(-0.64278761, 0.76604444), vec2(-0.65605903, 0.75470958), // 486 vec2(-0.66913061, 0.74314483), vec2(-0.68199836, 0.73135370), vec2(-0.69465837, 0.71933980), vec2(-0.70710678, 0.70710678), vec2(-0.71933980, 0.69465837), vec2(-0.73135370, 0.68199836), // 492 vec2(-0.74314483, 0.66913061), vec2(-0.75470958, 0.65605903), vec2(-0.76604444, 0.64278761), vec2(-0.77714596, 0.62932039), vec2(-0.78801075, 0.61566148), vec2(-0.79863551, 0.60181502), // 498 vec2(-0.80901699, 0.58778525), vec2(-0.81915204, 0.57357644), vec2(-0.82903757, 0.55919290), vec2(-0.83867057, 0.54463904), vec2(-0.84804810, 0.52991926), vec2(-0.85716730, 0.51503807), // 504 vec2(-0.86602540, 0.50000000), vec2(-0.87461971, 0.48480962), vec2(-0.88294759, 0.46947156), vec2(-0.89100652, 0.45399050), vec2(-0.89879405, 0.43837115), vec2(-0.90630779, 0.42261826), // 510 vec2(-0.91354546, 0.40673664), vec2(-0.92050485, 0.39073113), vec2(-0.92718385, 0.37460659), vec2(-0.93358043, 0.35836795), vec2(-0.93969262, 0.34202014), vec2(-0.94551858, 0.32556815), // 516 vec2(-0.95105652, 0.30901699), vec2(-0.95630476, 0.29237170), vec2(-0.96126170, 0.27563736), vec2(-0.96592583, 0.25881905), vec2(-0.97029573, 0.24192190), vec2(-0.97437006, 0.22495105), // 522 vec2(-0.97814760, 0.20791169), vec2(-0.98162718, 0.19080900), vec2(-0.98480775, 0.17364818), vec2(-0.98768834, 0.15643447), vec2(-0.99026807, 0.13917310), vec2(-0.99254615, 0.12186934), // 528 vec2(-0.99452190, 0.10452846), vec2(-0.99619470, 0.08715574), vec2(-0.99756405, 0.06975647), vec2(-0.99862953, 0.05233596), vec2(-0.99939083, 0.03489950), vec2(-0.99984770, 0.01745241), // 534 vec2(-1.00000000, 0.00000000), vec2(-0.99984770, -0.01745241), vec2(-0.99939083, -0.03489950), vec2(-0.99862953, -0.05233596), vec2(-0.99756405, -0.06975647), vec2(-0.99619470, -0.08715574), // 540 vec2(-0.99452190, -0.10452846), vec2(-0.99254615, -0.12186934), vec2(-0.99026807, -0.13917310), vec2(-0.98768834, -0.15643447), vec2(-0.98480775, -0.17364818), vec2(-0.98162718, -0.19080900), // 546 vec2(-0.97814760, -0.20791169), vec2(-0.97437006, -0.22495105), vec2(-0.97029573, -0.24192190), vec2(-0.96592583, -0.25881905), vec2(-0.96126170, -0.27563736), vec2(-0.95630476, -0.29237170), // 552 vec2(-0.95105652, -0.30901699), vec2(-0.94551858, -0.32556815), vec2(-0.93969262, -0.34202014), vec2(-0.93358043, -0.35836795), vec2(-0.92718385, -0.37460659), vec2(-0.92050485, -0.39073113), // 558 vec2(-0.91354546, -0.40673664), vec2(-0.90630779, -0.42261826), vec2(-0.89879405, -0.43837115), vec2(-0.89100652, -0.45399050), vec2(-0.88294759, -0.46947156), vec2(-0.87461971, -0.48480962), // 564 vec2(-0.86602540, -0.50000000), vec2(-0.85716730, -0.51503807), vec2(-0.84804810, -0.52991926), vec2(-0.83867057, -0.54463904), vec2(-0.82903757, -0.55919290), vec2(-0.81915204, -0.57357644), // 570 vec2(-0.80901699, -0.58778525), vec2(-0.79863551, -0.60181502), vec2(-0.78801075, -0.61566148), vec2(-0.77714596, -0.62932039), vec2(-0.76604444, -0.64278761), vec2(-0.75470958, -0.65605903), // 576 vec2(-0.74314483, -0.66913061), vec2(-0.73135370, -0.68199836), vec2(-0.71933980, -0.69465837), vec2(-0.70710678, -0.70710678), vec2(-0.69465837, -0.71933980), vec2(-0.68199836, -0.73135370), // 582 vec2(-0.66913061, -0.74314483), vec2(-0.65605903, -0.75470958), vec2(-0.64278761, -0.76604444), vec2(-0.62932039, -0.77714596), vec2(-0.61566148, -0.78801075), vec2(-0.60181502, -0.79863551), // 588 vec2(-0.58778525, -0.80901699), vec2(-0.57357644, -0.81915204), vec2(-0.55919290, -0.82903757), vec2(-0.54463904, -0.83867057), vec2(-0.52991926, -0.84804810), vec2(-0.51503807, -0.85716730), // 594 vec2(-0.50000000, -0.86602540), vec2(-0.48480962, -0.87461971), vec2(-0.46947156, -0.88294759), vec2(-0.45399050, -0.89100652), vec2(-0.43837115, -0.89879405), vec2(-0.42261826, -0.90630779), // 600 vec2(-0.40673664, -0.91354546), vec2(-0.39073113, -0.92050485), vec2(-0.37460659, -0.92718385), vec2(-0.35836795, -0.93358043), vec2(-0.34202014, -0.93969262), vec2(-0.32556815, -0.94551858), // 606 vec2(-0.30901699, -0.95105652), vec2(-0.29237170, -0.95630476), vec2(-0.27563736, -0.96126170), vec2(-0.25881905, -0.96592583), vec2(-0.24192190, -0.97029573), vec2(-0.22495105, -0.97437006), // 612 vec2(-0.20791169, -0.97814760), vec2(-0.19080900, -0.98162718), vec2(-0.17364818, -0.98480775), vec2(-0.15643447, -0.98768834), vec2(-0.13917310, -0.99026807), vec2(-0.12186934, -0.99254615), // 618 vec2(-0.10452846, -0.99452190), vec2(-0.08715574, -0.99619470), vec2(-0.06975647, -0.99756405), vec2(-0.05233596, -0.99862953), vec2(-0.03489950, -0.99939083), vec2(-0.01745241, -0.99984770), // 624 vec2(-0.00000000, -1.00000000), vec2(0.01745241, -0.99984770), vec2(0.03489950, -0.99939083), vec2(0.05233596, -0.99862953), vec2(0.06975647, -0.99756405), vec2(0.08715574, -0.99619470), // 630 vec2(0.10452846, -0.99452190), vec2(0.12186934, -0.99254615), vec2(0.13917310, -0.99026807), vec2(0.15643447, -0.98768834), vec2(0.17364818, -0.98480775), vec2(0.19080900, -0.98162718), // 636 vec2(0.20791169, -0.97814760), vec2(0.22495105, -0.97437006), vec2(0.24192190, -0.97029573), vec2(0.25881905, -0.96592583), vec2(0.27563736, -0.96126170), vec2(0.29237170, -0.95630476), // 642 vec2(0.30901699, -0.95105652), vec2(0.32556815, -0.94551858), vec2(0.34202014, -0.93969262), vec2(0.35836795, -0.93358043), vec2(0.37460659, -0.92718385), vec2(0.39073113, -0.92050485), // 648 vec2(0.40673664, -0.91354546), vec2(0.42261826, -0.90630779), vec2(0.43837115, -0.89879405), vec2(0.45399050, -0.89100652), vec2(0.46947156, -0.88294759), vec2(0.48480962, -0.87461971), // 654 vec2(0.50000000, -0.86602540), vec2(0.51503807, -0.85716730), vec2(0.52991926, -0.84804810), vec2(0.54463904, -0.83867057), vec2(0.55919290, -0.82903757), vec2(0.57357644, -0.81915204), // 660 vec2(0.58778525, -0.80901699), vec2(0.60181502, -0.79863551), vec2(0.61566148, -0.78801075), vec2(0.62932039, -0.77714596), vec2(0.64278761, -0.76604444), vec2(0.65605903, -0.75470958), // 666 vec2(0.66913061, -0.74314483), vec2(0.68199836, -0.73135370), vec2(0.69465837, -0.71933980), vec2(0.70710678, -0.70710678), vec2(0.71933980, -0.69465837), vec2(0.73135370, -0.68199836), // 672 vec2(0.74314483, -0.66913061), vec2(0.75470958, -0.65605903), vec2(0.76604444, -0.64278761), vec2(0.77714596, -0.62932039), vec2(0.78801075, -0.61566148), vec2(0.79863551, -0.60181502), // 678 vec2(0.80901699, -0.58778525), vec2(0.81915204, -0.57357644), vec2(0.82903757, -0.55919290), vec2(0.83867057, -0.54463904), vec2(0.84804810, -0.52991926), vec2(0.85716730, -0.51503807), // 684 vec2(0.86602540, -0.50000000), vec2(0.87461971, -0.48480962), vec2(0.88294759, -0.46947156), vec2(0.89100652, -0.45399050), vec2(0.89879405, -0.43837115), vec2(0.90630779, -0.42261826), // 690 vec2(0.91354546, -0.40673664), vec2(0.92050485, -0.39073113), vec2(0.92718385, -0.37460659), vec2(0.93358043, -0.35836795), vec2(0.93969262, -0.34202014), vec2(0.94551858, -0.32556815), // 696 vec2(0.95105652, -0.30901699), vec2(0.95630476, -0.29237170), vec2(0.96126170, -0.27563736), vec2(0.96592583, -0.25881905), vec2(0.97029573, -0.24192190), vec2(0.97437006, -0.22495105), // 702 vec2(0.97814760, -0.20791169), vec2(0.98162718, -0.19080900), vec2(0.98480775, -0.17364818), vec2(0.98768834, -0.15643447), vec2(0.99026807, -0.13917310), vec2(0.99254615, -0.12186934), // 708 vec2(0.99452190, -0.10452846), vec2(0.99619470, -0.08715574), vec2(0.99756405, -0.06975647), vec2(0.99862953, -0.05233596), vec2(0.99939083, -0.03489950), vec2(0.99984770, -0.01745241), // 714 vec2(1.00000000, 0.00000000) // 720 }; sandboxgamemaker-2.7.1+dfsg/src/shared/pch.cpp0000664000175000017500000000002311400572340021154 0ustar showardshoward#include "cube.h" sandboxgamemaker-2.7.1+dfsg/src/shared/cube.h0000664000175000017500000000222411601337414020776 0ustar showardshoward#ifndef __CUBE_H__ #define __CUBE_H__ #define _FILE_OFFSET_BITS 64 #ifdef __GNUC__ #define gamma __gamma #endif #ifdef WIN32 #define _USE_MATH_DEFINES #endif #include #ifdef __GNUC__ #undef gamma #endif #include #include #include #include #include #include #include #include #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #define _WIN32_WINNT 0x0500 #include "windows.h" #ifndef _WINDOWS #define _WINDOWS #endif #ifndef __GNUC__ #include #include #endif #define ZLIB_DLL #endif #ifndef STANDALONE #include #include #define GL_GLEXT_LEGACY #define __glext_h__ #define NO_SDL_GLEXT #include #undef __glext_h__ #include "GL/glext.h" #endif #include #include #ifdef __sun__ #undef sun #undef MAXNAMELEN #ifdef queue #undef queue #endif #define queue __squeue #endif #include "tools.h" #include "geom.h" #include "ents.h" #include "command.h" #include "iengine.h" #include "igame.h" #endif sandboxgamemaker-2.7.1+dfsg/src/shared/crypto.cpp0000664000175000017500000006436511400572340021745 0ustar showardshoward#include "cube.h" ///////////////////////// cryptography ///////////////////////////////// /* Based off the reference implementation of Tiger, a cryptographically * secure 192 bit hash function by Ross Anderson and Eli Biham. More info at: * http://www.cs.technion.ac.il/~biham/Reports/Tiger/ */ #define TIGER_PASSES 3 namespace tiger { typedef unsigned long long int chunk; union hashval { uchar bytes[3*8]; chunk chunks[3]; }; chunk sboxes[4*256]; void compress(const chunk *str, chunk state[3]) { chunk a, b, c; chunk aa, bb, cc; chunk x0, x1, x2, x3, x4, x5, x6, x7; a = state[0]; b = state[1]; c = state[2]; x0=str[0]; x1=str[1]; x2=str[2]; x3=str[3]; x4=str[4]; x5=str[5]; x6=str[6]; x7=str[7]; aa = a; bb = b; cc = c; loop(pass_no, TIGER_PASSES) { if(pass_no) { x0 -= x7 ^ 0xA5A5A5A5A5A5A5A5ULL; x1 ^= x0; x2 += x1; x3 -= x2 ^ ((~x1)<<19); x4 ^= x3; x5 += x4; x6 -= x5 ^ ((~x4)>>23); x7 ^= x6; x0 += x7; x1 -= x0 ^ ((~x7)<<19); x2 ^= x1; x3 += x2; x4 -= x3 ^ ((~x2)>>23); x5 ^= x4; x6 += x5; x7 -= x6 ^ 0x0123456789ABCDEFULL; } #define sb1 (sboxes) #define sb2 (sboxes+256) #define sb3 (sboxes+256*2) #define sb4 (sboxes+256*3) #define round(a, b, c, x) \ c ^= x; \ a -= sb1[((c)>>(0*8))&0xFF] ^ sb2[((c)>>(2*8))&0xFF] ^ \ sb3[((c)>>(4*8))&0xFF] ^ sb4[((c)>>(6*8))&0xFF] ; \ b += sb4[((c)>>(1*8))&0xFF] ^ sb3[((c)>>(3*8))&0xFF] ^ \ sb2[((c)>>(5*8))&0xFF] ^ sb1[((c)>>(7*8))&0xFF] ; \ b *= mul; uint mul = !pass_no ? 5 : (pass_no==1 ? 7 : 9); round(a, b, c, x0) round(b, c, a, x1) round(c, a, b, x2) round(a, b, c, x3) round(b, c, a, x4) round(c, a, b, x5) round(a, b, c, x6) round(b, c, a, x7) chunk tmp = a; a = c; c = b; b = tmp; } a ^= aa; b -= bb; c += cc; state[0] = a; state[1] = b; state[2] = c; } void gensboxes() { const char *str = "Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham"; chunk state[3] = { 0x0123456789ABCDEFULL, 0xFEDCBA9876543210ULL, 0xF096A5B4C3B2E187ULL }; uchar temp[64]; if(!*(const uchar *)&islittleendian) loopj(64) temp[j^7] = str[j]; else loopj(64) temp[j] = str[j]; loopi(1024) loop(col, 8) ((uchar *)&sboxes[i])[col] = i&0xFF; int abc = 2; loop(pass, 5) loopi(256) for(int sb = 0; sb < 1024; sb += 256) { abc++; if(abc >= 3) { abc = 0; compress((chunk *)temp, state); } loop(col, 8) { uchar val = ((uchar *)&sboxes[sb+i])[col]; ((uchar *)&sboxes[sb+i])[col] = ((uchar *)&sboxes[sb + ((uchar *)&state[abc])[col]])[col]; ((uchar *)&sboxes[sb + ((uchar *)&state[abc])[col]])[col] = val; } } } void hash(const uchar *str, int length, hashval &val) { static bool init = false; if(!init) { gensboxes(); init = true; } uchar temp[64]; val.chunks[0] = 0x0123456789ABCDEFULL; val.chunks[1] = 0xFEDCBA9876543210ULL; val.chunks[2] = 0xF096A5B4C3B2E187ULL; int i = length; for(; i >= 64; i -= 64, str += 64) { if(!*(const uchar *)&islittleendian) { loopj(64) temp[j^7] = str[j]; compress((chunk *)temp, val.chunks); } else compress((chunk *)str, val.chunks); } int j; if(!*(const uchar *)&islittleendian) { for(j = 0; j < i; j++) temp[j^7] = str[j]; temp[j^7] = 0x01; while(++j&7) temp[j^7] = 0; } else { for(j = 0; j < i; j++) temp[j] = str[j]; temp[j] = 0x01; while(++j&7) temp[j] = 0; } if(j > 56) { while(j < 64) temp[j++] = 0; compress((chunk *)temp, val.chunks); j = 0; } while(j < 56) temp[j++] = 0; *(chunk *)(temp+56) = (chunk)length<<3; compress((chunk *)temp, val.chunks); if(!*(const uchar *)&islittleendian) { loopk(3) { uchar *c = &val.bytes[k*sizeof(chunk)]; loopl(sizeof(chunk)/2) swap(c[l], c[sizeof(chunk)-1-l]); } } } } /* Elliptic curve cryptography based on NIST DSS prime curves. */ #define BI_DIGIT_BITS 16 #define BI_DIGIT_MASK ((1< struct bigint { typedef ushort digit; typedef uint dbldigit; int len; digit digits[BI_DIGITS]; bigint() {} bigint(digit n) { if(n) { len = 1; digits[0] = n; } else len = 0; } bigint(const char *s) { parse(s); } template bigint(const bigint &y) { *this = y; } static int parsedigits(ushort *digits, int maxlen, const char *s) { int slen = 0; while(isxdigit(s[slen])) slen++; int len = (slen+2*sizeof(ushort)-1)/(2*sizeof(ushort)); if(len>maxlen) return 0; memset(digits, 0, len*sizeof(ushort)); loopi(slen) { int c = s[slen-i-1]; if(isalpha(c)) c = toupper(c) - 'A' + 10; else if(isdigit(c)) c -= '0'; else return 0; digits[i/(2*sizeof(ushort))] |= c<<(4*(i%(2*sizeof(ushort)))); } return len; } void parse(const char *s) { len = parsedigits(digits, BI_DIGITS, s); shrink(); } void zero() { len = 0; } void print(stream *out) const { vector buf; printdigits(buf); out->write(buf.getbuf(), buf.length()); } void printdigits(vector &buf) const { loopi(len) { digit d = digits[len-i-1]; loopj(BI_DIGIT_BITS/4) { uint shift = BI_DIGIT_BITS - (j+1)*4; int val = (d >> shift) & 0xF; if(val < 10) buf.add('0' + val); else buf.add('a' + val - 10); } } } template bigint &operator=(const bigint &y) { len = y.len; memcpy(digits, y.digits, len*sizeof(digit)); return *this; } bool iszero() const { return !len; } bool isone() const { return len==1 && digits[0]==1; } int numbits() const { if(!len) return 0; int bits = len*BI_DIGIT_BITS; digit last = digits[len-1], mask = 1<<(BI_DIGIT_BITS-1); while(mask) { if(last&mask) return bits; bits--; mask >>= 1; } return 0; } bool hasbit(int n) const { return n/BI_DIGIT_BITS < len && ((digits[n/BI_DIGIT_BITS]>>(n%BI_DIGIT_BITS))&1); } template bigint &add(const bigint &x, const bigint &y) { dbldigit carry = 0; int maxlen = max(x.len, y.len), i; for(i = 0; i < y.len || carry; i++) { carry += (i < x.len ? (dbldigit)x.digits[i] : 0) + (i < y.len ? (dbldigit)y.digits[i] : 0); digits[i] = (digit)carry; carry >>= BI_DIGIT_BITS; } if(i < x.len && this != &x) memcpy(&digits[i], &x.digits[i], (x.len - i)*sizeof(digit)); len = max(i, maxlen); return *this; } template bigint &add(const bigint &y) { return add(*this, y); } template bigint &sub(const bigint &x, const bigint &y) { ASSERT(x >= y); dbldigit borrow = 0; int i; for(i = 0; i < y.len || borrow; i++) { borrow = (1<>BI_DIGIT_BITS)^1; } if(i < x.len && this != &x) memcpy(&digits[i], &x.digits[i], (x.len - i)*sizeof(digit)); len = x.len; shrink(); return *this; } template bigint &sub(const bigint &y) { return sub(*this, y); } void shrink() { while(len && !digits[len-1]) len--; } template bigint &mul(const bigint &x, const bigint &y) { if(!x.len || !y.len) { len = 0; return *this; } memset(digits, 0, y.len*sizeof(digit)); loopi(x.len) { dbldigit carry = 0; loopj(y.len) { carry += (dbldigit)x.digits[i] * (dbldigit)y.digits[j] + (dbldigit)digits[i+j]; digits[i+j] = (digit)carry; carry >>= BI_DIGIT_BITS; } digits[i+y.len] = carry; } len = x.len + y.len; shrink(); return *this; } template bigint &rshift(const bigint &x, int n) { if(!len || !n) return *this; int dig = (n-1)/BI_DIGIT_BITS; n = ((n-1) % BI_DIGIT_BITS)+1; digit carry = digit(x.digits[dig]>>n); loopi(len-dig-1) { digit tmp = x.digits[i+dig+1]; digits[i] = digit((tmp<<(BI_DIGIT_BITS-n)) | carry); carry = digit(tmp>>n); } digits[len-dig-1] = carry; len -= dig + (n>>BI_DIGIT_BITS); shrink(); return *this; } bigint &rshift(int n) { return rshift(*this, n); } template bigint &lshift(const bigint &x, int n) { if(!len || !n) return *this; int dig = n/BI_DIGIT_BITS; n %= BI_DIGIT_BITS; digit carry = 0; for(int i = len-1; i>=0; i--) { digit tmp = x.digits[i]; digits[i+dig] = digit((tmp<>(BI_DIGIT_BITS-n)); } len += dig; if(carry) digits[len++] = carry; if(dig) memset(digits, 0, dig*sizeof(digit)); return *this; } bigint &lshift(int n) { return lshift(*this, n); } template bool operator==(const bigint &y) const { if(len!=y.len) return false; for(int i = len-1; i>=0; i--) if(digits[i]!=y.digits[i]) return false; return true; } template bool operator!=(const bigint &y) const { return !(*this==y); } template bool operator<(const bigint &y) const { if(leny.len) return false; for(int i = len-1; i>=0; i--) { if(digits[i]y.digits[i]) return false; } return false; } template bool operator>(const bigint &y) const { return y<*this; } template bool operator<=(const bigint &y) const { return !(y<*this); } template bool operator>=(const bigint &y) const { return !(*this gfint; /* NIST prime Galois fields. * Currently only supports NIST P-192, where P=2^192-2^64-1. */ struct gfield : gfint { static const gfield P; gfield() {} gfield(digit n) : gfint(n) {} gfield(const char *s) : gfint(s) {} template gfield(const bigint &y) : gfint(y) {} template gfield &operator=(const bigint &y) { gfint::operator=(y); return *this; } template gfield &add(const bigint &x, const bigint &y) { gfint::add(x, y); if(*this >= P) gfint::sub(*this, P); return *this; } template gfield &add(const bigint &y) { return add(*this, y); } template gfield &mul2(const bigint &x) { return add(x, x); } gfield &mul2() { return mul2(*this); } template gfield &div2(const bigint &x) { if(hasbit(0)) { gfint::add(x, P); rshift(1); } else rshift(x, 1); return *this; } gfield &div2() { return div2(*this); } template gfield &sub(const bigint &x, const bigint &y) { if(x < y) { gfint tmp; /* necessary if this==&y, using this instead would clobber y */ tmp.add(x, P); gfint::sub(tmp, y); } else gfint::sub(x, y); return *this; } template gfield &sub(const bigint &y) { return sub(*this, y); } template gfield &neg(const bigint &x) { gfint::sub(P, x); return *this; } gfield &neg() { return neg(*this); } template gfield &square(const bigint &x) { return mul(x, x); } gfield &square() { return square(*this); } template gfield &mul(const bigint &x, const bigint &y) { bigint result; result.mul(x, y); reduce(result); return *this; } template gfield &mul(const bigint &y) { return mul(*this, y); } template void reduce(const bigint &result) { #if GF_BITS==192 len = min(result.len, GF_DIGITS); memcpy(digits, result.digits, len*sizeof(digit)); shrink(); if(result.len > 192/BI_DIGIT_BITS) { gfield s; memcpy(s.digits, &result.digits[192/BI_DIGIT_BITS], min(result.len-192/BI_DIGIT_BITS, 64/BI_DIGIT_BITS)*sizeof(digit)); if(result.len < 256/BI_DIGIT_BITS) memset(&s.digits[result.len-192/BI_DIGIT_BITS], 0, (256/BI_DIGIT_BITS-result.len)*sizeof(digit)); memcpy(&s.digits[64/BI_DIGIT_BITS], s.digits, 64/BI_DIGIT_BITS*sizeof(digit)); s.len = 128/BI_DIGIT_BITS; s.shrink(); add(s); if(result.len > 256/BI_DIGIT_BITS) { memset(s.digits, 0, 64/BI_DIGIT_BITS*sizeof(digit)); memcpy(&s.digits[64/BI_DIGIT_BITS], &result.digits[256/BI_DIGIT_BITS], min(result.len-256/BI_DIGIT_BITS, 64/BI_DIGIT_BITS)*sizeof(digit)); if(result.len < 320/BI_DIGIT_BITS) memset(&s.digits[result.len+(64-256)/BI_DIGIT_BITS], 0, (320/BI_DIGIT_BITS-result.len)*sizeof(digit)); memcpy(&s.digits[128/BI_DIGIT_BITS], &s.digits[64/BI_DIGIT_BITS], 64/BI_DIGIT_BITS*sizeof(digit)); s.len = GF_DIGITS; s.shrink(); add(s); if(result.len > 320/BI_DIGIT_BITS) { memcpy(s.digits, &result.digits[320/BI_DIGIT_BITS], min(result.len-320/BI_DIGIT_BITS, 64/BI_DIGIT_BITS)*sizeof(digit)); if(result.len < 384/BI_DIGIT_BITS) memset(&s.digits[result.len-320/BI_DIGIT_BITS], 0, (384/BI_DIGIT_BITS-result.len)*sizeof(digit)); memcpy(&s.digits[64/BI_DIGIT_BITS], s.digits, 64/BI_DIGIT_BITS*sizeof(digit)); memcpy(&s.digits[128/BI_DIGIT_BITS], s.digits, 64/BI_DIGIT_BITS*sizeof(digit)); s.len = GF_DIGITS; s.shrink(); add(s); } } } else if(*this >= P) gfint::sub(*this, P); #else #error Unsupported GF #endif } template gfield &pow(const bigint &x, const bigint &y) { gfield a(x); if(y.hasbit(0)) *this = a; else { len = 1; digits[0] = 1; if(!y.len) return *this; } for(int i = 1, j = y.numbits(); i < j; i++) { a.square(); if(y.hasbit(i)) mul(a); } return *this; } template gfield &pow(const bigint &y) { return pow(*this, y); } bool invert(const gfield &x) { if(!x.len) return false; gfint u(x), v(P), A((gfint::digit)1), C((gfint::digit)0); while(!u.iszero()) { int ushift = 0, ashift = 0; while(!u.hasbit(ushift)) { ushift++; if(A.hasbit(ashift)) { if(ashift) { A.rshift(ashift); ashift = 0; } A.add(P); } ashift++; } if(ushift) u.rshift(ushift); if(ashift) A.rshift(ashift); int vshift = 0, cshift = 0; while(!v.hasbit(vshift)) { vshift++; if(C.hasbit(cshift)) { if(cshift) { C.rshift(cshift); cshift = 0; } C.add(P); } cshift++; } if(vshift) v.rshift(vshift); if(cshift) C.rshift(cshift); if(u >= v) { u.sub(v); if(A < C) A.add(P); A.sub(C); } else { v.sub(v, u); if(C < A) C.add(P); C.sub(A); } } if(C >= P) gfint::sub(C, P); else { len = C.len; memcpy(digits, C.digits, len*sizeof(digit)); } ASSERT(*this < P); return true; } void invert() { invert(*this); } template static int legendre(const bigint &x) { static const gfint Psub1div2(gfint(P).sub(bigint<1>(1)).rshift(1)); gfield L; L.pow(x, Psub1div2); if(!L.len) return 0; if(L.len==1) return 1; return -1; } int legendre() const { return legendre(*this); } bool sqrt(const gfield &x) { if(!x.len) { len = 0; return true; } #if GF_BITS==224 #error Unsupported GF #else ASSERT((P.digits[0]%4)==3); static const gfint Padd1div4(gfint(P).add(bigint<1>(1)).rshift(2)); switch(legendre(x)) { case 0: len = 0; return true; case -1: return false; default: pow(x, Padd1div4); return true; } #endif } bool sqrt() { return sqrt(*this); } }; struct ecjacobian { static const gfield B; static const ecjacobian base; static const ecjacobian origin; gfield x, y, z; ecjacobian() {} ecjacobian(const gfield &x, const gfield &y) : x(x), y(y), z(bigint<1>(1)) {} ecjacobian(const gfield &x, const gfield &y, const gfield &z) : x(x), y(y), z(z) {} void mul2() { if(z.iszero()) return; else if(y.iszero()) { *this = origin; return; } gfield a, b, c, d; d.sub(x, c.square(z)); d.mul(c.add(x)); c.mul2(d).add(d); z.mul(y).add(z); a.square(y); b.mul2(a); d.mul2(x).mul(b); x.square(c).sub(d).sub(d); a.square(b).add(a); y.sub(d, x).mul(c).sub(a); } void add(const ecjacobian &q) { if(q.z.iszero()) return; else if(z.iszero()) { *this = q; return; } gfield a, b, c, d, e, f; a.square(z); b.mul(q.y, a).mul(z); a.mul(q.x); if(q.z.isone()) { c.add(x, a); d.add(y, b); a.sub(x, a); b.sub(y, b); } else { f.mul(y, e.square(q.z)).mul(q.z); e.mul(x); c.add(e, a); d.add(f, b); a.sub(e, a); b.sub(f, b); } if(a.iszero()) { if(b.iszero()) mul2(); else *this = origin; return; } if(!q.z.isone()) z.mul(q.z); z.mul(a); x.square(b).sub(f.mul(c, e.square(a))); y.sub(f, x).sub(x).mul(b).sub(e.mul(a).mul(d)).div2(); } template void mul(const ecjacobian &p, const bigint q) { *this = origin; for(int i = q.numbits()-1; i >= 0; i--) { mul2(); if(q.hasbit(i)) add(p); } } template void mul(const bigint q) { ecjacobian tmp(*this); mul(tmp, q); } void normalize() { if(z.iszero() || z.isone()) return; gfield tmp; z.invert(); tmp.square(z); x.mul(tmp); y.mul(tmp).mul(z); z = bigint<1>(1); } bool calcy(bool ybit) { gfield y2, tmp; y2.square(x).mul(x).sub(tmp.add(x, x).add(x)).add(B); if(!y.sqrt(y2)) { y.zero(); return false; } if(y.hasbit(0) != ybit) y.neg(); return true; } void print(vector &buf) { normalize(); buf.add(y.hasbit(0) ? '-' : '+'); x.printdigits(buf); } void parse(const char *s) { bool ybit = *s++ == '-'; x.parse(s); calcy(ybit); z = bigint<1>(1); } }; const ecjacobian ecjacobian::origin(gfield((gfield::digit)1), gfield((gfield::digit)1), gfield((gfield::digit)0)); #if GF_BITS==192 const gfield gfield::P("fffffffffffffffffffffffffffffffeffffffffffffffff"); const gfield ecjacobian::B("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1"); const ecjacobian ecjacobian::base( gfield("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"), gfield("07192b95ffc8da78631011ed6b24cdd573f977a11e794811") ); #elif GF_BITS==224 const gfield gfield::P("ffffffffffffffffffffffffffffffff000000000000000000000001"); const gfield ecjacobian::B("b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4"); const ecjacobian ecjacobian::base( gfield("b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21"), gfield("bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34"), ); #elif GF_BITS==256 const gfield gfield::P("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff"); const gfield ecjacobian::B("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"); const ecjacobian ecjacobian::base( gfield("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"), gfield("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"), ); #elif GF_BITS==384 const gfield gfield::P("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"); const gfield ecjacobian::B("b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"); const ecjacobian ecjacobian::base( gfield("aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"), gfield("3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"), ); #elif GF_BITS==521 const gfield gfield::P("1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); const gfield ecjacobian::B("051953eb968e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"); const ecjacobian ecjacobian::base( gfield("c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"), gfield("11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650") ); #else #error Unsupported GF #endif void genprivkey(const char *seed, vector &privstr, vector &pubstr) { tiger::hashval hash; tiger::hash((const uchar *)seed, (int)strlen(seed), hash); bigint<8*sizeof(hash.bytes)/BI_DIGIT_BITS> privkey; memcpy(privkey.digits, hash.bytes, sizeof(privkey.digits)); privkey.len = 8*sizeof(hash.bytes)/BI_DIGIT_BITS; privkey.shrink(); privkey.printdigits(privstr); privstr.add('\0'); ecjacobian c(ecjacobian::base); c.mul(privkey); c.normalize(); c.print(pubstr); pubstr.add('\0'); } bool hashstring(const char *str, char *result, int maxlen) { tiger::hashval hv; if(maxlen < 2*(int)sizeof(hv.bytes) + 1) return false; tiger::hash((uchar *)str, strlen(str), hv); loopi(sizeof(hv.bytes)) { uchar c = hv.bytes[i]; *result++ = "0123456789abcdef"[c&0xF]; *result++ = "0123456789abcdef"[c>>4]; } *result = '\0'; return true; } void answerchallenge(const char *privstr, const char *challenge, vector &answerstr) { gfint privkey; privkey.parse(privstr); ecjacobian answer; answer.parse(challenge); answer.mul(privkey); answer.normalize(); answer.x.printdigits(answerstr); answerstr.add('\0'); } void *parsepubkey(const char *pubstr) { ecjacobian *pubkey = new ecjacobian; pubkey->parse(pubstr); return pubkey; } void freepubkey(void *pubkey) { delete (ecjacobian *)pubkey; } void *genchallenge(void *pubkey, const void *seed, int seedlen, vector &challengestr) { tiger::hashval hash; tiger::hash((const uchar *)seed, sizeof(seed), hash); gfint challenge; memcpy(challenge.digits, hash.bytes, sizeof(challenge.digits)); challenge.len = 8*sizeof(hash.bytes)/BI_DIGIT_BITS; challenge.shrink(); ecjacobian answer(*(ecjacobian *)pubkey); answer.mul(challenge); answer.normalize(); ecjacobian secret(ecjacobian::base); secret.mul(challenge); secret.normalize(); secret.print(challengestr); challengestr.add('\0'); return new gfield(answer.x); } void freechallenge(void *answer) { delete (gfint *)answer; } bool checkchallenge(const char *answerstr, void *correct) { gfint answer(answerstr); return answer == *(gfint *)correct; } sandboxgamemaker-2.7.1+dfsg/src/shared/cube2font.c0000664000175000017500000004215211660231276021752 0ustar showardshoward#include #include #include #include #include #include #include #include FT_FREETYPE_H #include FT_STROKER_H #include FT_GLYPH_H typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; void fatal(const char *fmt, ...) // failure exit { va_list v; va_start(v, fmt); vfprintf(stderr, fmt, v); va_end(v); fputc('\n', stderr); exit(EXIT_FAILURE); } void savepng(uchar *pixels, int w, int h, const char *name) { FILE *f = fopen(name, "wb"); int y; png_structp p; png_infop i; if(!f) goto failed; p = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if(!p) goto failed; i = png_create_info_struct(p); if(!i) goto failed; if(!setjmp(png_jmpbuf(p))) { png_init_io(p, f); png_set_compression_level(p, 9); png_set_IHDR(p, i, w, h, 8, PNG_COLOR_TYPE_GRAY_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(p, i); for(y = 0; y < h; y++) { png_write_row(p, &pixels[y*w*2]); } png_write_end(p, NULL); png_destroy_write_struct(&p, &i); fclose(f); return; } failed: fatal("cube2font: failed writing %s", name); } int iscubeprint(int c) { static const char flags[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; return flags[c]; } int cube2uni(int c) { static const int conv[256] = { 0, 192, 193, 194, 195, 196, 197, 198, 199, 9, 10, 11, 12, 13, 200, 201, 202, 203, 204, 205, 206, 207, 209, 210, 211, 212, 213, 214, 216, 217, 218, 219, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 220, 221, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 241, 242, 243, 244, 245, 246, 248, 249, 250, 251, 252, 253, 255, 0x104, 0x105, 0x106, 0x107, 0x10C, 0x10D, 0x10E, 0x10F, 0x118, 0x119, 0x11A, 0x11B, 0x11E, 0x11F, 0x130, 0x131, 0x141, 0x142, 0x143, 0x144, 0x147, 0x148, 0x150, 0x151, 0x152, 0x153, 0x158, 0x159, 0x15A, 0x15B, 0x15E, 0x15F, 0x160, 0x161, 0x164, 0x165, 0x16E, 0x16F, 0x170, 0x171, 0x178, 0x179, 0x17A, 0x17B, 0x17C, 0x17D, 0x17E, 0x404, 0x411, 0x413, 0x414, 0x416, 0x417, 0x418, 0x419, 0x41B, 0x41F, 0x423, 0x424, 0x426, 0x427, 0x428, 0x429, 0x42A, 0x42B, 0x42C, 0x42D, 0x42E, 0x42F, 0x431, 0x432, 0x433, 0x434, 0x436, 0x437, 0x438, 0x439, 0x43A, 0x43B, 0x43C, 0x43D, 0x43F, 0x442, 0x444, 0x446, 0x447, 0x448, 0x449, 0x44A, 0x44B, 0x44C, 0x44D, 0x44E, 0x44F, 0x454, 0x490, 0x491 }; return conv[c]; } int uni2cube(int c) { static const int offsets[256] = { 0, 256, 658, 658, 512, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, }; static const int chars[878] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 12, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 14, 15, 16, 17, 18, 19, 20, 21, 0, 22, 23, 24, 25, 26, 27, 0, 28, 29, 30, 31, 127, 128, 0, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 0, 146, 147, 148, 149, 150, 151, 0, 152, 153, 154, 155, 156, 157, 0, 158, 0, 0, 0, 0, 159, 160, 161, 162, 0, 0, 0, 0, 163, 164, 165, 166, 0, 0, 0, 0, 0, 0, 0, 0, 167, 168, 169, 170, 0, 0, 171, 172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 173, 174, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 175, 176, 177, 178, 0, 0, 179, 180, 0, 0, 0, 0, 0, 0, 0, 181, 182, 183, 184, 0, 0, 0, 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, 192, 0, 0, 193, 194, 0, 0, 0, 0, 0, 0, 0, 0, 195, 196, 197, 198, 0, 0, 0, 0, 0, 0, 199, 200, 201, 202, 203, 204, 205, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 206, 83, 73, 21, 74, 0, 0, 0, 0, 0, 0, 0, 65, 207, 66, 208, 209, 69, 210, 211, 212, 213, 75, 214, 77, 72, 79, 215, 80, 67, 84, 216, 217, 88, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 97, 228, 229, 230, 231, 101, 232, 233, 234, 235, 236, 237, 238, 239, 111, 240, 112, 99, 241, 121, 242, 120, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 0, 141, 0, 0, 253, 115, 105, 145, 106, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 254, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; return uint(c) <= 0xFFFF ? chars[offsets[c>>8] + (c&0xFF)] : 0; } const char *encodeutf8(int uni) { static char buf[7]; char *dst = buf; if(uni <= 0x7F) { *dst++ = uni; goto uni1; } else if(uni <= 0x7FF) { *dst++ = 0xC0 | (uni>>6); goto uni2; } else if(uni <= 0xFFFF) { *dst++ = 0xE0 | (uni>>12); goto uni3; } else if(uni <= 0x1FFFFF) { *dst++ = 0xF0 | (uni>>18); goto uni4; } else if(uni <= 0x3FFFFFF) { *dst++ = 0xF8 | (uni>>24); goto uni5; } else if(uni <= 0x7FFFFFFF) { *dst++ = 0xFC | (uni>>30); goto uni6; } else goto uni1; uni6: *dst++ = 0x80 | ((uni>>24)&0x3F); uni5: *dst++ = 0x80 | ((uni>>18)&0x3F); uni4: *dst++ = 0x80 | ((uni>>12)&0x3F); uni3: *dst++ = 0x80 | ((uni>>6)&0x3F); uni2: *dst++ = 0x80 | (uni&0x3F); uni1: *dst++ = '\0'; return buf; } struct fontchar { int code, uni, tex, x, y, w, h, offx, offy, advance; FT_BitmapGlyph color, alpha; }; char *texname(const char *name, int texnum) { static char file[256]; snprintf(file, sizeof(file), "%s%d.png", name, texnum); return file; } void writetexs(const char *name, struct fontchar *chars, int numchars, int numtexs, int tw, int th) { int tex; uchar *pixels = (uchar *)malloc(tw*th*2); if(!pixels) fatal("cube2font: failed allocating textures"); for(tex = 0; tex < numtexs; tex++) { const char *file = texname(name, tex); int texchars = 0, i; uchar *dst, *src; memset(pixels, 0, tw*th*2); for(i = 0; i < numchars; i++) { struct fontchar *c = &chars[i]; int x, y; if(c->tex != tex) continue; texchars++; dst = &pixels[2*((c->y + c->alpha->top - c->color->top)*tw + c->x + c->color->left - c->alpha->left)]; src = (uchar *)c->color->bitmap.buffer; for(y = 0; y < c->color->bitmap.rows; y++) { for(x = 0; x < c->color->bitmap.width; x++) dst[2*x] = src[x]; src += c->color->bitmap.pitch; dst += 2*tw; } dst = &pixels[2*(c->y*tw + c->x)]; src = (uchar *)c->alpha->bitmap.buffer; for(y = 0; y < c->alpha->bitmap.rows; y++) { for(x = 0; x < c->alpha->bitmap.width; x++) dst[2*x+1] = src[x]; src += c->alpha->bitmap.pitch; dst += 2*tw; } } printf("cube2font: writing %d chars to %s\n", texchars, file); savepng(pixels, tw, th, file); } free(pixels); } void writecfg(const char *name, struct fontchar *chars, int numchars, int x1, int y1, int x2, int y2, int space) { FILE *f; char file[256]; int i, lastcode = 0, lasttex = 0; snprintf(file, sizeof(file), "%s.cfg", name); f = fopen(file, "w"); if(!f) fatal("cube2font: failed writing %s", file); printf("cube2font: writing %d chars to %s\n", numchars, file); fprintf(f, "font \"%s\" \"%s\" %d %d\n", name, texname(name, 0), space, y2-y1); for(i = 0; i < numchars; i++) { struct fontchar *c = &chars[i]; if(!lastcode && lastcode < c->code) { fprintf(f, "fontoffset \"%s\"\n", encodeutf8(c->uni)); lastcode = c->code; } else if(lastcode < c->code) { if(lastcode + 1 == c->code) fprintf(f, "fontskip // %d\n", lastcode); else fprintf(f, "fontskip %d // %d .. %d\n", c->code - lastcode, lastcode, c->code-1); lastcode = c->code; } if(lasttex != c->tex) { fprintf(f, "\nfonttex \"%s\"\n", texname(name, c->tex)); lasttex = c->tex; } if(c->code != c->uni) fprintf(f, "fontchar %d %d %d %d %d %d %d // %s (%d -> 0x%X)\n", c->x, c->y, c->w, c->h, c->offx, y2-c->offy, c->advance, encodeutf8(c->uni), c->code, c->uni); else fprintf(f, "fontchar %d %d %d %d %d %d %d // %s (%d)\n", c->x, c->y, c->w, c->h, c->offx, y2-c->offy, c->advance, encodeutf8(c->uni), c->code); lastcode++; } fclose(f); } int groupchar(int c) { switch(c) { case 0x152: case 0x153: case 0x178: return 1; } if(c < 127 || c >= 0x2000) return 0; if(c < 0x100) return 1; if(c < 0x400) return 2; return 3; } int sortchars(const void *x, const void *y) { const struct fontchar *xc = *(const struct fontchar **)x, *yc = *(const struct fontchar **)y; int xg = groupchar(xc->uni), yg = groupchar(yc->uni); if(xg < yg) return -1; if(xg > yg) return 1; if(xc->h != yc->h) return yc->h - xc->h; if(xc->w != yc->w) return yc->w - xc->w; return yc->uni - xc->uni; } int main(int argc, char **argv) { FT_Library l; FT_Face f; FT_Stroker s; int i, pad, offset, advance, w, h, tw, th, c, rw = 0, rh = 0, ry = 0, x1 = INT_MAX, x2 = INT_MIN, y1 = INT_MAX, y2 = INT_MIN, w2 = 0, h2 = 0; float border; struct fontchar chars[256]; struct fontchar *order[256]; int numchars = 0, numtex = 0; if(argc < 11) fatal("Usage: cube2font infile outfile border pad offset advance charwidth charheight texwidth texheight"); border = atof(argv[3]); pad = atoi(argv[4]); offset = atoi(argv[5]); advance = atoi(argv[6]); w = atoi(argv[7]); h = atoi(argv[8]); tw = atoi(argv[9]); th = atoi(argv[10]); if(FT_Init_FreeType(&l)) fatal("cube2font: failed initing freetype"); if(FT_New_Face(l, argv[1], 0, &f) || FT_Set_Charmap(f, f->charmaps[0]) || FT_Set_Pixel_Sizes(f, w, h) || FT_Stroker_New(l, &s)) fatal("cube2font: failed loading font %s", argv[1]); FT_Stroker_Set(s, (FT_Fixed)(border * 64), FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); for(c = 0; c < 256; c++) if(iscubeprint(c)) { FT_Glyph p, p2; FT_BitmapGlyph b, b2; struct fontchar *dst = &chars[numchars]; dst->code = c; dst->uni = cube2uni(c); if(FT_Load_Char(f, dst->uni, FT_LOAD_DEFAULT)) fatal("cube2font: failed loading character %s", encodeutf8(dst->uni)); FT_Get_Glyph(f->glyph, &p); p2 = p; FT_Glyph_StrokeBorder(&p, s, 0, 0); FT_Glyph_To_Bitmap(&p, FT_RENDER_MODE_NORMAL, 0, 1); FT_Glyph_To_Bitmap(&p2, FT_RENDER_MODE_NORMAL, 0, 1); b = (FT_BitmapGlyph)p; b2 = (FT_BitmapGlyph)p2; dst->tex = -1; dst->offx = b->left + offset; dst->offy = b->top; dst->advance = offset + ((p->advance.x+0xFFFF)>>16) + advance; dst->w = b->bitmap.width; dst->h = b->bitmap.rows; dst->alpha = b; dst->color = b2; order[numchars++] = dst; } qsort(order, numchars, sizeof(order[0]), sortchars); for(i = 0; i < numchars; i++) { FT_BitmapGlyph b; struct fontchar *dst = order[i]; int j, g; if(dst->tex >= 0) continue; g = groupchar(dst->uni); for(j = i; j < numchars; j++) { struct fontchar *fit = order[j]; if(groupchar(fit->uni) != g) break; if(fit->tex >= 0) continue; if(rw + fit->alpha->bitmap.width <= tw && ry + fit->alpha->bitmap.rows <= th) { dst = fit; break; } } b = dst->alpha; if(rw + b->bitmap.width > tw) { ry += rh + pad; rw = rh = 0; } if(ry + b->bitmap.rows > th) { ry = rw = rh = 0; numtex++; } dst->tex = numtex; dst->x = rw; dst->y = ry; rw += b->bitmap.width + pad; if(b->bitmap.rows > rh) rh = b->bitmap.rows; if(b->top - b->bitmap.rows < y1) y1 = b->top - b->bitmap.rows; if(b->top > y2) y2 = b->top; if(b->left < x1) x1 = b->left; if(b->left + b->bitmap.width > x2) x2 = b->left + b->bitmap.width; if(b->bitmap.width > w2) w2 = b->bitmap.width; if(b->bitmap.rows > h2) h2 = b->bitmap.rows; if(dst != order[i]) --i; } if(FT_Load_Char(f, ' ', FT_LOAD_DEFAULT)) fatal("cube2font: failed loading space character"); if(rh > 0) numtex++; writetexs(argv[2], chars, numchars, numtex, tw, th); writecfg(argv[2], chars, numchars, x1, y1, x2, y2, (f->glyph->advance.x+0x3F)>>6); for(i = 0; i < numchars; i++) { FT_Done_Glyph((FT_Glyph)chars[i].alpha); FT_Done_Glyph((FT_Glyph)chars[i].color); } FT_Stroker_Done(s); FT_Done_FreeType(l); printf("cube2font: (%d, %d) .. (%d, %d) = (%d, %d) / (%d, %d), %d texs\n", x1, y1, x2, y2, x2 - x1, y2 - y1, w2, h2, numtex); return EXIT_SUCCESS; } sandboxgamemaker-2.7.1+dfsg/src/shared/tools.cpp0000664000175000017500000000156211601337414021557 0ustar showardshoward// implementation of generic tools #include "cube.h" ////////////////////////// rnd numbers //////////////////////////////////////// #define N (624) #define M (397) #define K (0x9908B0DFU) static uint state[N]; static int next = N; void seedMT(uint seed) { state[0] = seed; for(uint i = 1; i < N; i++) state[i] = seed = 1812433253U * (seed ^ (seed >> 30)) + i; next = 0; } uint randomMT() { int cur = next; if(++next >= N) { if(next > N) { seedMT(5489U + time(NULL)); cur = next++; } else next = 0; } uint y = (state[cur] & 0x80000000U) | (state[next] & 0x7FFFFFFFU); state[cur] = y = state[cur < N-M ? cur + M : cur + M-N] ^ (y >> 1) ^ (-int(y & 1U) & K); y ^= (y >> 11); y ^= (y << 7) & 0x9D2C5680U; y ^= (y << 15) & 0xEFC60000U; y ^= (y >> 18); return y; }sandboxgamemaker-2.7.1+dfsg/src/shared/igame.h0000664000175000017500000001341511527772736021167 0ustar showardshoward// the interface the engine uses to run the gameplay module namespace entities { extern void editent(int i, bool local); extern const char *entnameinfo(entity &e); extern const char *entname(int i); extern const int numattrs(int type); extern int extraentinfosize(); extern void writeent(entity &e, char *buf); extern void readent(entity &e, char *buf, int ver); extern float dropheight(entity &e); extern void fixentity(extentity &e); extern void entradius(extentity &e, bool &color); extern bool mayattach(extentity &e); extern bool attachent(extentity &e, extentity &a); extern bool printent(extentity &e, char *buf); extern extentity *newentity(); extern void deleteentity(extentity *e); extern void clearents(); extern vector &getents(); extern bool dirent(extentity &e); extern bool radiusent(extentity &e); extern void renderhelpertext(extentity &e, int &colour, vec &pos, string &tmp); extern const char *entmodel(const entity &e); extern void animatemapmodel(const extentity &e, int &anim, int &basetime); extern int *getmodelattr(extentity &e); extern bool checkmodelusage(extentity &e, int i); } namespace game { extern void parseoptions(vector &args); extern void gamedisconnect(bool cleanup); extern void parsepacketclient(int chan, packetbuf &p); extern void connectattempt(const char *name, const char *password, const ENetAddress &address); extern void connectfail(); extern void gameconnect(bool _remote); extern bool allowedittoggle(); extern void edittoggled(bool on); extern void writeclientinfo(stream *f); extern void toserver(char *text); extern void changemap(const char *name); extern void forceedit(const char *name); extern bool ispaused(); extern const char *gameident(); extern const char *autoexec(); extern const char *savedservers(); extern void loadconfigs(); extern void updateworld(); extern void initclient(); extern void physicstrigger(physent *d, bool local, int floorlevel, int waterlevel, int material = 0); extern void bounced(physent *d, const vec &surface); extern void edittrigger(const selinfo &sel, int op, int arg1 = 0, int arg2 = 0, int arg3 = 0); extern void vartrigger(ident *id); extern void dynentcollide(physent *d, physent *o, const vec &dir); extern const char *getclientmap(); extern const char *getmapinfo(); extern void resetgamestate(); extern void suicide(physent *d); extern void newmap(int size); extern void startmap(const char *name); extern void preload(); extern float abovegameplayhud(int w, int h); extern void gameplayhud(int w, int h); extern bool canjump(); extern bool allowmove(physent *d); extern dynent *iterdynents(int i); extern int numdynents(); extern void rendergame(bool mainpass); extern void renderavatar(); extern void writegamedata(vector &extras); extern void readgamedata(vector &extras); extern int clipconsole(int w, int h); extern const char *defaultcrosshair(int index); extern int selectcrosshair(float &r, float &g, float &b); extern void lighteffects(dynent *d, vec &color, vec &dir); extern void setupcamera(); extern bool detachcamera(); extern bool collidecamera(); extern void adddynlights(); extern void writemapdata(stream *f); extern void particletrack(physent *owner, vec &o, vec &d); extern void dynlighttrack(physent *owner, vec &o, vec &hud); extern bool needminimap(); #ifndef NEWGUI extern void g3d_gamemenus(); extern bool serverinfostartcolumn(g3d_gui *g, int i); extern void serverinfoendcolumn(g3d_gui *g, int i); extern bool serverinfoentry(g3d_gui *g, int i, const char *name, int port, const char *desc, const char *map, int ping, const vector &attr, int np); #endif extern bool allowdoublejump(); extern bool showenthelpers(); extern void setwindowcaption(); //__offtools__ - disfunc fix this extern void texturefailed(char *file, int slot); extern void mmodelfailed(const char *name, int idx); extern void mapfailed(const char *name); //__offtools__ extern void registeranimation(char *dir, char* anim, int num); //return false if you do not wish to override the associated code in game - return true otherwise extern bool mousemove(int &dx, int &dy, float &cursens); extern bool recomputecamera(physent *&camera1, physent &tempcamera, bool &detachedcamera, float &thirdpersondistance); } namespace server { extern void *newclientinfo(); extern void deleteclientinfo(void *ci); extern void serverinit(); extern int reserveclients(); extern int numchannels(); extern void clientdisconnect(int n); extern int clientconnect(int n, uint ip); extern void localdisconnect(int n); extern void localconnect(int n); extern bool allowbroadcast(int n); extern void parsepacket(int sender, int chan, packetbuf &p); extern void sendservmsg(const char *s); extern void recordpacket(int chan, void *data, int len); extern bool sendpackets(bool force = false); extern void serverinforeply(ucharbuf &req, ucharbuf &p); extern void serverupdate(); extern bool servercompatible(char *name, char *sdec, char *map, int ping, const vector &attr, int np); extern int laninfoport(); extern int serverinfoport(int servport = -1); extern int serverport(int infoport = -1); extern const char *defaultmaster(); extern int masterport(); extern void processmasterinput(const char *cmd, int cmdlen, const char *args); extern bool ispaused(); } sandboxgamemaker-2.7.1+dfsg/src/shared/tools.h0000664000175000017500000007212611655776736021257 0ustar showardshoward// generic useful stuff for any C++ program #ifndef _TOOLS_H #define _TOOLS_H #ifdef NULL #undef NULL #endif #define NULL 0 typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef signed long long int llong; typedef unsigned long long int ullong; #ifdef _DEBUG #ifdef __GNUC__ #define ASSERT(c) if(!(c)) { asm("int $3"); } #else #define ASSERT(c) if(!(c)) { __asm int 3 } #endif #else #define ASSERT(c) if(c) {} #endif #if defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1400) #define RESTRICT __restrict #else #define RESTRICT #endif inline void *operator new(size_t size) { void *p = malloc(size); if(!p) abort(); return p; } inline void *operator new[](size_t size) { void *p = malloc(size); if(!p) abort(); return p; } inline void operator delete(void *p) { if(p) free(p); } inline void operator delete[](void *p) { if(p) free(p); } inline void *operator new(size_t, void *p) { return p; } inline void *operator new[](size_t, void *p) { return p; } inline void operator delete(void *, void *) {} inline void operator delete[](void *, void *) {} #ifdef swap #undef swap #endif template static inline void swap(T &a, T &b) { T t = a; a = b; b = t; } #ifdef max #undef max #endif #ifdef min #undef min #endif template static inline T max(T a, T b) { return a > b ? a : b; } template static inline T min(T a, T b) { return a < b ? a : b; } template static inline T clamp(T a, T b, T c) //max min val { return max(b, min(a, c)); } #define rnd(x) ((int)(randomMT()&0xFFFFFF)%(x)) #define rndscale(x) (float((randomMT()&0xFFFFFF)*double(x)/double(0xFFFFFF))) #define detrnd(s, x) ((int)(((((uint)(s))*1103515245+12345)>>16)%(x))) #define loop(v,m) for(int v = 0; v= 0; v--) #define loopirev(m) looprev(i, m) #define DELETEP(p) if(p) { delete p; p = 0; } #define DELETEA(p) if(p) { delete[] p; p = 0; } #define PI (3.1415927f) #define PI2 (2*PI) #define SQRT2 (1.4142136f) #define SQRT3 (1.7320508f) #define RAD (PI / 180.0f) #ifdef WIN32 #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef M_LN2 #define M_LN2 0.693147180559945309417 #endif #ifndef __GNUC__ #pragma warning (3: 4189) // local variable is initialized but not referenced #pragma warning (disable: 4244) // conversion from 'int' to 'float', possible loss of data #pragma warning (disable: 4267) // conversion from 'size_t' to 'int', possible loss of data #pragma warning (disable: 4355) // 'this' : used in base member initializer list #pragma warning (disable: 4996) // 'strncpy' was declared deprecated #endif #define strcasecmp _stricmp #define PATHDIV '\\' #else #define __cdecl #define _vsnprintf vsnprintf #define PATHDIV '/' #endif // easy safe strings #define MAXSTRLEN 260 typedef char string[MAXSTRLEN]; inline void vformatstring(char *d, const char *fmt, va_list v, int len = MAXSTRLEN) { _vsnprintf(d, len, fmt, v); d[len-1] = 0; } inline char *copystring(char *d, const char *s, size_t len = MAXSTRLEN) { strncpy(d, s, len); d[len-1] = 0; return d; } inline char *concatstring(char *d, const char *s, size_t len = MAXSTRLEN) { size_t used = strlen(d); return used < len ? copystring(d+used, s, len-used) : d; } struct stringformatter { char *buf; stringformatter(char *buf): buf((char *)buf) {} void operator()(const char *fmt, ...) { va_list v; va_start(v, fmt); vformatstring(buf, fmt, v); va_end(v); } }; #define formatstring(d) stringformatter((char *)d) #define defformatstring(d) string d; formatstring(d) #define defvformatstring(d,last,fmt) string d; { va_list ap; va_start(ap, last); vformatstring(d, fmt, ap); va_end(ap); } #define loopv(v) for(int i = 0; i<(v).length(); i++) #define loopvj(v) for(int j = 0; j<(v).length(); j++) #define loopvk(v) for(int k = 0; k<(v).length(); k++) #define loopvrev(v) for(int i = (v).length()-1; i>=0; i--) template struct databuf { enum { OVERREAD = 1<<0, OVERWROTE = 1<<1 }; T *buf; int len, maxlen; uchar flags; databuf() : buf(NULL), len(0), maxlen(0), flags(0) {} template databuf(T *buf, U maxlen) : buf(buf), len(0), maxlen((int)maxlen), flags(0) {} const T &get() { static T overreadval = 0; if(len charbuf; typedef databuf ucharbuf; struct packetbuf : ucharbuf { ENetPacket *packet; int growth; packetbuf(ENetPacket *packet) : ucharbuf(packet->data, packet->dataLength), packet(packet), growth(0) {} packetbuf(int growth, int pflags = 0) : growth(growth) { packet = enet_packet_create(NULL, growth, pflags); buf = (uchar *)packet->data; maxlen = packet->dataLength; } ~packetbuf() { cleanup(); } void reliable() { packet->flags |= ENET_PACKET_FLAG_RELIABLE; } void resize(int n) { enet_packet_resize(packet, n); buf = (uchar *)packet->data; maxlen = packet->dataLength; } void checkspace(int n) { if(len + n > maxlen && packet && growth > 0) resize(max(len + n, maxlen + growth)); } ucharbuf subbuf(int sz) { checkspace(sz); return ucharbuf::subbuf(sz); } void put(const uchar &val) { checkspace(1); ucharbuf::put(val); } void put(const uchar *vals, int numvals) { checkspace(numvals); ucharbuf::put(vals, numvals); } ENetPacket *finalize() { resize(len); return packet; } void cleanup() { if(growth > 0 && packet && !packet->referenceCount) { enet_packet_destroy(packet); packet = NULL; buf = NULL; len = maxlen = 0; } } }; template static inline float heapscore(const T &n) { return n; } template static inline bool compareless(const T &x, const T &y) { return x < y; } template static inline void insertionsort(T *start, T *end, F fun) { for(T *i = start+1; i < end; i++) { if(fun(*i, i[-1])) { T tmp = *i; *i = i[-1]; T *j = i-1; for(; j > start && fun(tmp, j[-1]); --j) *j = j[-1]; *j = tmp; } } } template static inline void insertionsort(T *buf, int n, F fun) { insertionsort(buf, buf+n, fun); } template static inline void insertionsort(T *buf, int n) { insertionsort(buf, buf+n, compareless); } template static inline void quicksort(T *start, T *end, F fun) { while(end-start > 10) { T *mid = &start[(end-start)/2], *i = start+1, *j = end-2, pivot; if(fun(*start, *mid)) /* start < mid */ { if(fun(end[-1], *start)) { pivot = *start; *start = end[-1]; end[-1] = *mid; } /* end < start < mid */ else if(fun(end[-1], *mid)) { pivot = end[-1]; end[-1] = *mid; } /* start <= end < mid */ else { pivot = *mid; } /* start < mid <= end */ } else if(fun(*start, end[-1])) { pivot = *start; *start = *mid; } /*mid <= start < end */ else if(fun(*mid, end[-1])) { pivot = end[-1]; end[-1] = *start; *start = *mid; } /* mid < end <= start */ else { pivot = *mid; swap(*start, end[-1]); } /* end <= mid <= start */ *mid = end[-2]; do { while(fun(*i, pivot)) if(++i >= j) goto partitioned; while(fun(pivot, *--j)) if(i >= j) goto partitioned; swap(*i, *j); } while(++i < j); partitioned: end[-2] = *i; *i = pivot; if(i-start < end-(i+1)) { quicksort(start, i, fun); start = i+1; } else { quicksort(i+1, end, fun); end = i; } } insertionsort(start, end, fun); } template static inline void quicksort(T *buf, int n, F fun) { quicksort(buf, buf+n, fun); } template static inline void quicksort(T *buf, int n) { quicksort(buf, buf+n, compareless); } template struct vector { static const int MINSIZE = 8; T *buf; int alen, ulen; vector() : buf(NULL), alen(0), ulen(0) { } vector(const vector &v) : buf(NULL), alen(0), ulen(0) { *this = v; } ~vector() { shrink(0); if(buf) delete[] (uchar *)buf; } vector &operator=(const vector &v) { shrink(0); if(v.length() > alen) growbuf(v.length()); loopv(v) add(v[i]); return *this; } T &add(const T &x) { if(ulen==alen) growbuf(ulen+1); new (&buf[ulen]) T(x); return buf[ulen++]; } T &add() { if(ulen==alen) growbuf(ulen+1); new (&buf[ulen]) T; return buf[ulen++]; } T &dup() { if(ulen==alen) growbuf(ulen+1); new (&buf[ulen]) T(buf[ulen-1]); return buf[ulen++]; } void move(vector &v) { if(!ulen) { swap(buf, v.buf); swap(ulen, v.ulen); swap(alen, v.alen); } else { growbuf(ulen+v.ulen); if(v.ulen) memcpy(&buf[ulen], v.buf, v.ulen*sizeof(T)); ulen += v.ulen; v.ulen = 0; } } bool inrange(size_t i) const { return i=0 && i=0 && i= 0 && ii) drop(); } void setsize(int i) { ASSERT(i<=ulen); ulen = i; } void deletecontents() { while(!empty()) delete pop(); } void deletearrays() { while(!empty()) delete[] pop(); } T *getbuf() { return buf; } const T *getbuf() const { return buf; } bool inbuf(const T *e) const { return e >= buf && e < &buf[ulen]; } template void sort(F fun, int i = 0, int n = -1) { quicksort(&buf[i], n < 0 ? ulen-i : n, fun); } void sort() { sort(compareless); } void growbuf(int sz) { int olen = alen; if(!alen) alen = max(MINSIZE, sz); else while(alen < sz) alen *= 2; if(alen <= olen) return; uchar *newbuf = new uchar[alen*sizeof(T)]; if(olen > 0) { memcpy(newbuf, buf, olen*sizeof(T)); delete[] (uchar *)buf; } buf = (T *)newbuf; } databuf reserve(int sz) { if(ulen+sz > alen) growbuf(ulen+sz); return databuf(&buf[ulen], sz); } void advance(int sz) { ulen += sz; } void addbuf(const databuf &p) { advance(p.length()); } T *pad(int n) { T *buf = reserve(n).buf; advance(n); return buf; } void put(const T &v) { add(v); } void put(const T *v, int n) { databuf buf = reserve(n); buf.put(v, n); addbuf(buf); } void remove(int i, int n) { for(int p = i+n; p0) buf[i] = buf[ulen]; return e; } template int find(const U &o) { loopi(ulen) if(buf[i]==o) return i; return -1; } void removeobj(const T &o) { loopi(ulen) if(buf[i]==o) remove(i--); } void replacewithlast(const T &o) { if(!ulen) return; loopi(ulen-1) if(buf[i]==o) { buf[i] = buf[ulen-1]; } ulen--; } T &insert(int i, const T &e) { add(T()); for(int p = ulen-1; p>i; p--) buf[p] = buf[p-1]; buf[i] = e; return buf[i]; } T *insert(int i, const T *e, int n) { if(ulen+n>alen) growbuf(ulen+n); loopj(n) add(T()); for(int p = ulen-1; p>=i+n; p--) buf[p] = buf[p-n]; loopj(n) buf[i+j] = e[j]; return &buf[i]; } void reverse() { loopi(ulen/2) swap(buf[i], buf[ulen-1-i]); } static int heapparent(int i) { return (i - 1) >> 1; } static int heapchild(int i) { return (i << 1) + 1; } void buildheap() { for(int i = ulen/2; i >= 0; i--) downheap(i); } int upheap(int i) { float score = heapscore(buf[i]); while(i > 0) { int pi = heapparent(i); if(score >= heapscore(buf[pi])) break; swap(buf[i], buf[pi]); i = pi; } return i; } T &addheap(const T &x) { add(x); return buf[upheap(ulen-1)]; } int downheap(int i) { float score = heapscore(buf[i]); for(;;) { int ci = heapchild(i); if(ci >= ulen) break; float cscore = heapscore(buf[ci]); if(score > cscore) { if(ci+1 < ulen && heapscore(buf[ci+1]) < cscore) { swap(buf[ci+1], buf[i]); i = ci+1; } else { swap(buf[ci], buf[i]); i = ci; } } else if(ci+1 < ulen && heapscore(buf[ci+1]) < score) { swap(buf[ci+1], buf[i]); i = ci+1; } else break; } return i; } T removeheap() { T e = removeunordered(0); if(ulen) downheap(0); return e; } }; static inline uint hthash(const char *key) { uint h = 5381; for(int i = 0, k; (k = key[i]); i++) h = ((h<<5)+h)^k; // bernstein k=33 xor return h; } static inline bool htcmp(const char *x, const char *y) { return !strcmp(x, y); } static inline uint hthash(int key) { return key; } static inline bool htcmp(int x, int y) { return x==y; } template struct hashset { typedef T elem; typedef const T const_elem; enum { CHUNKSIZE = 64 }; struct chain { T elem; chain *next; }; struct chainchunk { chain chains[CHUNKSIZE]; chainchunk *next; }; int size; int numelems; chain **chains; chainchunk *chunks; chain *unused; hashset(int size = 1<<10) : size(size) { numelems = 0; chunks = NULL; unused = NULL; chains = new chain *[size]; loopi(size) chains[i] = NULL; } ~hashset() { DELETEA(chains); deletechunks(); } chain *insert(uint h) { if(!unused) { chainchunk *chunk = new chainchunk; chunk->next = chunks; chunks = chunk; loopi(CHUNKSIZE-1) chunk->chains[i].next = &chunk->chains[i+1]; chunk->chains[CHUNKSIZE-1].next = unused; unused = chunk->chains; } chain *c = unused; unused = unused->next; c->next = chains[h]; chains[h] = c; numelems++; return c; } #define HTFIND(key, success, fail) \ uint h = hthash(key)&(this->size-1); \ for(chain *c = this->chains[h]; c; c = c->next) \ { \ if(htcmp(key, c->elem)) return (success); \ } \ return (fail); template T *access(const K &key) { HTFIND(key, &c->elem, NULL); } template T &access(const K &key, const E &elem) { HTFIND(key, c->elem, insert(h)->elem = elem); } template T &operator[](const K &key) { HTFIND(key, c->elem, insert(h)->elem); } template bool remove(const K &key) { uint h = hthash(key)&(size-1); for(chain **p = &chains[h], *c = chains[h]; c; p = &c->next, c = c->next) { if(htcmp(key, c->elem)) { *p = c->next; c->elem.~T(); new (&c->elem) T; c->next = unused; unused = c; numelems--; return true; } } return false; } void deletechunks() { for(chainchunk *nextchunk; chunks; chunks = nextchunk) { nextchunk = chunks->next; delete chunks; } } void clear() { if(!numelems) return; loopi(size) chains[i] = NULL; numelems = 0; unused = NULL; deletechunks(); } static inline chain *getnext(void *i) { return ((chain *)i)->next; } static inline T &getdata(void *i) { return ((chain *)i)->elem; } }; template struct hashtableentry { K key; T data; hashtableentry() {} hashtableentry(const K &key, const T &data) : key(key), data(data) {} }; template static inline bool htcmp(const U *x, const hashtableentry &y) { return htcmp(x, y.key); } template static inline bool htcmp(const U &x, const hashtableentry &y) { return htcmp(x, y.key); } template struct hashtable : hashset > { typedef hashtableentry entry; typedef struct hashset::chain chain; typedef K key; typedef T value; hashtable(int size = 1<<10) : hashset(size) {} entry &insert(const K &key, uint h) { chain *c = hashset::insert(h); c->elem.key = key; return c->elem; } T *access(const K &key) { HTFIND(key, &c->elem.data, NULL); } T &access(const K &key, const T &data) { HTFIND(key, c->elem.data, insert(key, h).data = data); } T &operator[](const K &key) { HTFIND(key, c->elem.data, insert(key, h).data); } static inline chain *getnext(void *i) { return ((chain *)i)->next; } static inline K &getkey(void *i) { return ((chain *)i)->elem.key; } static inline T &getdata(void *i) { return ((chain *)i)->elem.data; } }; #define enumerates(ht,t,e,b) loopi((ht).size) for(hashset::chain *enumc = (ht).chains[i]; enumc;) { t &e = enumc->elem; enumc = enumc->next; b; } #define enumeratekt(ht,k,e,t,f,b) loopi((ht).size) for(hashtable::chain *enumc = (ht).chains[i]; enumc;) { const hashtable::key &e = enumc->elem.key; t &f = enumc->elem.data; enumc = enumc->next; b; } #define enumerate(ht,t,e,b) loopi((ht).size) for(void *enumc = (ht).chains[i]; enumc;) { t &e = (ht).getdata(enumc); enumc = (ht).getnext(enumc); b; } struct unionfind { struct ufval { int rank, next; ufval() : rank(0), next(-1) {} }; vector ufvals; int find(int k) { if(k>=ufvals.length()) return k; while(ufvals[k].next>=0) k = ufvals[k].next; return k; } int compressfind(int k) { if(ufvals[k].next<0) return k; return ufvals[k].next = compressfind(ufvals[k].next); } void unite (int x, int y) { while(ufvals.length() <= max(x, y)) ufvals.add(); x = compressfind(x); y = compressfind(y); if(x==y) return; ufval &xval = ufvals[x], &yval = ufvals[y]; if(xval.rank < yval.rank) xval.next = y; else { yval.next = x; if(xval.rank==yval.rank) yval.rank++; } } }; template struct ringbuf { int index, len; T data[SIZE]; ringbuf() { clear(); } void clear() { index = len = 0; } bool empty() const { return !len; } const int length() const { return len; } T &add() { T &t = data[index]; index++; if(index >= SIZE) index -= SIZE; if(len < SIZE) len++; return t; } T &add(const T &e) { return add() = e; } T &operator[](int i) { i += index - len; return data[i < 0 ? i + SIZE : i%SIZE]; } const T &operator[](int i) const { i += index - len; return data[i < 0 ? i + SIZE : i%SIZE]; } }; template struct queue { int head, tail, len; T data[SIZE]; queue() { clear(); } void clear() { head = tail = len = 0; } int length() const { return len; } bool empty() const { return !len; } bool full() const { return len == SIZE; } T &added() { return data[tail > 0 ? tail-1 : SIZE-1]; } T &added(int offset) { return data[tail-offset > 0 ? tail-offset-1 : tail-offset-1 + SIZE]; } T &adding() { return data[tail]; } T &adding(int offset) { return data[tail+offset >= SIZE ? tail+offset - SIZE : tail+offset]; } T &add() { ASSERT(len < SIZE); T &t = data[tail]; tail = (tail + 1)%SIZE; len++; return t; } T &removing() { return data[head]; } T &removing(int offset) { return data[head+offset >= SIZE ? head+offset - SIZE : head+offset]; } T &remove() { ASSERT(len > 0); T &t = data[head]; head = (head + 1)%SIZE; len--; return t; } }; inline char *newstring(size_t l) { return new char[l+1]; } inline char *newstring(const char *s, size_t l) { return copystring(newstring(l), s, l+1); } inline char *newstring(const char *s) { return newstring(s, strlen(s)); } inline char *newstringbuf(const char *s) { return newstring(s, MAXSTRLEN-1); } const int islittleendian = 1; #ifdef SDL_BYTEORDER #define endianswap16 SDL_Swap16 #define endianswap32 SDL_Swap32 #define endianswap64 SDL_Swap64 #else inline ushort endianswap16(ushort n) { return (n<<8) | (n>>8); } inline uint endianswap32(uint n) { return (n<<24) | (n>>24) | ((n>>8)&0xFF00) | ((n<<8)&0xFF0000); } inline ullong endianswap64(ullong n) { return endianswap32(uint(n >> 32)) | ((ullong)endianswap32(uint(n)) << 32); } #endif template inline T endianswap(T n) { union { T t; uint i; } conv; conv.t = n; conv.i = endianswap32(conv.i); return conv.t; } template<> inline ushort endianswap(ushort n) { return endianswap16(n); } template<> inline short endianswap(short n) { return endianswap16(n); } template<> inline uint endianswap(uint n) { return endianswap32(n); } template<> inline int endianswap(int n) { return endianswap32(n); } template<> inline ullong endianswap(ullong n) { return endianswap64(n); } template<> inline llong endianswap(llong n) { return endianswap64(n); } template<> inline double endianswap(double n) { union { double t; uint i; } conv; conv.t = n; conv.i = endianswap64(conv.i); return conv.t; } template inline void endianswap(T *buf, int len) { for(T *end = &buf[len]; buf < end; buf++) *buf = endianswap(*buf); } template inline T endiansame(T n) { return n; } template inline void endiansame(T *buf, int len) {} #ifdef SDL_BYTEORDER #if SDL_BYTEORDER == SDL_LIL_ENDIAN #define lilswap endiansame #define bigswap endianswap #else #define lilswap endianswap #define bigswap endiansame #endif #else template inline T lilswap(T n) { return *(const uchar *)&islittleendian ? n : endianswap(n); } template inline void lilswap(T *buf, int len) { if(!*(const uchar *)&islittleendian) endianswap(buf, len); } template inline T bigswap(T n) { return *(const uchar *)&islittleendian ? endianswap(n) : n; } template inline void bigswap(T *buf, int len) { if(*(const uchar *)&islittleendian) endianswap(buf, len); } #endif /* workaround for some C platforms that have these two functions as macros - not used anywhere */ #ifdef getchar #undef getchar #endif #ifdef putchar #undef putchar #endif struct stream { #ifdef WIN32 #ifdef __GNUC__ typedef off64_t offset; #else typedef __int64 offset; #endif #else typedef off_t offset; #endif virtual ~stream() {} virtual void close() = 0; virtual bool end() = 0; virtual offset tell() { return -1; } virtual bool seek(offset pos, int whence = SEEK_SET) { return false; } virtual offset size(); virtual int read(void *buf, int len) { return 0; } virtual int write(const void *buf, int len) { return 0; } virtual int getchar() { uchar c; return read(&c, 1) == 1 ? c : -1; } virtual bool putchar(int n) { uchar c = n; return write(&c, 1) == 1; } virtual bool getline(char *str, int len); virtual bool putstring(const char *str) { int len = (int)strlen(str); return write(str, len) == len; } virtual bool putline(const char *str) { return putstring(str) && putchar('\n'); } virtual int printf(const char *fmt, ...); virtual uint getcrc() { return 0; } template bool put(T n) { return write(&n, sizeof(n)) == sizeof(n); } template bool putlil(T n) { return put(lilswap(n)); } template bool putbig(T n) { return put(bigswap(n)); } template T get() { T n; return read(&n, sizeof(n)) == sizeof(n) ? n : 0; } template T getlil() { return lilswap(get()); } template T getbig() { return bigswap(get()); } #ifndef STANDALONE SDL_RWops *rwops(); #endif }; extern int iscubeprint(int c); extern int uni2cube(int c); extern int cube2uni(int c); extern int decodeutf8(uchar *dst, uchar *src, int len, int *carry = NULL); extern int encodeutf8(uchar *dstbuf, int dstlen, uchar *srcbuf, int srclen, int *carry = NULL); extern char *makerelpath(const char *dir, const char *file, const char *prefix = NULL, const char *cmd = NULL); extern char *path(char *s); extern char *path(const char *s, bool copy); extern const char *parentdir(const char *directory); extern bool fileexists(const char *path, const char *mode); extern bool createdir(const char *path); extern bool isdir(char* path); //__offtools__ simple dir check extern size_t fixpackagedir(char *dir); extern const char *sethomedir(const char *dir); extern const char *addpackagedir(const char *dir); extern const char *findfile(const char *filename, const char *mode); extern stream *openrawfile(const char *filename, const char *mode); extern stream *openzipfile(const char *filename, const char *mode); extern stream *openfile(const char *filename, const char *mode); extern stream *opentempfile(const char *filename, const char *mode); extern stream *opengzfile(const char *filename, const char *mode, stream *file = NULL, int level = Z_BEST_COMPRESSION); extern stream *openutf8file(const char *filename, const char *mode, stream *file = NULL); extern char *loadfile(const char *fn, int *size, bool utf8 = true); extern bool listdir(const char *dir, bool rel, const char *ext, vector &files); extern int listfiles(const char *dir, const char *ext, vector &files); extern int listzipfiles(const char *dir, const char *ext, vector &files); extern void seedMT(uint seed); extern uint randomMT(void); #ifndef STANDALONE extern SDL_Surface *loadsurface(const char *name); #endif #endif sandboxgamemaker-2.7.1+dfsg/src/shared/zip.cpp0000664000175000017500000004322011601337414021216 0ustar showardshoward#include "cube.h" enum { ZIP_LOCAL_FILE_SIGNATURE = 0x04034B50, ZIP_LOCAL_FILE_SIZE = 30, ZIP_FILE_SIGNATURE = 0x02014B50, ZIP_FILE_SIZE = 46, ZIP_DIRECTORY_SIGNATURE = 0x06054B50, ZIP_DIRECTORY_SIZE = 22 }; struct ziplocalfileheader { uint signature; ushort version, flags, compression, modtime, moddate; uint crc32, compressedsize, uncompressedsize; ushort namelength, extralength; }; struct zipfileheader { uint signature; ushort version, needversion, flags, compression, modtime, moddate; uint crc32, compressedsize, uncompressedsize; ushort namelength, extralength, commentlength, disknumber, internalattribs; uint externalattribs, offset; }; struct zipdirectoryheader { uint signature; ushort disknumber, directorydisk, diskentries, entries; uint size, offset; ushort commentlength; }; struct zipfile { char *name; uint header, offset, size, compressedsize; zipfile() : name(NULL), header(0), offset(~0U), size(0), compressedsize(0) { } ~zipfile() { DELETEA(name); } }; struct zipstream; struct ziparchive { char *name; FILE *data; hashtable files; int openfiles; zipstream *owner; ziparchive() : name(NULL), data(NULL), files(512), openfiles(0), owner(NULL) { } ~ziparchive() { DELETEA(name); if(data) { fclose(data); data = NULL; } } }; static bool findzipdirectory(FILE *f, zipdirectoryheader &hdr) { if(fseek(f, 0, SEEK_END) < 0) return false; uchar buf[1024], *src = NULL; int len = 0, offset = ftell(f), end = max(offset - 0xFFFF - ZIP_DIRECTORY_SIZE, 0); const uint signature = lilswap(ZIP_DIRECTORY_SIGNATURE); while(offset > end) { int carry = min(len, ZIP_DIRECTORY_SIZE-1), next = min((int)sizeof(buf) - carry, offset - end); offset -= next; memmove(&buf[next], buf, carry); if(next + carry < ZIP_DIRECTORY_SIZE || fseek(f, offset, SEEK_SET) < 0 || (int)fread(buf, 1, next, f) != next) return false; len = next + carry; uchar *search = &buf[next-1]; for(; search >= buf; search--) if(*(uint *)search == signature) break; if(search >= buf) { src = search; break; } } if(&buf[len] - src < ZIP_DIRECTORY_SIZE) return false; hdr.signature = lilswap(*(uint *)src); src += 4; hdr.disknumber = lilswap(*(ushort *)src); src += 2; hdr.directorydisk = lilswap(*(ushort *)src); src += 2; hdr.diskentries = lilswap(*(ushort *)src); src += 2; hdr.entries = lilswap(*(ushort *)src); src += 2; hdr.size = lilswap(*(uint *)src); src += 4; hdr.offset = lilswap(*(uint *)src); src += 4; hdr.commentlength = lilswap(*(ushort *)src); src += 2; if(hdr.signature != ZIP_DIRECTORY_SIGNATURE || hdr.disknumber != hdr.directorydisk || hdr.diskentries != hdr.entries) return false; return true; } #ifndef STANDALONE VAR(dbgzip, 0, 0, 1); #endif static bool readzipdirectory(const char *archname, FILE *f, int entries, int offset, int size, vector &files) { uchar *buf = new uchar[size], *src = buf; if(fseek(f, offset, SEEK_SET) < 0 || (int)fread(buf, 1, size, f) != size) { delete[] buf; return false; } loopi(entries) { if(src + ZIP_FILE_SIZE > &buf[size]) break; zipfileheader hdr; hdr.signature = lilswap(*(uint *)src); src += 4; hdr.version = lilswap(*(ushort *)src); src += 2; hdr.needversion = lilswap(*(ushort *)src); src += 2; hdr.flags = lilswap(*(ushort *)src); src += 2; hdr.compression = lilswap(*(ushort *)src); src += 2; hdr.modtime = lilswap(*(ushort *)src); src += 2; hdr.moddate = lilswap(*(ushort *)src); src += 2; hdr.crc32 = lilswap(*(uint *)src); src += 4; hdr.compressedsize = lilswap(*(uint *)src); src += 4; hdr.uncompressedsize = lilswap(*(uint *)src); src += 4; hdr.namelength = lilswap(*(ushort *)src); src += 2; hdr.extralength = lilswap(*(ushort *)src); src += 2; hdr.commentlength = lilswap(*(ushort *)src); src += 2; hdr.disknumber = lilswap(*(ushort *)src); src += 2; hdr.internalattribs = lilswap(*(ushort *)src); src += 2; hdr.externalattribs = lilswap(*(uint *)src); src += 4; hdr.offset = lilswap(*(uint *)src); src += 4; if(hdr.signature != ZIP_FILE_SIGNATURE) break; if(!hdr.namelength || !hdr.uncompressedsize || (hdr.compression && (hdr.compression != Z_DEFLATED || !hdr.compressedsize))) { src += hdr.namelength + hdr.extralength + hdr.commentlength; continue; } if(src + hdr.namelength > &buf[size]) break; string pname; int namelen = min((int)hdr.namelength, (int)sizeof(pname)-1); memcpy(pname, src, namelen); pname[namelen] = '\0'; path(pname); char *name = newstring(pname); zipfile &f = files.add(); f.name = name; f.header = hdr.offset; f.size = hdr.uncompressedsize; f.compressedsize = hdr.compression ? hdr.compressedsize : 0; #ifndef STANDALONE if(dbgzip) conoutf(CON_DEBUG, "file %s, size %d, compress %d, flags %x", archname, name, hdr.uncompressedsize, hdr.compression, hdr.flags); #endif src += hdr.namelength + hdr.extralength + hdr.commentlength; } delete[] buf; return files.length() > 0; } static bool readlocalfileheader(FILE *f, ziplocalfileheader &h, uint offset) { fseek(f, offset, SEEK_SET); uchar buf[ZIP_LOCAL_FILE_SIZE]; if(fread(buf, 1, ZIP_LOCAL_FILE_SIZE, f) != ZIP_LOCAL_FILE_SIZE) return false; uchar *src = buf; h.signature = lilswap(*(uint *)src); src += 4; h.version = lilswap(*(ushort *)src); src += 2; h.flags = lilswap(*(ushort *)src); src += 2; h.compression = lilswap(*(ushort *)src); src += 2; h.modtime = lilswap(*(ushort *)src); src += 2; h.moddate = lilswap(*(ushort *)src); src += 2; h.crc32 = lilswap(*(uint *)src); src += 4; h.compressedsize = lilswap(*(uint *)src); src += 4; h.uncompressedsize = lilswap(*(uint *)src); src += 4; h.namelength = lilswap(*(ushort *)src); src += 2; h.extralength = lilswap(*(ushort *)src); src += 2; if(h.signature != ZIP_LOCAL_FILE_SIGNATURE) return false; // h.uncompressedsize or h.compressedsize may be zero - so don't validate return true; } static vector archives; ziparchive *findzip(const char *name) { loopv(archives) if(!strcmp(name, archives[i]->name)) return archives[i]; return NULL; } static bool checkprefix(vector &files, const char *prefix, int prefixlen) { loopv(files) { if(!strncmp(files[i].name, prefix, prefixlen)) return false; } return true; } static void mountzip(ziparchive &arch, vector &files, const char *mountdir, const char *stripdir) { string packagesdir = "packages/"; path(packagesdir); int striplen = stripdir ? (int)strlen(stripdir) : 0; if(!mountdir && !stripdir) loopv(files) { zipfile &f = files[i]; const char *foundpackages = strstr(f.name, packagesdir); if(foundpackages) { if(foundpackages > f.name) { stripdir = f.name; striplen = foundpackages - f.name; } break; } const char *foundogz = strstr(f.name, ".ogz"); if(foundogz) { const char *ogzdir = foundogz; while(--ogzdir >= f.name && *ogzdir != PATHDIV); if(ogzdir < f.name || checkprefix(files, f.name, ogzdir + 1 - f.name)) { if(ogzdir >= f.name) { stripdir = f.name; striplen = ogzdir + 1 - f.name; } if(!mountdir) mountdir = "packages/base/"; break; } } } string mdir = "", fname; if(mountdir) { copystring(mdir, mountdir); if(fixpackagedir(mdir) <= 1) mdir[0] = '\0'; } loopv(files) { zipfile &f = files[i]; formatstring(fname)("%s%s", mdir, striplen && !strncmp(f.name, stripdir, striplen) ? &f.name[striplen] : f.name); if(arch.files.access(fname)) continue; char *mname = newstring(fname); zipfile &mf = arch.files[mname]; mf = f; mf.name = mname; } } bool addzip(const char *name, const char *mount = NULL, const char *strip = NULL) { string pname; copystring(pname, name); path(pname); int plen = (int)strlen(pname); if(plen < 4 || !strchr(&pname[plen-4], '.')) concatstring(pname, ".zip"); ziparchive *exists = findzip(pname); if(exists) { conoutf(CON_ERROR, "already added zip %s", pname); return true; } FILE *f = fopen(findfile(pname, "rb"), "rb"); if(!f) { conoutf(CON_ERROR, "could not open file %s", pname); return false; } zipdirectoryheader h; vector files; if(!findzipdirectory(f, h) || !readzipdirectory(pname, f, h.entries, h.offset, h.size, files)) { conoutf(CON_ERROR, "could not read directory in zip %s", pname); fclose(f); return false; } ziparchive *arch = new ziparchive; arch->name = newstring(pname); arch->data = f; mountzip(*arch, files, mount, strip); archives.add(arch); conoutf("added zip %s", pname); return true; } bool removezip(const char *name) { string pname; copystring(pname, name); path(pname); int plen = (int)strlen(pname); if(plen < 4 || !strchr(&pname[plen-4], '.')) concatstring(pname, ".zip"); ziparchive *exists = findzip(pname); if(!exists) { conoutf(CON_ERROR, "zip %s is not loaded", pname); return false; } if(exists->openfiles) { conoutf(CON_ERROR, "zip %s has open files", pname); return false; } conoutf("removed zip %s", exists->name); archives.removeobj(exists); delete exists; return true; } struct zipstream : stream { enum { BUFSIZE = 16384 }; ziparchive *arch; zipfile *info; z_stream zfile; uchar *buf; int reading; bool ended; zipstream() : arch(NULL), info(NULL), buf(NULL), reading(-1), ended(false) { zfile.zalloc = NULL; zfile.zfree = NULL; zfile.opaque = NULL; zfile.next_in = zfile.next_out = NULL; zfile.avail_in = zfile.avail_out = 0; } ~zipstream() { close(); } void readbuf(uint size = BUFSIZE) { if(!zfile.avail_in) zfile.next_in = (Bytef *)buf; size = min(size, uint(&buf[BUFSIZE] - &zfile.next_in[zfile.avail_in])); if(arch->owner != this) { arch->owner = NULL; if(fseek(arch->data, reading, SEEK_SET) >= 0) arch->owner = this; else return; } uint remaining = info->offset + info->compressedsize - reading; int n = arch->owner == this ? (int)fread(zfile.next_in + zfile.avail_in, 1, min(size, remaining), arch->data) : 0; zfile.avail_in += n; reading += n; } bool open(ziparchive *a, zipfile *f) { if(f->offset == ~0U) { ziplocalfileheader h; a->owner = NULL; if(!readlocalfileheader(a->data, h, f->header)) return false; f->offset = f->header + ZIP_LOCAL_FILE_SIZE + h.namelength + h.extralength; } if(f->compressedsize && inflateInit2(&zfile, -MAX_WBITS) != Z_OK) return false; a->openfiles++; arch = a; info = f; reading = f->offset; ended = false; if(f->compressedsize) buf = new uchar[BUFSIZE]; return true; } void stopreading() { if(reading < 0) return; #ifndef STANDALONE if(dbgzip) conoutf(CON_DEBUG, info->compressedsize ? "%s: zfile.total_out %d, info->size %d" : "%s: reading %d, info->size %d", info->name, info->compressedsize ? zfile.total_out : reading - info->offset, info->size); #endif if(info->compressedsize) inflateEnd(&zfile); reading = -1; } void close() { stopreading(); DELETEA(buf); if(arch) { arch->owner = NULL; arch->openfiles--; arch = NULL; } } offset size() { return info->size; } bool end() { return reading < 0 || ended; } offset tell() { return reading >= 0 ? (info->compressedsize ? zfile.total_out : reading - info->offset) : -1; } bool seek(offset pos, int whence) { if(reading < 0) return false; if(!info->compressedsize) { switch(whence) { case SEEK_END: pos += info->offset + info->size; break; case SEEK_CUR: pos += reading; break; case SEEK_SET: pos += info->offset; break; default: return false; } pos = clamp(pos, offset(info->offset), offset(info->offset + info->size)); arch->owner = NULL; if(fseek(arch->data, int(pos), SEEK_SET) < 0) return false; arch->owner = this; reading = pos; ended = false; return true; } switch(whence) { case SEEK_END: pos += info->size; break; case SEEK_CUR: pos += zfile.total_out; break; case SEEK_SET: break; default: return false; } if(pos >= (offset)info->size) { reading = info->offset + info->compressedsize; zfile.next_in += zfile.avail_in; zfile.avail_in = 0; zfile.total_in = info->compressedsize; arch->owner = NULL; ended = false; return true; } if(pos < 0) return false; if(pos >= (offset)zfile.total_out) pos -= zfile.total_out; else { if(zfile.next_in && zfile.total_in <= uint(zfile.next_in - buf)) { zfile.avail_in += zfile.total_in; zfile.next_in -= zfile.total_in; } else { arch->owner = NULL; zfile.avail_in = 0; zfile.next_in = NULL; reading = info->offset; } inflateReset(&zfile); } uchar skip[512]; while(pos > 0) { int skipped = (int)min(pos, (offset)sizeof(skip)); if(read(skip, skipped) != skipped) return false; pos -= skipped; } ended = false; return true; } int read(void *buf, int len) { if(reading < 0 || !buf || !len) return 0; if(!info->compressedsize) { if(arch->owner != this) { arch->owner = NULL; if(fseek(arch->data, reading, SEEK_SET) < 0) { stopreading(); return 0; } arch->owner = this; } int n = (int)fread(buf, 1, min(len, int(info->size + info->offset - reading)), arch->data); reading += n; if(n < len) ended = true; return n; } zfile.next_out = (Bytef *)buf; zfile.avail_out = len; while(zfile.avail_out > 0) { if(!zfile.avail_in) readbuf(BUFSIZE); int err = inflate(&zfile, Z_NO_FLUSH); if(err != Z_OK) { if(err == Z_STREAM_END) ended = true; else { #ifndef STANDALONE if(dbgzip) conoutf(CON_DEBUG, "inflate error: %s", err); #endif stopreading(); } break; } } return len - zfile.avail_out; } }; stream *openzipfile(const char *name, const char *mode) { for(; *mode; mode++) if(*mode=='w' || *mode=='a') return NULL; loopvrev(archives) { ziparchive *arch = archives[i]; zipfile *f = arch->files.access(name); if(!f) continue; zipstream *s = new zipstream; if(s->open(arch, f)) return s; delete s; } return NULL; } int listzipfiles(const char *dir, const char *ext, vector &files) { int extsize = ext ? (int)strlen(ext)+1 : 0, dirsize = (int)strlen(dir), dirs = 0; loopvrev(archives) { ziparchive *arch = archives[i]; int oldsize = files.length(); enumerate(arch->files, zipfile, f, { if(strncmp(f.name, dir, dirsize)) continue; const char *name = f.name + dirsize; if(name[0] == PATHDIV) name++; if(strchr(name, PATHDIV)) continue; if(!ext) files.add(newstring(name)); else { int namelength = (int)strlen(name) - extsize; if(namelength > 0 && name[namelength] == '.' && strncmp(name+namelength+1, ext, extsize-1)==0) files.add(newstring(name, namelength)); } }); if(files.length() > oldsize) dirs++; } return dirs; } #ifndef STANDALONE ICOMMAND(addzip, "sss", (const char *name, const char *mount, const char *strip), addzip(name, mount[0] ? mount : NULL, strip[0] ? strip : NULL)); ICOMMAND(removezip, "s", (const char *name), removezip(name)); #endif sandboxgamemaker-2.7.1+dfsg/src/Makefile0000664000175000017500000011667711655776736020152 0ustar showardshoward DEFINES = MACHINENAME= CXXFLAGS= -O2 -fomit-frame-pointer $(DEFINES) override CXXFLAGS+= -Wall -fsigned-char -fno-exceptions -fno-rtti PLATFORM= $(shell uname -s) PLATFORM_PREFIX=sandbox INCLUDES= -Ishared -Iengine -Ienet/include STRIP= ifeq (,$(findstring -g,$(CXXFLAGS))) ifeq (,$(findstring -pg,$(CXXFLAGS))) STRIP=strip endif endif MV=mv ifneq (,$(findstring MINGW,$(PLATFORM))) WINDRES= windres CLIENT_INCLUDES= $(INCLUDES) -Iinclude CLIENT_LIBS= -mwindows -Llib -lSDL -lSDL_image -lSDL_mixer -lzdll -lopengl32 -lenet -lws2_32 -lwinmm else CLIENT_INCLUDES= $(INCLUDES) -I/usr/X11R6/include `sdl-config --cflags` CLIENT_LIBS= -Lenet/.libs -lenet -L/usr/X11R6/lib `sdl-config --libs` -lSDL_image -lSDL_mixer -lz -lGL -lX11 endif ifeq ($(PLATFORM),Linux) CLIENT_LIBS+= -lrt ifneq (,$(findstring _64,$(shell uname -m))) MACHINENAME=64 else MACHINENAME=32 endif endif CLIENT_OBJS= \ shared/crypto.o \ shared/geom.o \ shared/stream.o \ shared/tools.o \ shared/zip.o \ engine/3dgui.o \ engine/bih.o \ engine/blend.o \ engine/blob.o \ engine/client.o \ engine/command.o \ engine/console.o \ engine/decal.o \ engine/dynlight.o \ engine/glare.o \ engine/grass.o \ engine/lightmap.o \ engine/main.o \ engine/material.o \ engine/menus.o \ engine/movie.o \ engine/normal.o \ engine/octa.o \ engine/octaedit.o \ engine/octarender.o \ engine/pvs.o \ engine/physics.o \ engine/rendergl.o \ engine/rendermodel.o \ engine/renderparticles.o \ engine/rendersky.o \ engine/rendertext.o \ engine/renderva.o \ engine/server.o \ engine/serverbrowser.o \ engine/shader.o \ engine/shadowmap.o \ engine/sound.o \ engine/texture.o \ engine/ui.o \ engine/water.o \ engine/world.o \ engine/worldio.o FPSCLIENT_OBJS = \ fpsgame/ai.o \ fpsgame/client.o \ fpsgame/entities.o \ fpsgame/fps.o \ fpsgame/monster.o \ fpsgame/movable.o \ fpsgame/render.o \ fpsgame/scoreboard.o \ fpsgame/server.o \ fpsgame/waypoint.o SSPCLIENT_OBJS = \ sspgame/ssp.o \ sspgame/sspent.o \ sspgame/sspentities.o \ sspgame/sspweapons.o \ sspgame/sspmonster.o \ sspgame/ssprender.o \ sspgame/sspstubs.o RPGCLIENT_OBJS = \ rpggame/rpg.o \ rpggame/rpgai.o \ rpggame/rpgaction.o \ rpggame/rpgcamera.o \ rpggame/rpgchar.o \ rpggame/rpgconfig.o \ rpggame/rpgcontainer.o \ rpggame/rpgeffect.o \ rpggame/rpgentities.o \ rpggame/rpghud.o \ rpggame/rpggui.o \ rpggame/rpgio.o \ rpggame/rpgitem.o \ rpggame/rpgobstacle.o \ rpggame/rpgplatform.o \ rpggame/rpgproj.o \ rpggame/rpgscript.o \ rpggame/rpgstats.o \ rpggame/rpgstatus.o \ rpggame/rpgstubs.o \ rpggame/rpgrender.o \ rpggame/rpgtest.o \ rpggame/rpgtrigger.o \ rpggame/waypoint.o MOVIECLIENT_OBJS= \ moviecube/action.o \ moviecube/characterinfo.o \ moviecube/client.o \ moviecube/clientmode.o \ moviecube/control.o \ moviecube/entities.o \ moviecube/mapentities.o \ moviecube/movable.o \ moviecube/moviecube.o \ moviecube/render.o \ moviecube/camera.o \ moviecube/server.o KRSCLIENT_OBJS = \ krsgame/krs.o \ krsgame/krsai.o \ krsgame/krsents.o \ krsgame/krshud.o \ krsgame/krsrender.o \ krsgame/krsstubs.o \ krsgame/krsscript.o \ krsgame/waypoint.o PZLCLIENT_OBJS = \ pzlgame/pzl.o \ pzlgame/pzlents.o \ pzlgame/pzlhud.o \ pzlgame/pzlrender.o \ pzlgame/pzlstubs.o \ pzlgame/pzlscript.o CLIENT_PCH = \ shared/cube.h.gch \ engine/engine.h.gch \ fpsgame/game.h.gch \ sspgame/sspgame.h.gch \ rpggame/rpggame.h.gch \ moviecube/game.h.gch \ krsgame/krsgame.h.gch \ pzlgame/pzlgame.h.gch ifneq (,$(findstring MINGW,$(PLATFORM))) SERVER_INCLUDES= -DSTANDALONE $(INCLUDES) -Iinclude SERVER_LIBS= -mwindows -Llib -lzdll -lenet -lws2_32 -lwinmm MASTER_LIBS= -Llib -lzdll -lenet -lws2_32 -lwinmm else SERVER_INCLUDES= -DSTANDALONE $(INCLUDES) SERVER_LIBS= -Lenet/.libs -lenet -lz MASTER_LIBS= $(SERVER_LIBS) endif SERVER_OBJS= \ shared/crypto-standalone.o \ shared/stream-standalone.o \ shared/tools-standalone.o \ engine/command-standalone.o \ engine/server-standalone.o \ engine/worldio-standalone.o FPSSERVER_OBJS = \ fpsgame/entities-standalone.o \ fpsgame/server-standalone.o MOVIESERVER_OBJS= \ moviecube/server-standalone.o \ moviecube/entities-standalone.o MASTER_OBJS= \ shared/crypto-standalone.o \ shared/stream-standalone.o \ shared/tools-standalone.o \ engine/command-standalone.o \ engine/master-standalone.o LAUNCHER_LIBS= `wx-config --libs` LAUNCHER_FLAGS= `wx-config --cxxflags` LAUNCHER_OBJS= \ launcher/pasl.o \ launcher/paslapp.o ifeq ($(PLATFORM),SunOS) CLIENT_LIBS+= -lsocket -lnsl -lX11 SERVER_LIBS+= -lsocket -lnsl endif default: all $(LAUNCHER_OBJS): CXXFLAGS += $(LAUNCHER_FLAGS) pasl: $(LAUNCHER_OBJS) $(CXX) $(CXXFLAGS) -o launch $(LAUNCHER_OBJS) $(LAUNCHER_LIBS) cp launch ../launcher strip ../launcher chmod +x ../launcher all: client server enet/Makefile: cd enet; ./configure --enable-shared=no --enable-static=yes libenet: enet/Makefile $(MAKE) -C enet/ all clean-enet: enet/Makefile $(MAKE) -C enet/ clean clean: -$(RM) $(SERVER_OBJS) $(FPSSERVER_OBJS) $(MOVIESERVER_OBJS) $(CLIENT_PCH) $(CLIENT_OBJS) $(SSPCLIENT_OBJS) $(RPGCLIENT_OBJS) $(FPSCLIENT_OBJS) $(MOVIECLIENT_OBJS) $(KRSCLIENT_OBJS) $(PZLCLIENT_OBJS) $(LAUNCHER_OBJS) $(MASTER_OBJS) $(PLATFORM_PREFIX)_server_* $(PLATFORM_PREFIX)_client_* %.h.gch: %.h $(CXX) $(CXXFLAGS) -o $@.tmp $(subst .h.gch,.h,$@) $(MV) $@.tmp $@ %-standalone.o: %.cpp $(CXX) $(CXXFLAGS) -c -o $@ $(subst -standalone.o,.cpp,$@) $(CLIENT_OBJS): CXXFLAGS += $(CLIENT_INCLUDES) $(filter shared/%,$(CLIENT_OBJS)): $(filter shared/%,$(CLIENT_PCH)) $(filter engine/%,$(CLIENT_OBJS)): $(filter engine/%,$(CLIENT_PCH)) $(SSPCLIENT_OBJS): CXXFLAGS += $(CLIENT_INCLUDES) -Isspgame $(SSPCLIENT_OBJS): $(filter sspgame/%,$(CLIENT_PCH)) $(FPSCLIENT_OBJS): CXXFLAGS += $(CLIENT_INCLUDES) -Ifpsgame $(FPSCLIENT_OBJS): $(filter fpsgame/%,$(CLIENT_PCH)) $(RPGCLIENT_OBJS): CXXFLAGS += $(CLIENT_INCLUDES) -Irpggame $(RPGCLIENT_OBJS): $(filter rpggame/%,$(CLIENT_PCH)) $(MOVIECLIENT_OBJS): CXXFLAGS += $(CLIENT_INCLUDES) -Imoviecube $(MOVIECLIENT_OBJS): $(filter moviecube/%,$(CLIENT_PCH)) $(KRSCLIENT_OBJS): CXXFLAGS += $(CLIENT_INCLUDES) -Ikrsgame $(KRSCLIENT_OBJS): $(filter krsgame/%,$(CLIENT_PCH)) $(PZLCLIENT_OBJS): CXXFLAGS += $(CLIENT_INCLUDES) -Ipzlgame $(PZLCLIENT_OBJS): $(filter pzlgame/%,$(CLIENT_PCH)) $(SERVER_OBJS): CXXFLAGS += $(SERVER_INCLUDES) $(filter-out $(SERVER_OBJS),$(MASTER_OBJS)): CXXFLAGS += $(SERVER_INCLUDES) $(FPSSERVER_OBJS): CXXFLAGS += -Ifpsgame $(SERVER_INCLUDES) $(MOVIESERVER_OBJS): CXXFLAGS += -Imoviecube $(SERVER_INCLUDES) client: client-fps client-krs client-movie client-rpg client-ssp #client-pzl server: server-fps server-movie ifneq (,$(findstring MINGW,$(PLATFORM))) client-fps:$(CLIENT_OBJS) $(FPSCLIENT_OBJS) $(WINDRES) -I windows/resources -i windows/resources/fps.rc -J rc -o windows/resources/fps.res -O coff $(CXX) $(CXXFLAGS) -o ../bin/sandbox_fps.exe windows/resources/fps.res $(CLIENT_OBJS) $(FPSCLIENT_OBJS) $(CLIENT_LIBS) client-ssp:$(CLIENT_OBJS) $(SSPCLIENT_OBJS) $(WINDRES) -I windows/resources -i windows/resources/ssp.rc -J rc -o windows/resources/ssp.res -O coff $(CXX) $(CXXFLAGS) -o ../bin/sandbox_ssp.exe windows/resources/ssp.res $(CLIENT_OBJS) $(SSPCLIENT_OBJS) $(CLIENT_LIBS) client-rpg:$(CLIENT_OBJS) $(RPGCLIENT_OBJS) $(WINDRES) -I windows/resources -i windows/resources/rpg.rc -J rc -o windows/resources/rpg.res -O coff $(CXX) $(CXXFLAGS) -o ../bin/sandbox_rpg.exe windows/resources/rpg.res $(CLIENT_OBJS) $(RPGCLIENT_OBJS) $(CLIENT_LIBS) client-movie:$(CLIENT_OBJS) $(MOVIECLIENT_OBJS) $(WINDRES) -I windows/resources -i windows/resources/mc.rc -J rc -o windows/resources/mc.res -O coff $(CXX) $(CXXFLAGS) -o ../bin/sandbox_movie.exe windows/resources/mc.res $(CLIENT_OBJS) $(MOVIECLIENT_OBJS) $(CLIENT_LIBS) client-krs:$(CLIENT_OBJS) $(KRSCLIENT_OBJS) $(WINDRES) -I windows/resources -i windows/resources/krs.rc -J rc -o windows/resources/krs.res -O coff $(CXX) $(CXXFLAGS) -o ../bin/sandbox_krs.exe windows/resources/krs.res $(CLIENT_OBJS) $(KRSCLIENT_OBJS) $(CLIENT_LIBS) client-pzl:$(CLIENT_OBJS) $(PZLCLIENT_OBJS) $(WINDRES) -I windows/resources -i windows/resources/pzl.rc -J rc -o windows/resources/pzl.res -O coff $(CXX) $(CXXFLAGS) -o ../bin/sandbox_pzl.exe windows/resources/pzl.res $(CLIENT_OBJS) $(PZLCLIENT_OBJS) $(CLIENT_LIBS) server-fps:$(SERVER_OBJS) $(FPSSERVEROBJS) $(WINDRES) -I windows/resources -i windows/resources/fps.rc -J rc -o windows/resources/fps.res -O coff $(CXX) $(CXXFLAGS) -o ../bin/sandbox_server_fps.exe windows/resources/fps.res $(SERVER_OBJS) $(FPSSERVER_OBJS) $(SERVER_LIBS) server-movie: $(SERVER_OBJS) $(MOVIESERVER_OBJS) $(WINDRES) -I windows/resources -i windows/resources/mc.rc -J rc -o windows/resources/mc.res -O coff $(CXX) $(CXXFLAGS) -o ../bin/sandbox_server_movie.exe windows/resources/mc.res $(SERVER_OBJS) $(MOVIESERVER_OBJS) $(SERVER_LIBS) master: $(MASTER_OBJS) $(CXX) $(CXXFLAGS) -o ../bin/sandbox_master.exe $(MASTER_OBJS) $(MASTER_LIBS) install: all else client-fps:libenet $(CLIENT_OBJS) $(FPSCLIENT_OBJS) $(CXX) $(CXXFLAGS) -o $(PLATFORM_PREFIX)_client_$(MACHINENAME)_fps $(CLIENT_OBJS) $(FPSCLIENT_OBJS) $(CLIENT_LIBS) client-ssp:libenet $(CLIENT_OBJS) $(SSPCLIENT_OBJS) $(CXX) $(CXXFLAGS) -o $(PLATFORM_PREFIX)_client_$(MACHINENAME)_ssp $(CLIENT_OBJS) $(SSPCLIENT_OBJS) $(CLIENT_LIBS) client-rpg:libenet $(CLIENT_OBJS) $(RPGCLIENT_OBJS) $(CXX) $(CXXFLAGS) -o $(PLATFORM_PREFIX)_client_$(MACHINENAME)_rpg $(CLIENT_OBJS) $(RPGCLIENT_OBJS) $(CLIENT_LIBS) client-movie:libenet $(CLIENT_OBJS) $(MOVIECLIENT_OBJS) $(CXX) $(CXXFLAGS) -o $(PLATFORM_PREFIX)_client_$(MACHINENAME)_movie $(CLIENT_OBJS) $(MOVIECLIENT_OBJS) $(CLIENT_LIBS) client-krs:libenet $(CLIENT_OBJS) $(KRSCLIENT_OBJS) $(CXX) $(CXXFLAGS) -o $(PLATFORM_PREFIX)_client_$(MACHINENAME)_krs $(CLIENT_OBJS) $(KRSCLIENT_OBJS) $(CLIENT_LIBS) client-pzl:libenet $(CLIENT_OBJS) $(PZLCLIENT_OBJS) $(CXX) $(CXXFLAGS) -o $(PLATFORM_PREFIX)_client_$(MACHINENAME)_pzl $(CLIENT_OBJS) $(PZLCLIENT_OBJS) $(CLIENT_LIBS) server-fps: libenet $(SERVER_OBJS) $(FPSSERVER_OBJS) $(CXX) $(CXXFLAGS) -o $(PLATFORM_PREFIX)_server_$(MACHINENAME)_fps $(SERVER_OBJS) $(FPSSERVER_OBJS) $(SERVER_LIBS) server-movie: libenet $(SERVER_OBJS) $(MOVIESERVER_OBJS) $(CXX) $(CXXFLAGS) -o $(PLATFORM_PREFIX)_server_$(MACHINENAME)_movie $(SERVER_OBJS) $(MOVIESERVER_OBJS) $(SERVER_LIBS) master: libenet $(MASTER_OBJS) $(CXX) $(CXXFLAGS) -o $(PLATFORM_PREFIX)_master $(MASTER_OBJS) $(MASTER_LIBS) install: all cp $(PLATFORM_PREFIX)_* ../bin/ ifneq (,$(STRIP)) strip ../bin/$(PLATFORM_PREFIX)_??????_$(MACHINENAME)* endif chmod +x ../bin/$(PLATFORM_PREFIX)_??????_$(MACHINENAME)* endif shared/cube2font.o: shared/cube2font.c $(CXX) $(CXXFLAGS) -c -o $@ $< `freetype-config --cflags` cube2font: shared/cube2font.o $(CXX) $(CXXFLAGS) -o cube2font shared/cube2font.o `freetype-config --libs` -lz -lpng depend: makedepend -Y -Ishared -Iengine -Ifpsgame -Isspgame $(subst .o,.cpp,$(CLIENT_OBJS)) makedepend -a -o.h.gch -Y -Ishared -Iengine -Ifpsgame $(subst .h.gch,.h,$(CLIENT_PCH)) makedepend -a -o-standalone.o -Y -Ishared -Iengine -Ifpsgame -Isspgame $(subst -standalone.o,.cpp,$(SERVER_OBJS)) makedepend -a -o-standalone.o -Y -Ishared -Iengine -Ifpsgame $(subst -standalone.o,.cpp,$(filter-out $(SERVER_OBJS), $(MASTER_OBJS))) engine/engine.h.gch: shared/cube.h.gch fpsgame/game.h.gch: shared/cube.h.gch # DO NOT DELETE shared/crypto.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h shared/crypto.o: shared/command.h shared/iengine.h shared/igame.h shared/geom.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h shared/geom.o: shared/command.h shared/iengine.h shared/igame.h shared/stream.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h shared/stream.o: shared/command.h shared/iengine.h shared/igame.h shared/tools.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h shared/tools.o: shared/command.h shared/iengine.h shared/igame.h shared/zip.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h shared/zip.o: shared/command.h shared/iengine.h shared/igame.h engine/3dgui.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/3dgui.o: shared/ents.h shared/command.h shared/iengine.h engine/3dgui.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/3dgui.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/3dgui.o: engine/textedit.h engine/bih.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/bih.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h engine/bih.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h engine/bih.o: engine/texture.h engine/model.h engine/varray.h engine/blend.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/blend.o: shared/ents.h shared/command.h shared/iengine.h engine/blend.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/blend.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/blob.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/blob.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h engine/blob.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h engine/blob.o: engine/texture.h engine/model.h engine/varray.h engine/client.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/client.o: shared/ents.h shared/command.h shared/iengine.h engine/client.o: shared/igame.h engine/world.h engine/octa.h engine/client.o: engine/lightmap.h engine/bih.h engine/texture.h engine/client.o: engine/model.h engine/varray.h engine/command.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/command.o: shared/ents.h shared/command.h shared/iengine.h engine/command.o: shared/igame.h engine/world.h engine/octa.h engine/command.o: engine/lightmap.h engine/bih.h engine/texture.h engine/command.o: engine/model.h engine/varray.h engine/console.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/console.o: shared/ents.h shared/command.h shared/iengine.h engine/console.o: shared/igame.h engine/world.h engine/octa.h engine/console.o: engine/lightmap.h engine/bih.h engine/texture.h engine/console.o: engine/model.h engine/varray.h engine/decal.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/decal.o: shared/ents.h shared/command.h shared/iengine.h engine/decal.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/decal.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/dynlight.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/dynlight.o: shared/ents.h shared/command.h shared/iengine.h engine/dynlight.o: shared/igame.h engine/world.h engine/octa.h engine/dynlight.o: engine/lightmap.h engine/bih.h engine/texture.h engine/dynlight.o: engine/model.h engine/varray.h engine/glare.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/glare.o: shared/ents.h shared/command.h shared/iengine.h engine/glare.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/glare.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/glare.o: engine/rendertarget.h engine/grass.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/grass.o: shared/ents.h shared/command.h shared/iengine.h engine/grass.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/grass.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/lightmap.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/lightmap.o: shared/ents.h shared/command.h shared/iengine.h engine/lightmap.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.o: engine/lightmap.h engine/bih.h engine/texture.h engine/lightmap.o: engine/model.h engine/varray.h engine/main.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/main.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h engine/main.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h engine/main.o: engine/texture.h engine/model.h engine/varray.h engine/material.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/material.o: shared/ents.h shared/command.h shared/iengine.h engine/material.o: shared/igame.h engine/world.h engine/octa.h engine/material.o: engine/lightmap.h engine/bih.h engine/texture.h engine/material.o: engine/model.h engine/varray.h engine/menus.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/menus.o: shared/ents.h shared/command.h shared/iengine.h engine/menus.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/menus.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/movie.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/movie.o: shared/ents.h shared/command.h shared/iengine.h engine/movie.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/movie.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/normal.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/normal.o: shared/ents.h shared/command.h shared/iengine.h engine/normal.o: shared/igame.h engine/world.h engine/octa.h engine/normal.o: engine/lightmap.h engine/bih.h engine/texture.h engine/normal.o: engine/model.h engine/varray.h engine/octa.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/octa.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h engine/octa.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h engine/octa.o: engine/texture.h engine/model.h engine/varray.h engine/octaedit.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/octaedit.o: shared/ents.h shared/command.h shared/iengine.h engine/octaedit.o: shared/igame.h engine/world.h engine/octa.h engine/octaedit.o: engine/lightmap.h engine/bih.h engine/texture.h engine/octaedit.o: engine/model.h engine/varray.h engine/octarender.o: engine/engine.h shared/cube.h shared/tools.h engine/octarender.o: shared/geom.h shared/ents.h shared/command.h engine/octarender.o: shared/iengine.h shared/igame.h engine/world.h engine/octarender.o: engine/octa.h engine/lightmap.h engine/bih.h engine/octarender.o: engine/texture.h engine/model.h engine/varray.h engine/physics.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/physics.o: shared/ents.h shared/command.h shared/iengine.h engine/physics.o: shared/igame.h engine/world.h engine/octa.h engine/physics.o: engine/lightmap.h engine/bih.h engine/texture.h engine/physics.o: engine/model.h engine/varray.h engine/mpr.h engine/pvs.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/pvs.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h engine/pvs.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h engine/pvs.o: engine/texture.h engine/model.h engine/varray.h engine/rendergl.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/rendergl.o: shared/ents.h shared/command.h shared/iengine.h engine/rendergl.o: shared/igame.h engine/world.h engine/octa.h engine/rendergl.o: engine/lightmap.h engine/bih.h engine/texture.h engine/rendergl.o: engine/model.h engine/varray.h engine/rendermodel.o: engine/engine.h shared/cube.h shared/tools.h engine/rendermodel.o: shared/geom.h shared/ents.h shared/command.h engine/rendermodel.o: shared/iengine.h shared/igame.h engine/world.h engine/rendermodel.o: engine/octa.h engine/lightmap.h engine/bih.h engine/rendermodel.o: engine/texture.h engine/model.h engine/varray.h engine/rendermodel.o: engine/ragdoll.h engine/animmodel.h engine/vertmodel.h engine/rendermodel.o: engine/skelmodel.h engine/md2.h engine/md3.h engine/rendermodel.o: engine/md5.h engine/obj.h engine/smd.h engine/renderparticles.o: engine/engine.h shared/cube.h shared/tools.h engine/renderparticles.o: shared/geom.h shared/ents.h shared/command.h engine/renderparticles.o: shared/iengine.h shared/igame.h engine/world.h engine/renderparticles.o: engine/octa.h engine/lightmap.h engine/bih.h engine/renderparticles.o: engine/texture.h engine/model.h engine/varray.h engine/renderparticles.o: engine/rendertarget.h engine/depthfx.h engine/renderparticles.o: engine/explosion.h engine/lensflare.h engine/renderparticles.o: engine/lightning.h engine/rendersky.o: engine/engine.h shared/cube.h shared/tools.h engine/rendersky.o: shared/geom.h shared/ents.h shared/command.h engine/rendersky.o: shared/iengine.h shared/igame.h engine/world.h engine/rendersky.o: engine/octa.h engine/lightmap.h engine/bih.h engine/rendersky.o: engine/texture.h engine/model.h engine/varray.h engine/rendertext.o: engine/engine.h shared/cube.h shared/tools.h engine/rendertext.o: shared/geom.h shared/ents.h shared/command.h engine/rendertext.o: shared/iengine.h shared/igame.h engine/world.h engine/rendertext.o: engine/octa.h engine/lightmap.h engine/bih.h engine/rendertext.o: engine/texture.h engine/model.h engine/varray.h engine/renderva.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/renderva.o: shared/ents.h shared/command.h shared/iengine.h engine/renderva.o: shared/igame.h engine/world.h engine/octa.h engine/renderva.o: engine/lightmap.h engine/bih.h engine/texture.h engine/renderva.o: engine/model.h engine/varray.h engine/server.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/server.o: shared/ents.h shared/command.h shared/iengine.h engine/server.o: shared/igame.h engine/world.h engine/octa.h engine/server.o: engine/lightmap.h engine/bih.h engine/texture.h engine/server.o: engine/model.h engine/varray.h engine/serverbrowser.o: engine/engine.h shared/cube.h shared/tools.h engine/serverbrowser.o: shared/geom.h shared/ents.h shared/command.h engine/serverbrowser.o: shared/iengine.h shared/igame.h engine/world.h engine/serverbrowser.o: engine/octa.h engine/lightmap.h engine/bih.h engine/serverbrowser.o: engine/texture.h engine/model.h engine/varray.h engine/shader.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/shader.o: shared/ents.h shared/command.h shared/iengine.h engine/shader.o: shared/igame.h engine/world.h engine/octa.h engine/shader.o: engine/lightmap.h engine/bih.h engine/texture.h engine/shader.o: engine/model.h engine/varray.h engine/shadowmap.o: engine/engine.h shared/cube.h shared/tools.h engine/shadowmap.o: shared/geom.h shared/ents.h shared/command.h engine/shadowmap.o: shared/iengine.h shared/igame.h engine/world.h engine/shadowmap.o: engine/octa.h engine/lightmap.h engine/bih.h engine/shadowmap.o: engine/texture.h engine/model.h engine/varray.h engine/shadowmap.o: engine/rendertarget.h engine/sound.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/sound.o: shared/ents.h shared/command.h shared/iengine.h engine/sound.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/sound.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/texture.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/texture.o: shared/ents.h shared/command.h shared/iengine.h engine/texture.o: shared/igame.h engine/world.h engine/octa.h engine/texture.o: engine/lightmap.h engine/bih.h engine/texture.h engine/texture.o: engine/model.h engine/varray.h engine/scale.h engine/water.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/water.o: shared/ents.h shared/command.h shared/iengine.h engine/water.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/water.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/world.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/world.o: shared/ents.h shared/command.h shared/iengine.h engine/world.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/world.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/worldio.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/worldio.o: shared/ents.h shared/command.h shared/iengine.h engine/worldio.o: shared/igame.h engine/world.h engine/octa.h engine/worldio.o: engine/lightmap.h engine/bih.h engine/texture.h engine/worldio.o: engine/model.h engine/varray.h fpsgame/ai.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/ai.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h fpsgame/ai.o: fpsgame/ai.h fpsgame/client.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/client.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/client.o: shared/igame.h fpsgame/ai.h fpsgame/capture.h fpsgame/ctf.h fpsgame/entities.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/entities.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/entities.o: shared/igame.h fpsgame/ai.h fpsgame/fps.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/fps.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h fpsgame/fps.o: fpsgame/ai.h fpsgame/monster.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/monster.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/monster.o: shared/igame.h fpsgame/ai.h fpsgame/movable.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/movable.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/movable.o: shared/igame.h fpsgame/ai.h fpsgame/render.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/render.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/render.o: shared/igame.h fpsgame/ai.h fpsgame/scoreboard.o: fpsgame/game.h shared/cube.h shared/tools.h fpsgame/scoreboard.o: shared/geom.h shared/ents.h shared/command.h fpsgame/scoreboard.o: shared/iengine.h shared/igame.h fpsgame/ai.h fpsgame/server.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/server.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/server.o: shared/igame.h fpsgame/ai.h fpsgame/capture.h fpsgame/ctf.h fpsgame/server.o: fpsgame/extinfo.h fpsgame/aiman.h fpsgame/waypoint.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/waypoint.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/waypoint.o: shared/igame.h fpsgame/ai.h sspgame/ssp.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h sspgame/ssp.o: shared/command.h shared/iengine.h shared/igame.h sspgame/ssp.o: sspgame/sspgame.h sspgame/sspent.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h sspgame/sspent.o: shared/command.h shared/iengine.h shared/igame.h sspgame/sspent.o: sspgame/sspgame.h sspgame/ssprender.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h sspgame/ssprender.o: shared/command.h shared/iengine.h shared/igame.h sspgame/ssprender.o: sspgame/sspgame.h sspgame/sspmoster.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h sspgame/sspmonster.o: shared/command.h shared/iengine.h shared/igame.h sspgame/sspmonster.o: sspgame/sspgame.h sspgame/sspstubs.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h sspgame/sspstubs.o: shared/command.h shared/iengine.h shared/igame.h sspgame/sspstubs.o: sspgame/sspgame.h sspgame/sspweapons.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h sspgame/sspweapons.o: shared/command.h shared/iengine.h shared/igame.h sspgame/sspweapons.o: sspgame/sspgame.h rpggame/rpg.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpg.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgai.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgai.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgaction.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgaction.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgcamera.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgcamera.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgchar.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgchar.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgconfig.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgconfig.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgcontainer.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgcontainer.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgeffect.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgeffect.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgentities.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgentities.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpggui.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpggui.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpghud.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpghud.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgio.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgio.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgitem.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgitem.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgobstacle.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgobstacle.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgplatform.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgplatform.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgproj.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgproj.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgscript.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgscript.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgstats.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgstats.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgstatus.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgstatus.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgstubs.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgstubs.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgrender.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgrender.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgtest.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgtest.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/rpgtrigger.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/rpgtrigger.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h rpggame/waypoint.o : shared/cube.h shared/tools.h shared/geom.h shared/ents.h rpggame/waypoint.o : shared/command.h shared/iengine.h shared/igame.h rpggame/rpggame.h moviecube/client.o: moviecube/game.h shared/cube.h shared/tools.h shared/geom.h moviecube/modeinfo.h moviecube/clientmode.h moviecube/client.o: shared/ents.h shared/command.h shared/iengine.h moviecube/client.o: shared/igame.h moviecube/entities.o: moviecube/game.h shared/cube.h shared/tools.h shared/geom.h moviecube/modeinfo.h moviecube/clientmode.h moviecube/entities.o: shared/ents.h shared/command.h shared/iengine.h moviecube/entities.o: shared/igame.h moviecube/moviecube.o: moviecube/game.h shared/cube.h shared/tools.h shared/geom.h moviecube/modeinfo.h moviecube/clientmode.h moviecube/moviecube.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h moviecube/movable.o: moviecube/game.h shared/cube.h shared/tools.h shared/geom.h moviecube/movable.o: shared/ents.h shared/command.h shared/iengine.h moviecube/movable.o: shared/igame.h moviecube/render.o: moviecube/game.h shared/cube.h shared/tools.h shared/geom.h moviecube/render.o: shared/ents.h shared/command.h shared/iengine.h moviecube/render.o: shared/igame.h moviecube/server.o: moviecube/game.h shared/cube.h shared/tools.h shared/geom.h moviecube/server.o: moviecube/game.h shared/cube.h shared/tools.h shared/geom.h moviecube/modeinfo.h moviecube/servmode.h moviecube/server.o: shared/igame.h moviecube/server.o: moviecube/extinfo.h moviecube/botmgr.h krsgame/krs.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h krsgame/krs.o: shared/command.h shared/iengine.h shared/igame.h krsgame/krs.o: krsgame/krsgame.h krsgame/krsai.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h krsgame/krsai.o: shared/command.h shared/iengine.h shared/igame.h krsgame/krsai.o: krsgame/krsgame.h krsgame/krsents.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h krsgame/krsents.o: shared/command.h shared/iengine.h shared/igame.h krsgame/krsents.o: krsgame/krsgame.h krsgame/krshud.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h krsgame/krshud.o: shared/command.h shared/iengine.h shared/igame.h krsgame/krshud.o: krsgame/krsgame.h krsgame/krsrender.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h krsgame/krsrender.o: shared/command.h shared/iengine.h shared/igame.h krsgame/krsrender.o: krsgame/krsgame.h krsgame/krsstubs.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h krsgame/krsstubs.o: shared/command.h shared/iengine.h shared/igame.h krsgame/krsstubs.o: krsgame/krsgame.h krsgame/krsscript.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h krsgame/krsscript.o: shared/command.h shared/iengine.h shared/igame.h krsgame/krsscript.o: krsgame/krsgame.h krsgame/waypoint.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h krsgame/waypoint.o: shared/command.h shared/iengine.h shared/igame.h krsgame/waypoint.o: krsgame/krsgame.h pzlgame/pzl.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h pzlgame/pzl.o: shared/command.h shared/iengine.h shared/igame.h pzlgame/pzl.o: pzlgame/pzlgame.h pzlgame/pzlents.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h pzlgame/pzlents.o: shared/command.h shared/iengine.h shared/igame.h pzlgame/pzlents.o: pzlgame/pzlgame.h pzlgame/pzlhud.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h pzlgame/pzlhud.o: shared/command.h shared/iengine.h shared/igame.h pzlgame/pzlhud.o: pzlgame/pzlgame.h pzlgame/pzlrender.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h pzlgame/pzlrender.o: shared/command.h shared/iengine.h shared/igame.h pzlgame/pzlrender.o: pzlgame/pzlgame.h pzlgame/pzlstubs.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h pzlgame/pzlstubs.o: shared/command.h shared/iengine.h shared/igame.h pzlgame/pzlstubs.o: pzlgame/pzlgame.h pzlgame/pzlscript.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h pzlgame/pzlscript.o: shared/command.h shared/iengine.h shared/igame.h pzlgame/pzlscript.o: pzlgame/pzlgame.h shared/cube.h.gch: shared/tools.h shared/geom.h shared/ents.h shared/cube.h.gch: shared/command.h shared/iengine.h shared/igame.h engine/engine.h.gch: shared/cube.h shared/tools.h shared/geom.h shared/ents.h engine/engine.h.gch: shared/command.h shared/iengine.h shared/igame.h engine/engine.h.gch: engine/world.h engine/octa.h engine/lightmap.h engine/engine.h.gch: engine/bih.h engine/texture.h engine/model.h engine/engine.h.gch: engine/varray.h fpsgame/game.h.gch: shared/cube.h shared/tools.h shared/geom.h shared/ents.h fpsgame/game.h.gch: shared/command.h shared/iengine.h shared/igame.h fpsgame/game.h.gch: fpsgame/ai.h sspgame/sspgame.h.gch: shared/cube.h shared/tools.h shared/geom.h shared/ents.h sspgame/sspgame.h.gch: shared/command.h shared/iengine.h shared/igame.h krsgame/krsgame.h.gch: shared/cube.h shared/tools.h shared/geom.h shared/ents.h krsgame/krsgame.h.gch: shared/command.h shared/iengine.h shared/igame.h pzlgame/pzlgame.h.gch: shared/cube.h shared/tools.h shared/geom.h shared/ents.h pzlgame/pzlgame.h.gch: shared/command.h shared/iengine.h shared/igame.h moviecube/game.h.gch: shared/cube.h shared/tools.h shared/geom.h shared/ents.h moviecube/game.h.gch: shared/command.h shared/iengine.h shared/igame.h moviecube/game.h.gch: moviecube/modeinfo.h moviecube/clientmode.h moviecube/servmode.h shared/crypto-standalone.o: shared/cube.h shared/tools.h shared/geom.h shared/crypto-standalone.o: shared/ents.h shared/command.h shared/iengine.h shared/crypto-standalone.o: shared/igame.h shared/stream-standalone.o: shared/cube.h shared/tools.h shared/geom.h shared/stream-standalone.o: shared/ents.h shared/command.h shared/iengine.h shared/stream-standalone.o: shared/igame.h shared/tools-standalone.o: shared/cube.h shared/tools.h shared/geom.h shared/tools-standalone.o: shared/ents.h shared/command.h shared/iengine.h shared/tools-standalone.o: shared/igame.h engine/command-standalone.o: engine/engine.h shared/cube.h shared/tools.h engine/command-standalone.o: shared/geom.h shared/ents.h shared/command.h engine/command-standalone.o: shared/iengine.h shared/igame.h engine/world.h engine/command-standalone.o: engine/octa.h engine/lightmap.h engine/bih.h engine/command-standalone.o: engine/texture.h engine/model.h engine/varray.h engine/server-standalone.o: engine/engine.h shared/cube.h shared/tools.h engine/server-standalone.o: shared/geom.h shared/ents.h shared/command.h engine/server-standalone.o: shared/iengine.h shared/igame.h engine/world.h engine/server-standalone.o: engine/octa.h engine/lightmap.h engine/bih.h engine/server-standalone.o: engine/texture.h engine/model.h engine/varray.h engine/worldio-standalone.o: engine/engine.h shared/cube.h shared/tools.h engine/worldio-standalone.o: shared/geom.h shared/ents.h shared/command.h engine/worldio-standalone.o: shared/iengine.h shared/igame.h engine/world.h engine/worldio-standalone.o: engine/octa.h engine/lightmap.h engine/bih.h engine/worldio-standalone.o: engine/texture.h engine/model.h engine/varray.h fpsgame/entities-standalone.o: fpsgame/game.h shared/cube.h shared/tools.h fpsgame/entities-standalone.o: shared/geom.h shared/ents.h shared/command.h fpsgame/entities-standalone.o: shared/iengine.h shared/igame.h fpsgame/ai.h fpsgame/server-standalone.o: fpsgame/game.h shared/cube.h shared/tools.h fpsgame/server-standalone.o: shared/geom.h shared/ents.h shared/command.h fpsgame/server-standalone.o: shared/iengine.h shared/igame.h fpsgame/ai.h fpsgame/server-standalone.o: fpsgame/capture.h fpsgame/ctf.h fpsgame/server-standalone.o: fpsgame/extinfo.h fpsgame/aiman.h fpsgame/entities-standalone.o: moviecube/game.h shared/cube.h shared/tools.h fpsgame/entities-standalone.o: shared/geom.h shared/ents.h shared/command.h fpsgame/entities-standalone.o: shared/iengine.h shared/igame.h fpsgame/ai.h moviecube/server-standalone.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/server-standalone.o: shared/geom.h shared/ents.h shared/command.h moviecube/server-standalone.o: shared/iengine.h shared/igame.h moviecube/server-standalone.o: moviecube/extinfo.h moviecube/botmgr.h moviecube/server-standalone.o: moviecube/modeinfo.h moviecube/clientmode.h moviecube/servmode.h engine/master-standalone.o: shared/cube.h shared/tools.h shared/geom.h engine/master-standalone.o: shared/ents.h shared/command.h shared/iengine.h engine/master-standalone.o: shared/igame.h sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/0000775000175000017500000000000011660234752021301 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/dynentities.h0000664000175000017500000000372011442705030024001 0ustar showardshoward#ifndef __DYNAMICENTITIES_H__ #define __DYNAMICENTITIES_H__ //#include "characterinfo.h" //#include "game.h" //enum { CONTROL_PLAYER = 0, CONTROL_CHARACTER, CONTROL_REMOTE, CONTROL_AI, CONTROL_MAX }; //enum { CLIENT_PLAYER = 0, CLIENT_BOT }; // //struct dynentstate //{ // int clienttype; // // dynentstate() : clienttype(CLIENT_PLAYER) {} //TODO: change this to NONE on implementing ControlPlayer // // bool canpickup(int type) { return false; } // // void pickup(int type) {} // // void respawn() {} // // void spawnstate(int gamemode) // { //// if(m_demo) {} // } //}; // //struct DynamicEntity : dynent, dynentstate //{ // int weight; // affects the effectiveness of hitpush // int clientnum, privilege, lastupdate, plag, ping; // int lastaction; // int basetime; // int lastpickup, lastpickupmillis; // editinfo *edit; // float deltayaw, deltapitch, newyaw, newpitch; // int smoothmillis; // string name, info; // int ownernum; // int controltype; // vec muzzle; // Character::CharacterInfo charinfo; // // DynamicEntity() : weight(100), clientnum(-1), privilege(PRIV_NONE), lastupdate(0), plag(0), ping(0), basetime(0), edit(NULL), smoothmillis(-1), ownernum(-1), controltype(CONTROL_PLAYER), muzzle(-1, -1, -1) // { // name[0] = info[0] = 0; // respawn(); // } // ~DynamicEntity() // { //// conoutf("DEBUG: DynamicEntity::~DynamicEntity cn: %d", clientnum); // freeeditinfo(edit); // } // // Character::CharacterInfo& getcharinfo() { return charinfo; } // // void respawn() // { //// conoutf("DEBUG: DynamicEntity::respawn cn: %d", clientnum); // dynent::reset(); // dynentstate::respawn(); // lastaction = 0; // lastpickup = -1; // lastpickupmillis = 0; // ///TODO: check this //// charinfo.resetao(); // } //}; #endif // __DYNAMICENTITIES_H__ sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/clientmode.cpp0000664000175000017500000000151011442705030024113 0ustar showardshoward/* * clientmode.cpp * * Created on: 18.12.2009 * Author: offtools */ #include "game.h" namespace game { void defaultclientmode::pickspawn(DynamicEntity *d) { switch(d->controltype) { case CONTROL_NPC: { //check ActionLib empty // if(editmode) // { //// TODO (offtools#1#): fix if author under floor // d->o = vec(player1->o); // droptofloor(d->o, 0, 0); // vec sp = vec(0,0,0); // vecfromyawpitch(game::player1->yaw, 0, 50, 0, sp); // d->o.add(sp); // d->o.z += d->eyeheight; // } break; } case CONTROL_PLAYER: case CONTROL_AI: findplayerspawn(d); break; case CONTROL_REMOTE: default: break; } } } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/game.h0000664000175000017500000003770411442705030022364 0ustar showardshoward#ifndef __GAME_H__ #define __GAME_H__ #include "cube.h" #include "qcommand.h" #include "qcscript.h" #include "sb.h" #include "camera.h" #ifndef STANDALONE extern int dedicated; #endif // console message types enum { CON_CHAT = 1<<8, CON_TEAMCHAT = 1<<9, CON_GAMEINFO = 1<<10, CON_FRAG_SELF = 1<<11, CON_FRAG_OTHER = 1<<12 }; enum { CHAT_TALK = 1<<0, CHAT_EMOTE = 1<<1, CHAT_TEAM = 1<<2, }; // network quantization scale #define DMF 16.0f // for world locations #define DNF 100.0f // for normalized vectors #define DVELF 1.0f // for playerspeed based velocity vectors #define MAXNAMELEN 15 #define MAXTEAMLEN 4 #define SGRAYS 20 #define SGSPREAD 4 #define RL_DAMRAD 40 #define RL_SELFDAMDIV 2 #define RL_DISTSCALE 1.5f #define MAXBOTS 32 //enum // static entity types //{ // NOTUSED = ET_EMPTY, // entity slot not in use in map // LIGHT = ET_LIGHT, // lightsource, attr1 = radius, attr2 = intensity // MAPMODEL = ET_MAPMODEL, // attr1 = angle, attr2 = idx // PLAYERSTART, // attr1 = angle, attr2 = team // ENVMAP = ET_ENVMAP, // attr1 = radius // PARTICLES = ET_PARTICLES, // MAPSOUND = ET_SOUND, // SPOTLIGHT = ET_SPOTLIGHT, // I_SHELLS, I_BULLETS, I_ROCKETS, I_ROUNDS, I_GRENADES, I_CARTRIDGES, // I_HEALTH, I_BOOST, // I_GREENARMOUR, I_YELLOWARMOUR, // I_QUAD, // TELEPORT, // attr1 = idx // TELEDEST, // attr1 = angle, attr2 = idx // MONSTER, // attr1 = angle, attr2 = monstertype // CARROT, // attr1 = tag, attr2 = type // JUMPPAD, // attr1 = zpush, attr2 = ypush, attr3 = xpush // BASE, // RESPAWNPOINT, // BOX, // attr1 = angle, attr2 = idx, attr3 = weight // BARREL, // attr1 = angle, attr2 = idx, attr3 = weight, attr4 = health // PLATFORM, // attr1 = angle, attr2 = idx, attr3 = tag, attr4 = speed // ELEVATOR, // attr1 = angle, attr2 = idx, attr3 = tag, attr4 = speed // FLAG, // attr1 = angle, attr2 = team // WAYPOINT, // CAMERA, //attr1 = pitch, attr2 = yaw, attr3 = focus // DYNLIGHT, // TEST, // MAXENTTYPES //}; enum { MM_AUTH = -1, MM_OPEN = 0, MM_VETO, MM_LOCKED, MM_PRIVATE, MM_PASSWORD, MM_START = MM_AUTH }; static const char * const mastermodenames[] = { "auth", "open", "veto", "locked", "private", "password" }; // hardcoded sounds, defined in sounds.cfg enum { S_JUMP = 0, S_LAND, S_RIFLE, S_TELEPORT, S_SPLASH1, S_SPLASH2, S_CG, S_RLFIRE, S_RUMBLE, S_JUMPPAD, S_WEAPLOAD, S_ITEMAMMO, S_ITEMHEALTH, S_ITEMARMOUR, S_ITEMPUP, S_ITEMSPAWN, S_NOAMMO, S_PUPOUT, S_PAIN1, S_PAIN2, S_PAIN3, S_PAIN4, S_PAIN5, S_PAIN6, S_DIE1, S_DIE2, S_FLAUNCH, S_FEXPLODE, S_SG, S_PUNCH1, S_GRUNT1, S_GRUNT2, S_RLHIT, S_PAINO, S_PAINR, S_DEATHR, S_PAINE, S_DEATHE, S_PAINS, S_DEATHS, S_PAINB, S_DEATHB, S_PAINP, S_PIGGR2, S_PAINH, S_DEATHH, S_PAIND, S_DEATHD, S_PIGR1, S_ICEBALL, S_SLIMEBALL, S_PISTOL, S_V_BASECAP, S_V_BASELOST, S_V_FIGHT, S_V_BOOST, S_V_BOOST10, S_V_QUAD, S_V_QUAD10, S_V_RESPAWNPOINT, S_FLAGPICKUP, S_FLAGDROP, S_FLAGRETURN, S_FLAGSCORE, S_FLAGRESET, S_BURN, S_CHAINSAW_ATTACK, S_CHAINSAW_IDLE, S_HIT }; // network messages codes, c2s, c2c, s2c enum { PRIV_NONE = 0, PRIV_MASTER, PRIV_ADMIN }; enum { SV_CONNECT = 0, SV_SERVINFO, SV_WELCOME, SV_INITCLIENT, SV_POS, SV_TEXT, SV_SOUND, SV_CDIS, SV_SHOOT, SV_EXPLODE, SV_SUICIDE, SV_TRYSPAWN, SV_SPAWNSTATE, SV_SPAWN, SV_FORCEDEATH, SV_MAPCHANGE, SV_MAPVOTE, SV_ITEMSPAWN, SV_ITEMPICKUP, SV_ITEMACC, SV_PING, SV_PONG, SV_CLIENTPING, SV_TIMEUP, SV_MAPRELOAD, SV_FORCEINTERMISSION, SV_SERVMSG, SV_ITEMLIST, SV_RESUME, SV_EDITMODE, SV_EDITENT, SV_EDITF, SV_EDITT, SV_EDITM, SV_FLIP, SV_COPY, SV_PASTE, SV_ROTATE, SV_REPLACE, SV_DELCUBE, SV_REMIP, SV_NEWMAP, SV_GETMAP, SV_SENDMAP, SV_SENDCFG, SV_UPLOADMAP, SV_UPLOADCFG, SV_SENDTEXTURE, SV_TEXTUREREQUEST, SV_EDITVAR, SV_MASTERMODE, SV_KICK, SV_CLEARBANS, SV_CURRENTMASTER, SV_SPECTATOR, SV_SETMASTER, SV_SETTEAM, SV_BASES, SV_BASEINFO, SV_BASESCORE, SV_REPAMMO, SV_BASEREGEN, SV_ANNOUNCE, SV_LISTDEMOS, SV_SENDDEMOLIST, SV_GETDEMO, SV_SENDDEMO, SV_DEMOPLAYBACK, SV_RECORDDEMO, SV_STOPDEMO, SV_CLEARDEMOS, SV_TAKEFLAG, SV_RETURNFLAG, SV_RESETFLAG, SV_INVISFLAG, SV_TRYDROPFLAG, SV_DROPFLAG, SV_SCOREFLAG, SV_INITFLAGS, SV_CLIENT, SV_AUTHTRY, SV_AUTHCHAL, SV_AUTHANS, SV_REQAUTH, SV_PAUSEGAME, SV_REQUESTBOT, SV_DELETEBOT, SV_INITBOT, SV_FROMBOT, SV_BOTLIMIT, SV_BOTBALANCE, SV_MAPCRC, SV_CHECKMAPS, SV_SWITCHNAME, SV_SWITCHMODEL, SV_SWITCHTEAM, SV_ATTACH, SV_DETACH, NUMSV }; static const int msgsizes[] = // size inclusive message token, 0 for variable or not-checked sizes { SV_CONNECT, 0, SV_SERVINFO, 5, SV_WELCOME, 2, SV_INITCLIENT, 0, SV_POS, 0, SV_TEXT, 0, SV_SOUND, 2, SV_CDIS, 2, SV_SHOOT, 0, SV_EXPLODE, 0, SV_SUICIDE, 1, SV_TRYSPAWN, 1, SV_SPAWNSTATE, 2, SV_SPAWN, 1, SV_FORCEDEATH, 2, SV_MAPCHANGE, 0, SV_MAPVOTE, 0, SV_ITEMSPAWN, 2, SV_ITEMPICKUP, 2, SV_ITEMACC, 3, SV_PING, 2, SV_PONG, 2, SV_CLIENTPING, 2, SV_TIMEUP, 2, SV_MAPRELOAD, 1, SV_FORCEINTERMISSION, 1, SV_SERVMSG, 0, SV_ITEMLIST, 0, SV_RESUME, 0, SV_EDITMODE, 2, SV_EDITENT, 0, SV_EDITF, 16, SV_EDITT, 16, SV_EDITM, 16, SV_FLIP, 14, SV_COPY, 14, SV_PASTE, 14, SV_ROTATE, 15, SV_REPLACE, 17, SV_DELCUBE, 14, SV_REMIP, 1, SV_NEWMAP, 2, SV_GETMAP, 1, SV_SENDMAP, 0, SV_SENDCFG, 0, SV_UPLOADMAP, 0, SV_UPLOADCFG, 0, SV_SENDTEXTURE, 0, SV_TEXTUREREQUEST, 0, SV_EDITVAR, 0, SV_MASTERMODE, 2, SV_KICK, 2, SV_CLEARBANS, 1, SV_CURRENTMASTER, 3, SV_SPECTATOR, 3, SV_SETMASTER, 0, SV_SETTEAM, 0, SV_BASES, 0, SV_BASEINFO, 0, SV_BASESCORE, 0, SV_REPAMMO, 1, SV_BASEREGEN, 6, SV_ANNOUNCE, 2, SV_LISTDEMOS, 1, SV_SENDDEMOLIST, 0, SV_GETDEMO, 2, SV_SENDDEMO, 0, SV_DEMOPLAYBACK, 3, SV_RECORDDEMO, 2, SV_STOPDEMO, 1, SV_CLEARDEMOS, 2, SV_TAKEFLAG, 2, SV_RETURNFLAG, 3, SV_RESETFLAG, 4, SV_INVISFLAG, 3, SV_TRYDROPFLAG, 1, SV_DROPFLAG, 6, SV_SCOREFLAG, 6, SV_INITFLAGS, 6, SV_CLIENT, 0, SV_AUTHTRY, 0, SV_AUTHCHAL, 0, SV_AUTHANS, 0, SV_REQAUTH, 0, SV_PAUSEGAME, 2, SV_REQUESTBOT, 1, SV_DELETEBOT, 2, SV_INITBOT, 5, SV_FROMBOT, 2, SV_BOTLIMIT, 2, SV_BOTBALANCE, 2, SV_MAPCRC, 0, SV_CHECKMAPS, 1, SV_SWITCHNAME, 0, SV_SWITCHMODEL, 2, SV_SWITCHTEAM, 0, SV_ATTACH, 0, SV_DETACH, 0, -1 }; #define MOVIECUBE_LANINFO_PORT 28784 #define MOVIECUBE_SERVER_PORT 28785 #define MOVIECUBE_SERVINFO_PORT 28786 #define MOVIECUBE_MASTER_PORT 28787 #define PROTOCOL_VERSION 5 // bump when protocol changes #define DEMO_VERSION 1 // bump when demo format changes #define DEMO_MAGIC "MOVIECUBE_DEMO" struct demoheader { char magic[16]; int version, protocol; }; //offtools: texture/modeltransfer //idea for a cachefile //cache entry: checksum (something unique, uuid, md5 or crc) //struct cache //{ // typedef string checksum; // typedef vector entries; // // hashtable lookuptable; // // void init(); // void read(); // void write(); // // char* search(string filename, string checksum) // { // //pseudo code: // //entries = lookuptable.access(filename) // //loop entries do: // // if getchecksum(cname) == checksum // // found cacheentry return // //end: not found return error // return NULL; // } //}; enum { TRIGGER_RESET = 0, TRIGGERING, TRIGGERED, TRIGGER_RESETTING, TRIGGER_DISAPPEARED }; //offtools: server side map data, for uploading and receiving mapdata and cfg's enum { MD_NONE = 0, MD_GOTMAP = 1<<0, MD_GOTCFG = 1<<1 }; struct mapdata { int cn; //uploader (server side only, use -1 on client) string prefix; string mname; //tmp map name int status; stream *map; stream *cfg; mapdata() : map(NULL), cfg(NULL) { cn = -1; status = MD_NONE; mname[0] = prefix[0] = '\0'; } ~mapdata() { reset(); } void init(int _cn, string _mname) { if( status != MD_NONE ) return; cn = _cn; copystring(mname, _mname); } void reset() { status = MD_NONE; if (map) {delete map; map = NULL;} if (cfg) {delete cfg; cfg = NULL;} } bool check(int _cn, string _mname) { if(cn != _cn) return false; if(strcmp(mname, _mname) != 0) return false; return true; } void clear() { reset(); defformatstring(fname)("packages/base/getmap_%s.ogz", mname); remove(findfile(fname, "rb")); formatstring(fname)("packages/base/getmap_%s-art.cfg", mname); remove(findfile(fname, "rb")); } bool finished() { return status == (MD_GOTMAP | MD_GOTCFG); } }; enum { CONTROL_PLAYER = 0, CONTROL_NPC, CONTROL_REMOTE, CONTROL_AI, CONTROL_MAX }; enum cltype { CLIENT_PLAYER = 0, CLIENT_BOT }; struct dynentstate { cltype clienttype; dynentstate() : clienttype(CLIENT_PLAYER) {} //TODO: change this to NONE on implementing ControlPlayer bool canpickup(int type) { return false; } void pickup(int type) {} void respawn() {} void spawnstate(int gamemode) {} }; #include "characterinfo.h" struct DynamicEntity : dynent, dynentstate { int weight; // affects the effectiveness of hitpush int clientnum, privilege, lastupdate, plag, ping; int lastaction; int basetime; int lastpickup, lastpickupmillis; editinfo *edit; float deltayaw, deltapitch, newyaw, newpitch; int smoothmillis; string name, info; int ownernum; int controltype; vec muzzle; Character::CharacterInfo charinfo; DynamicEntity() : weight(100), clientnum(-1), privilege(PRIV_NONE), lastupdate(0), plag(0), ping(0), basetime(0), edit(NULL), smoothmillis(-1), ownernum(-1), controltype(CONTROL_PLAYER), muzzle(-1, -1, -1) { name[0] = info[0] = 0; respawn(); } ~DynamicEntity() { freeeditinfo(edit); } Character::CharacterInfo& getcharinfo() { return charinfo; } void respawn() { dynent::reset(); dynentstate::respawn(); lastaction = 0; lastpickup = -1; lastpickupmillis = 0; ///TODO: check this // charinfo.resetao(); } }; namespace PlayerModel { struct PlayerModelInfo; extern int RegisterModel(const char *s); extern void RegisterAnimation(char *loadname, char* anim, int num); extern void BuildModelAttach(PlayerModelInfo& pm, int itemnum, modelattach& a); extern bool HasAnimation(PlayerModelInfo& pm, int anim); extern const char* GetName(PlayerModelInfo& pm); extern vector PlayerModels(); extern PlayerModelInfo& getPlayerModelInfo(int i); } //#include "mapentities.h" //namespace entities //{ // extern const char *entmdlname(int type); // extern const char *itemname(int i); // // extern void preloadentities(); // extern void checkitems(DynamicEntity *d); //// extern void resetspawns(); // extern void spawnitems(); // extern void setspawn(int i, bool on); // extern void teleport(int n, DynamicEntity *d); // extern void pickupeffects(int n, DynamicEntity *d); // extern void checktriggers(); // extern void resettriggers(); // // extern void repammo(DynamicEntity *d, int type, bool local = true); //} #include "clientmode.h" #include "control.h" #include "../sb/extentity.h" class Extent : public Extentities::Extentity { }; namespace Control { extern ControlPlayer& GetPlayer(); extern vector controls; } namespace CameraManager { extern void Update(); } namespace game { extern clientmode *cmode; extern void setclientmode(); // fps extern int gamemode, nextmode; extern string clientmap; extern int minremain; extern bool intermission; extern int maptime, maprealtime; extern DynamicEntity *player1; extern vector players, clients; extern int lastspawnattempt; extern int lasthit; extern int respawnent; extern int following; extern int smoothmove, smoothdist; extern int deathscore; extern bool clientoption(const char *arg); extern DynamicEntity *getclient(int cn); extern DynamicEntity *newclient(int cn); extern const char *colorname(DynamicEntity *d, const char *name = NULL, const char *prefix = ""); extern DynamicEntity *pointatplayer(); extern DynamicEntity *hudplayer(); extern DynamicEntity *followingplayer(); extern void stopfollowing(); extern void clientdisconnected(int cn, bool notify = true); extern void clearclients(bool notify = true); extern void startgame(); extern void spawnplayer(DynamicEntity *); extern void deathstate(DynamicEntity *d, bool restore = false); extern void damaged(int damage, DynamicEntity *d, DynamicEntity *actor, bool local = true); extern void killed(DynamicEntity *d, DynamicEntity *actor); extern void timeupdate(int timeremain); extern void msgsound(int n, physent *d = NULL); extern void predictplayer(DynamicEntity *d, bool move); extern void initdynlights(); enum { HICON_BLUE_ARMOUR = 0, HICON_GREEN_ARMOUR, HICON_YELLOW_ARMOUR, HICON_HEALTH, HICON_FIST, HICON_SG, HICON_CG, HICON_RL, HICON_RIFLE, HICON_GL, HICON_PISTOL, HICON_QUAD, HICON_RED_FLAG, HICON_BLUE_FLAG, HICON_X = 20, HICON_Y = 1650, HICON_TEXTY = 1644, HICON_STEP = 490, HICON_SIZE = 120, HICON_SPACE = 40 }; extern void drawicon(int icon, float x, float y, float sz = 120); // client extern bool connected, remote, demoplayback; extern int parseplayer(const char *arg); extern void addmsg(int type, const char *fmt = NULL, ...); extern void switchname(const char *name); extern void switchplayermodel(int playermodel); extern void sendmapinfo(); extern void stopdemo(); extern void changemap(const char *name, int mode); extern void c2sinfo(); extern const char* attachtag(int i); extern int attachnumbypart(char* part); // movable struct movable; extern vector movables; extern void clearmovables(); extern void stackmovable(movable *d, physent *o); extern void updatemovables(int curtime); extern void rendermovables(); extern void suicidemovable(movable *m); extern void hitmovable(int damage, movable *m, DynamicEntity *at, const vec &vel, int gun); extern bool intersect(dynent *d, const vec &from, const vec &to); extern dynent *intersectclosest(const vec &from, const vec &to, DynamicEntity *at); extern void saveragdoll(DynamicEntity *d); extern void clearragdolls(); extern void moveragdolls(); extern int chooserandomplayermodel(int seed); extern void swayhudgun(int curtime); extern vec hudgunorigin(int gun, const vec &from, const vec &to, DynamicEntity *d); } namespace server { // extern bool allowupload; //offtools: server option extern const char *modename(int n, const char *unknown = "unknown"); extern const char *mastermodename(int n, const char *unknown = "unknown"); extern void startintermission(); extern void stopdemo(); extern void forcemap(const char *map, int mode); extern void hashpassword(int cn, int sessionid, const char *pwd, char *result, int maxlen = MAXSTRLEN); extern int msgsizelookup(int msg); extern bool serveroption(const char *arg); } #endif sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/map.cpp0000664000175000017500000000373311442705030022556 0ustar showardshoward#include "map.h" #include "mapentities.h" VARR(toclocked, 0, 1, 1); MapToc::MapToc() : lastid(-1) {} MapToc::~MapToc() {} MapTocEntry& MapToc::registerentry( MapObject& mapobject ) { int id = ++lastid; conoutf("MapToc::registerentry id %d", id); return *toc.add(new MapTocEntry(mapobject, id)); } void MapToc::removeentry( int id ) {} MapTocEntry* MapToc::lookupentry(int id) { loopv(toc) if(toc[i]->getid() == id) { return toc[i]; } return NULL; } ///TODO: implementation only works on MapEntities now, this is just for testing and acts ///as replacment for mapuid. Later it will used as general Lookup for all kind of entities ///and instances void MapToc::writetoc(stream *f) { // int idx = 0; // f->printf("tocreset\n"); // loopv(MapEntities::ents) // { // MapEntities::StaticEntity* ent = MapEntities::ents[i]; // if(ent->type != ET_EMPTY) // { // conoutf("MapToc::writetoc - not implementet, ent idx: %d, num: %d, id: %d", i, idx, ent->getid()); // f->printf("toc %d %d\n", idx, ent->getid()); // idx++; // } // } } void MapToc::readtoc(int idx, int id) { // if( toclocked ) // { // conoutf("toc command is locked"); // } // // if( MapEntities::ents.inrange(idx) ) // { // MapEntities::StaticEntity* ent = MapEntities::ents[idx]; // ent->entry.setid(id); // if(lastid < id) // { // lastid = id; // } // } } void MapToc::lock(bool lk) { toclocked = lk; } void MapToc::clear() { lastid = -1; } MapObject::MapObject() : entry(MapToc::Get ().registerentry(*this)) { conoutf("MapObject::MapObject"); } MapObject::~MapObject() {} int MapObject::getid() { return entry.getid(); } MapTocEntry::MapTocEntry( MapObject& mapobject, int id ) : id(id), object(mapobject) {} MapTocEntry::~MapTocEntry() {} int MapTocEntry::getid() { return id; } void MapTocEntry::setid(int i) { id = i; } ICOMMAND(toc, "ii", (int *idx, int *id), MapToc::Get().readtoc(*idx, *id)); ICOMMAND(tocreset, "", (), MapToc::Get ().clear(); // toclocked = 0; MapToc::Get ().lock(false); ); sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/camera.h0000664000175000017500000000166511442705030022700 0ustar showardshoward#ifndef CAMERA_H_INCLUDED #define CAMERA_H_INCLUDED #include "game.h" #include "entityscript/command.h" //Cutscene Instance for cutscenes //using namespace EntityScript; class Cutscene : public EntityScript::Instance, public physent { public: Cutscene(EntityScript::Script &s); ~Cutscene(); void debug(); }; //base class of scene actions class ActionScene : public EntityScript::Action { public: ActionScene(int d = 0); virtual ~ActionScene(); float multiplier(bool total); protected: int startmillis; int duration; }; class ActionCameraMove : public ActionScene { public: ActionCameraMove(extentity& e, int d); ~ActionCameraMove(); bool process(); private: extentity& ent; float dx, dy, dz; vec start; vec dest; }; class CommandMove : public Command { public: } namespace Cutscenes { void Init(); // void Update(); } #endif // CAMERA_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/server.cpp0000664000175000017500000024752411442705030023317 0ustar showardshoward#include "game.h" #include "servmode.h" #include "extentity.h" namespace game { void parseoptions(vector &args) { loopv(args) #ifndef STANDALONE if(!game::clientoption(args[i])) #endif if(!server::serveroption(args[i])) { conoutf(CON_ERROR, "unknown command-line option: %s", args[i]); } } } extern ENetAddress masteraddress; namespace server { struct server_entity // server side version of "entity" type { int type; int spawntime; char spawned; }; static const int DEATHMILLIS = 300; struct clientinfo; struct gameevent { virtual ~gameevent() {} virtual bool flush(clientinfo *ci, int fmillis); virtual void process(clientinfo *ci) {} virtual bool keepable() const { return false; } }; struct timedevent : gameevent { int millis; bool flush(clientinfo *ci, int fmillis); }; struct hitinfo { int target; int lifesequence; union { int rays; float dist; }; vec dir; }; struct shotevent : timedevent { int id, gun; vec from, to; vector hits; void process(clientinfo *ci); }; struct explodeevent : timedevent { int id, gun; vector hits; bool keepable() const { return true; } void process(clientinfo *ci); }; struct pickupevent : gameevent { int ent; void process(clientinfo *ci); }; struct gamestate : dynentstate { vec o; int state, editstate; // int lastspawn; int lasttimeplayed, timeplayed; // gamestate() : state(CS_DEAD), editstate(CS_DEAD), lastspawn(-1) {} gamestate() : state(CS_DEAD), editstate(CS_DEAD){} bool isalive(int gamemillis) { return state==CS_ALIVE; // || (state==CS_DEAD && gamemillis - lastdeath <= DEATHMILLIS); } bool waitexpired(int gamemillis) { return false; } void reset() { if(state!=CS_SPECTATOR) state = editstate = CS_DEAD; timeplayed = 0; respawn(); } void respawn() { dynentstate::respawn(); o = vec(-1e10f, -1e10f, -1e10f); } void reassign() { respawn(); } }; struct clientinfo { int clientnum, ownernum, connectmillis, sessionid; string name, mapvote; int playermodel; int modevote; int privilege; bool connected, local, timesync; int gameoffset, lastevent; gamestate state; vector events; vector position, messages; int posoff, poslen, msgoff, msglen; vector bots; uint authreq; string authname; int ping, botreinit; string clientmap; int mapcrc; bool warned, gameclip; clientinfo() { reset(); } ~clientinfo() { events.deletecontents(); } void addevent(gameevent *e) { if(state.state==CS_SPECTATOR || events.length()>100) delete e; else events.add(e); } void mapchange() { mapvote[0] = 0; state.reset(); events.deletecontents(); timesync = false; lastevent = 0; clientmap[0] = '\0'; mapcrc = 0; warned = false; gameclip = false; } void reassign() { state.reassign(); events.deletecontents(); timesync = false; lastevent = 0; } void reset() { name[0] = 0; playermodel = -1; privilege = PRIV_NONE; connected = local = false; authreq = 0; position.setsize(0); messages.setsize(0); ping = 0; botreinit = 0; mapchange(); } int geteventmillis(int servmillis, int clientmillis) { if(!timesync || (events.empty() && state.waitexpired(servmillis))) { timesync = true; gameoffset = servmillis - clientmillis; return servmillis; } else return gameoffset + clientmillis; } }; struct worldstate { int uses; vector positions, messages; }; struct ban { int time; uint ip; }; namespace botmgr { extern void removebot(clientinfo *ci); extern void clearbot(); extern void checkbot(); extern void reqadd(clientinfo *ci); extern void reqdel(clientinfo *ci); extern void deletebot(clientinfo *ci); extern void setbotlimit(clientinfo *ci, int limit); extern void setbotbalance(clientinfo *ci, bool balance); extern void changemap(); extern void addclient(clientinfo *ci); extern void changeteam(clientinfo *ci); } #define MM_MODE 0xF #define MM_AUTOAPPROVE 0x1000 #define MM_PRIVSERV (MM_MODE | MM_AUTOAPPROVE) #define MM_PUBSERV ((1< allowedips; vector bannedips; vector connects, clients, bots; vector worldstates; bool reliablemessages = false; struct demofile { string info; uchar *data; int len; }; #define MAXDEMOS 5 vector demos; bool demonextmatch = false; stream *demotmp = NULL, *demorecord = NULL, *demoplayback = NULL; int nextplayback = 0, demomillis = 0; #define SERVMODE 1 // #include "capture.h" // #include "ctf.h" // captureservmode capturemode; // ctfservmode ctfmode; servmode *smode = new defaultservmode; SVAR(serverdesc, ""); SVAR(serverpass, ""); SVAR(adminpass, ""); VARF(publicserver, 0, 0, 2, { switch(publicserver) { case 0: default: mastermask = MM_PRIVSERV; break; case 1: mastermask = MM_PUBSERV; break; case 2: mastermask = MM_COOPSERV; break; } }); SVAR(servermotd, ""); void *newclientinfo() { return new clientinfo; } void deleteclientinfo(void *ci) { delete (clientinfo *)ci; } clientinfo *getinfo(int n) { if(n < MAXCLIENTS) return (clientinfo *)getclientinfo(n); n -= MAXCLIENTS; return bots.inrange(n) ? bots[n] : NULL; } vector sents; int msgsizelookup(int msg) { static int sizetable[NUMSV] = { -1 }; if(sizetable[0] < 0) { memset(sizetable, -1, sizeof(sizetable)); for(const int *p = msgsizes; *p >= 0; p += 2) sizetable[p[0]] = p[1]; } return msg >= 0 && msg < NUMSV ? sizetable[msg] : -1; } const char *modename(int n, const char *unknown) { if(m_valid(n)) return gamemodes[n - STARTGAMEMODE].name; return unknown; } const char *mastermodename(int n, const char *unknown) { return (n>=MM_START && size_t(n-MM_START)state.state!=CS_SPECTATOR) && (!noai || clients[i]->state.clienttype == CLIENT_PLAYER)) n++; return n; } bool duplicatename(clientinfo *ci, char *name) { if(!name) name = ci->name; loopv(clients) if(clients[i]!=ci && !strcmp(name, clients[i]->name)) return true; return false; } const char *colorname(clientinfo *ci, char *name = NULL) { if(!name) name = ci->name; if(name[0] && !duplicatename(ci, name) && ci->state.clienttype == CLIENT_PLAYER) return name; static string cname[3]; static int cidx = 0; cidx = (cidx+1)%3; formatstring(cname[cidx])(ci->state.clienttype == CLIENT_PLAYER ? "%s \fs\f5(%d)\fr" : "%s \fs\f5[%d]\fr", name, ci->clientnum); return cname[cidx]; } bool canspawnitem(int type) { return !m_noitems; } int spawntime(int type) { if(m_classicsp) return INT_MAX; int np = numclients(-1, true, false); np = np<3 ? 4 : (np>4 ? 2 : 3); // spawn times are dependent on number of players int sec = 0; // switch(type) // { // case I_SHELLS: // case I_BULLETS: // case I_ROCKETS: // case I_ROUNDS: // case I_GRENADES: // case I_CARTRIDGES: sec = np*4; break; // case I_HEALTH: sec = np*5; break; // case I_GREENARMOUR: // case I_YELLOWARMOUR: sec = 20; break; // case I_BOOST: // case I_QUAD: sec = 40+rnd(40); break; // } // return sec*1000; return sec*np*1000; } bool pickup(int i, int sender) // server side item pickup, acknowledge first client that gets it { if(minremain<=0 || !sents.inrange(i) || !sents[i].spawned) return false; clientinfo *ci = getinfo(sender); if(!ci || (!ci->local && !ci->state.canpickup(sents[i].type))) return false; sents[i].spawned = false; sents[i].spawntime = spawntime(sents[i].type); sendf(-1, 1, "ri3", SV_ITEMACC, i, sender); ci->state.pickup(sents[i].type); return true; } void writedemo(int chan, void *data, int len) { if(!demorecord) return; int stamp[3] = { gamemillis, chan, len }; lilswap(stamp, 3); demorecord->write(stamp, sizeof(stamp)); demorecord->write(data, len); } void recordpacket(int chan, void *data, int len) { writedemo(chan, data, len); } void enddemorecord() { if(!demorecord) return; DELETEP(demorecord); if(!demotmp) return; int len = demotmp->size(); if(demos.length()>=MAXDEMOS) { delete[] demos[0].data; demos.remove(0); } demofile &d = demos.add(); time_t t = time(NULL); char *timestr = ctime(&t), *trim = timestr + strlen(timestr); while(trim>timestr && isspace(*--trim)) *trim = '\0'; formatstring(d.info)("%s: %s, %s, %.2f%s", timestr, modename(gamemode), smapname, len > 1024*1024 ? len/(1024*1024.f) : len/1024.0f, len > 1024*1024 ? "MB" : "kB"); defformatstring(msg)("demo \"%s\" recorded", d.info); sendservmsg(msg); d.data = new uchar[len]; d.len = len; demotmp->seek(0, SEEK_SET); demotmp->read(d.data, len); DELETEP(demotmp); } int welcomepacket(packetbuf &p, clientinfo *ci); void sendwelcome(clientinfo *ci); void setupdemorecord() { if(!m_mp(gamemode) || m_edit) return; demotmp = opentempfile("demorecord", "w+b"); if(!demotmp) return; stream *f = opengzfile(NULL, "wb", demotmp); if(!f) { DELETEP(demotmp); return; } sendservmsg("recording demo"); demorecord = f; demoheader hdr; memcpy(hdr.magic, DEMO_MAGIC, sizeof(hdr.magic)); hdr.version = DEMO_VERSION; hdr.protocol = PROTOCOL_VERSION; lilswap(&hdr.version, 2); demorecord->write(&hdr, sizeof(demoheader)); packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); welcomepacket(p, NULL); writedemo(1, p.buf, p.len); } void listdemos(int cn) { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); putint(p, SV_SENDDEMOLIST); putint(p, demos.length()); loopv(demos) sendstring(demos[i].info, p); sendpacket(cn, 1, p.finalize()); } void cleardemos(int n) { if(!n) { loopv(demos) delete[] demos[i].data; demos.shrink(0); sendservmsg("cleared all demos"); } else if(demos.inrange(n-1)) { delete[] demos[n-1].data; demos.remove(n-1); defformatstring(msg)("cleared demo %d", n); sendservmsg(msg); } } void senddemo(int cn, int num) { if(!num) num = demos.length(); if(!demos.inrange(num-1)) return; demofile &d = demos[num-1]; sendf(cn, 2, "rim", SV_SENDDEMO, d.len, d.data); } void enddemoplayback() { if(!demoplayback) return; DELETEP(demoplayback); loopv(clients) sendf(clients[i]->clientnum, 1, "ri3", SV_DEMOPLAYBACK, 0, clients[i]->clientnum); sendservmsg("demo playback finished"); loopv(clients) sendwelcome(clients[i]); } void setupdemoplayback() { if(demoplayback) return; demoheader hdr; string msg; msg[0] = '\0'; defformatstring(file)("%s.dmo", smapname); demoplayback = opengzfile(file, "rb"); if(!demoplayback) formatstring(msg)("could not read demo \"%s\"", file); else if(demoplayback->read(&hdr, sizeof(demoheader))!=sizeof(demoheader) || memcmp(hdr.magic, DEMO_MAGIC, sizeof(hdr.magic))) formatstring(msg)("\"%s\" is not a demo file", file); else { lilswap(&hdr.version, 2); if(hdr.version!=DEMO_VERSION) formatstring(msg)("demo \"%s\" requires an %s version of Cube 2: Sauerbraten", file, hdr.versionread(&nextplayback, sizeof(nextplayback))!=sizeof(nextplayback)) { enddemoplayback(); return; } lilswap(&nextplayback, 1); } void readdemo() { if(!demoplayback || gamepaused) return; demomillis += curtime; while(demomillis>=nextplayback) { int chan, len; if(demoplayback->read(&chan, sizeof(chan))!=sizeof(chan) || demoplayback->read(&len, sizeof(len))!=sizeof(len)) { enddemoplayback(); return; } lilswap(&chan, 1); lilswap(&len, 1); ENetPacket *packet = enet_packet_create(NULL, len, 0); if(!packet || demoplayback->read(packet->data, len)!=len) { if(packet) enet_packet_destroy(packet); enddemoplayback(); return; } sendpacket(-1, chan, packet); if(!packet->referenceCount) enet_packet_destroy(packet); if(demoplayback->read(&nextplayback, sizeof(nextplayback))!=sizeof(nextplayback)) { enddemoplayback(); return; } lilswap(&nextplayback, 1); } } void stopdemo() { if(m_demo) enddemoplayback(); else enddemorecord(); } void pausegame(bool val) { if(gamepaused==val) return; gamepaused = val; sendf(-1, 1, "rii", SV_PAUSEGAME, gamepaused ? 1 : 0); } void hashpassword(int cn, int sessionid, const char *pwd, char *result, int maxlen) { char buf[2*sizeof(string)]; formatstring(buf)("%d %d ", cn, sessionid); copystring(&buf[strlen(buf)], pwd); if(!hashstring(buf, result, maxlen)) *result = '\0'; } bool checkpassword(clientinfo *ci, const char *wanted, const char *given) { string hash; hashpassword(ci->clientnum, ci->sessionid, wanted, hash, sizeof(hash)); return !strcmp(hash, given); } void revokemaster(clientinfo *ci) { ci->privilege = PRIV_NONE; if(ci->state.state==CS_SPECTATOR && !ci->local) botmgr::removebot(ci); } void setmaster(clientinfo *ci, bool val, const char *pass = "", const char *authname = NULL) { if(authname && !val) return; const char *name = ""; if(val) { bool haspass = adminpass[0] && checkpassword(ci, adminpass, pass); if(ci->privilege) { if(!adminpass[0] || haspass==(ci->privilege==PRIV_ADMIN)) return; } else if(ci->state.state==CS_SPECTATOR && !haspass && !authname && !ci->local) return; loopv(clients) if(ci!=clients[i] && clients[i]->privilege) { if(haspass) clients[i]->privilege = PRIV_NONE; else if((authname || ci->local) && clients[i]->privilege<=PRIV_MASTER) continue; else return; } if(haspass) ci->privilege = PRIV_ADMIN; else if(!authname && !(mastermask&MM_AUTOAPPROVE) && !ci->privilege && !ci->local) { sendf(ci->clientnum, 1, "ris", SV_SERVMSG, "This server requires you to use the \"/auth\" command to gain master."); return; } else { if(authname) { loopv(clients) if(ci!=clients[i] && clients[i]->privilege<=PRIV_MASTER) revokemaster(clients[i]); } ci->privilege = PRIV_MASTER; } name = privname(ci->privilege); } else { if(!ci->privilege) return; name = privname(ci->privilege); revokemaster(ci); } mastermode = MM_OPEN; allowedips.shrink(0); string msg; if(val && authname) { formatstring(msg)("%s claimed %s as '\fs\f5%s\fr'", colorname(ci), name, authname); print(msg); } else { formatstring(msg)("%s %s %s", colorname(ci), val ? "claimed" : "relinquished", name); print(msg); } sendservmsg(msg); currentmaster = val ? ci->clientnum : -1; masterupdate = true; if(gamepaused) { int admins = 0; loopv(clients) if(clients[i]->privilege >= PRIV_ADMIN || clients[i]->local) admins++; if(!admins) pausegame(false); } } int checktype(int type, clientinfo *ci) { if(ci && ci->local) return type; // only allow edit messages in coop-edit mode if(type>=SV_EDITENT && type<=SV_EDITVAR && !m_edit) return -1; // server only messages static int servtypes[] = { SV_SERVINFO, SV_INITCLIENT, SV_WELCOME, SV_MAPRELOAD, SV_SERVMSG, SV_SPAWNSTATE, SV_FORCEDEATH, SV_ITEMACC, SV_ITEMSPAWN, SV_TIMEUP, SV_CDIS, SV_CURRENTMASTER, SV_PONG, SV_RESUME, SV_BASESCORE, SV_BASEINFO, SV_BASEREGEN, SV_ANNOUNCE, SV_SENDDEMOLIST, SV_SENDDEMO, SV_DEMOPLAYBACK, SV_SENDMAP, SV_DROPFLAG, SV_SCOREFLAG, SV_RETURNFLAG, SV_RESETFLAG, SV_INVISFLAG, SV_CLIENT, SV_AUTHCHAL, SV_INITBOT }; if(ci) loopi(sizeof(servtypes)/sizeof(int)) if(type == servtypes[i]) return -1; return type; } void cleanworldstate(ENetPacket *packet) { loopv(worldstates) { worldstate *ws = worldstates[i]; if(ws->positions.inbuf(packet->data) || ws->messages.inbuf(packet->data)) ws->uses--; else continue; if(!ws->uses) { delete ws; worldstates.remove(i); } break; } } void addclientstate(worldstate &ws, clientinfo &ci) { if(ci.position.empty()) ci.posoff = -1; else { ci.posoff = ws.positions.length(); loopvj(ci.position) ws.positions.add(ci.position[j]); ci.poslen = ws.positions.length() - ci.posoff; ci.position.setsize(0); } if(ci.messages.empty()) ci.msgoff = -1; else { ci.msgoff = ws.messages.length(); ucharbuf p = ws.messages.reserve(16); putint(p, SV_CLIENT); putint(p, ci.clientnum); putuint(p, ci.messages.length()); ws.messages.addbuf(p); loopvj(ci.messages) ws.messages.add(ci.messages[j]); ci.msglen = ws.messages.length() - ci.msgoff; ci.messages.setsize(0); } } bool buildworldstate() { worldstate &ws = *new worldstate; loopv(clients) { clientinfo &ci = *clients[i]; if(ci.state.clienttype != CLIENT_PLAYER) continue; addclientstate(ws, ci); loopv(ci.bots) { clientinfo &bi = *ci.bots[i]; addclientstate(ws, bi); if(bi.posoff >= 0) { if(ci.posoff < 0) { ci.posoff = bi.posoff; ci.poslen = bi.poslen; } else ci.poslen += bi.poslen; } if(bi.msgoff >= 0) { if(ci.msgoff < 0) { ci.msgoff = bi.msgoff; ci.msglen = bi.msglen; } else ci.msglen += bi.msglen; } } } int psize = ws.positions.length(), msize = ws.messages.length(); if(psize) recordpacket(0, ws.positions.getbuf(), psize); if(msize) recordpacket(1, ws.messages.getbuf(), msize); loopi(psize) { uchar c = ws.positions[i]; ws.positions.add(c); } loopi(msize) { uchar c = ws.messages[i]; ws.messages.add(c); } ws.uses = 0; if(psize || msize) loopv(clients) { clientinfo &ci = *clients[i]; if(ci.state.clienttype != CLIENT_PLAYER) continue; ENetPacket *packet; if(psize && (ci.posoff<0 || psize-ci.poslen>0)) { packet = enet_packet_create(&ws.positions[ci.posoff<0 ? 0 : ci.posoff+ci.poslen], ci.posoff<0 ? psize : psize-ci.poslen, ENET_PACKET_FLAG_NO_ALLOCATE); sendpacket(ci.clientnum, 0, packet); if(!packet->referenceCount) enet_packet_destroy(packet); else { ++ws.uses; packet->freeCallback = cleanworldstate; } } if(msize && (ci.msgoff<0 || msize-ci.msglen>0)) { packet = enet_packet_create(&ws.messages[ci.msgoff<0 ? 0 : ci.msgoff+ci.msglen], ci.msgoff<0 ? msize : msize-ci.msglen, (reliablemessages ? ENET_PACKET_FLAG_RELIABLE : 0) | ENET_PACKET_FLAG_NO_ALLOCATE); sendpacket(ci.clientnum, 1, packet); if(!packet->referenceCount) enet_packet_destroy(packet); else { ++ws.uses; packet->freeCallback = cleanworldstate; } } } reliablemessages = false; if(!ws.uses) { delete &ws; return false; } else { worldstates.add(&ws); return true; } } bool sendpackets(bool force) { if(clients.empty() || (!hasnonlocalclients() && !demorecord)) return false; enet_uint32 curtime = enet_time_get()-lastsend; if(curtime<33 && !force) return false; bool flush = buildworldstate(); lastsend += curtime - (curtime%33); return flush; } template void sendstate(gamestate &gs, T &p) { //send gamestate } void spawnstate(clientinfo *ci) { gamestate &gs = ci->state; gs.spawnstate(gamemode); } void sendspawn(clientinfo *ci) { // gamestate &gs = ci->state; spawnstate(ci); // defformatstring(dbg)("DEBUG: server::sendspawn send SV_SPAWNSTATE cl: %d, state: %d", ci->clientnum, ci->state.state); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); sendf(ci->ownernum, 1, "rii", SV_SPAWNSTATE, ci->clientnum); // gs.lastspawn = gamemillis; } void sendwelcome(clientinfo *ci) { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); int chan = welcomepacket(p, ci); sendpacket(ci->clientnum, chan, p.finalize()); } //Notify new clients about existing player or bots //TODO: *no tests here, let client handle the type: // clienttype is either bot || player controltype is CONTROL_REMOTE // *remove SV_INITBOT, add clienttype, ownernum to SV_INITCLIENT void putinitclient(clientinfo *ci, packetbuf &p) { if(ci->state.clienttype != CLIENT_PLAYER) { putint(p, SV_INITBOT); putint(p, ci->clientnum); putint(p, ci->ownernum); putint(p, ci->state.clienttype); putint(p, ci->playermodel); // defformatstring(dbg)("DEBUG: server::putinitclient SV_INITBOT cl: %d", ci->clientnum); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); } else { putint(p, SV_INITCLIENT); putint(p, ci->clientnum); sendstring(ci->name, p); putint(p, ci->playermodel); // defformatstring(dbg)("DEBUG: server::putinitclient SV_INITCLIENT cl: %d, state: %d", ci->clientnum, ci->state.state); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); } } //Notify new clients about other clients (see putinitclient) void welcomeinitclient(packetbuf &p, int exclude = -1) { loopv(clients) { clientinfo *ci = clients[i]; if(!ci->connected || ci->clientnum == exclude) continue; putinitclient(ci, p); } } //Welcome Packet on connect, sends about whats going on int welcomepacket(packetbuf &p, clientinfo *ci) { int hasmap = (m_edit && (clients.length()>1 || (ci && ci->local))) || (smapname[0] && (minremain>0 || (ci && ci->state.state==CS_SPECTATOR) || numclients(ci && ci->local ? ci->clientnum : -1))); putint(p, SV_WELCOME); putint(p, hasmap); if(hasmap) { putint(p, SV_MAPCHANGE); sendstring(smapname, p); putint(p, gamemode); putint(p, notgotitems ? 1 : 0); if(!ci || (m_timed && smapname[0])) { putint(p, SV_TIMEUP); putint(p, minremain); } if(!notgotitems) { putint(p, SV_ITEMLIST); loopv(sents) if(sents[i].spawned) { putint(p, i); putint(p, sents[i].type); } putint(p, -1); } } if(gamepaused) { putint(p, SV_PAUSEGAME); putint(p, 1); } if(ci && (m_demo || m_mp(gamemode)) && ci->state.state!=CS_SPECTATOR) { // if(smode && !smode->canspawn(ci, true)) // { // ci->state.state = CS_DEAD; // putint(p, SV_FORCEDEATH); // putint(p, ci->clientnum); // sendf(-1, 1, "ri2x", SV_FORCEDEATH, ci->clientnum, ci->clientnum); // } // else // { gamestate &gs = ci->state; spawnstate(ci); // defformatstring(dbg)("DEBUG: server::welcomepacket send SV_SPAWNSTATE cl: %d", ci->clientnum); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); putint(p, SV_SPAWNSTATE); putint(p, ci->clientnum); sendstate(gs, p); // } } if(ci && ci->state.state==CS_SPECTATOR) { putint(p, SV_SPECTATOR); putint(p, ci->clientnum); putint(p, 1); sendf(-1, 1, "ri3x", SV_SPECTATOR, ci->clientnum, 1, ci->clientnum); } if(!ci || clients.length()>1) { //TODO: check SV_RESUME putint(p, SV_RESUME); loopv(clients) { clientinfo *oi = clients[i]; // defformatstring(dbg)("DEBUG: server::welcomepacket SV_SV_RESUME cl: %d, state: %d", oi->clientnum, oi->state.state); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); if(ci && oi->clientnum==ci->clientnum) continue; putint(p, oi->clientnum); putint(p, oi->state.state); // putint(p, oi->state.frags); // putint(p, oi->state.quadmillis); // sendstate(oi->state, p); //TODO: smode->sendstate(); } putint(p, -1); welcomeinitclient(p, ci ? ci->clientnum : -1); } if(smode) smode->initclient(ci, p, true); return 1; } void sendresume(clientinfo *ci) { //TODO: correct SV_RESUME // defformatstring(dbg)("DEBUG: server::sendresume ci: %d, state: %d", ci->clientnum, ci->state); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); gamestate &gs = ci->state; sendf(-1, 1, "ri3i", SV_RESUME, ci->clientnum, gs.state, -1); // sendf(-1, 1, "ri2i9vi", SV_RESUME, ci->clientnum, // gs.state, gs.frags, gs.quadmillis, // gs.lifesequence, // gs.health, gs.maxhealth, // gs.armour, gs.armourtype, // gs.gunselect, GUN_PISTOL-GUN_SG+1, &gs.ammo[GUN_SG], -1); } void sendinitclient(clientinfo *ci) { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); putinitclient(ci, p); sendpacket(-1, 1, p.finalize(), ci->clientnum); } void changemap(const char *s, int mode) { stopdemo(); pausegame(false); if(smode) smode->reset(false); botmgr::clearbot(); mapreload = false; gamemode = mode; gamemillis = 0; minremain = m_overtime ? 15 : 10; gamelimit = minremain*60000; interm = 0; copystring(smapname, s); resetitems(); notgotitems = true; upload.reset(); loopv(clients) { clientinfo *ci = clients[i]; ci->state.timeplayed += lastmillis - ci->state.lasttimeplayed; } if(!m_mp(gamemode)) kicknonlocalclients(DISC_PRIVATE); // if(m_teammode) autoteam(); // if(m_capture) smode = &capturemode; // else if(m_ctf) smode = &ctfmode; // else smode = NULL; // smode = &defaultservmode; if(smode) smode->reset(false); if(m_timed && smapname[0]) sendf(-1, 1, "ri2", SV_TIMEUP, minremain); loopv(clients) { clientinfo *ci = clients[i]; ci->mapchange(); ci->state.lasttimeplayed = lastmillis; if(m_mp(gamemode) && ci->state.state!=CS_SPECTATOR) sendspawn(ci); } botmgr::changemap(); if(m_demo) { if(clients.length()) setupdemoplayback(); } else if(demonextmatch) { demonextmatch = false; setupdemorecord(); } } struct votecount { char *map; int mode, count; votecount() {} votecount(char *s, int n) : map(s), mode(n), count(0) {} }; void checkvotes(bool force = false) { vector votes; int maxvotes = 0; loopv(clients) { clientinfo *oi = clients[i]; if(oi->state.state==CS_SPECTATOR && !oi->privilege && !oi->local) continue; if(oi->state.clienttype!=CLIENT_PLAYER) continue; maxvotes++; if(!oi->mapvote[0]) continue; votecount *vc = NULL; loopvj(votes) if(!strcmp(oi->mapvote, votes[j].map) && oi->modevote==votes[j].mode) { vc = &votes[j]; break; } if(!vc) vc = &votes.add(votecount(oi->mapvote, oi->modevote)); vc->count++; } votecount *best = NULL; loopv(votes) if(!best || votes[i].count > best->count || (votes[i].count == best->count && rnd(2))) best = &votes[i]; if(force || (best && best->count > maxvotes/2)) { if(demorecord) enddemorecord(); if(best && (best->count > (force ? 1 : maxvotes/2))) { sendservmsg(force ? "vote passed by default" : "vote passed by majority"); sendf(-1, 1, "risii", SV_MAPCHANGE, best->map, best->mode, 1); print((force ? "admin/master forced map change to %s" : "map change vote passed for %s" ), best->map); changemap(best->map, best->mode); } else { mapreload = true; if(clients.length()) sendf(-1, 1, "ri", SV_MAPRELOAD); } } } void forcemap(const char *map, int mode) { stopdemo(); if(hasnonlocalclients() && !mapreload) { defformatstring(msg)("local player forced %s on map %s", modename(mode), map); sendservmsg(msg); } sendf(-1, 1, "risii", SV_MAPCHANGE, map, mode, 1); changemap(map, mode); } void vote(char *map, int reqmode, int sender) { clientinfo *ci = getinfo(sender); if(!ci || (ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) || (!ci->local && !m_mp(reqmode))) return; copystring(ci->mapvote, map); ci->modevote = reqmode; if(!ci->mapvote[0]) return; if(ci->local || mapreload || (ci->privilege && mastermode>=MM_VETO)) { if(demorecord) enddemorecord(); if((!ci->local || hasnonlocalclients()) && !mapreload) { defformatstring(msg)("%s forced %s on map %s", ci->privilege && mastermode>=MM_VETO ? privname(ci->privilege) : "local player", modename(ci->modevote), ci->mapvote); sendservmsg(msg); } sendf(-1, 1, "risii", SV_MAPCHANGE, ci->mapvote, ci->modevote, 1); changemap(ci->mapvote, ci->modevote); } else { defformatstring(msg)("%s suggests %s on map %s (select map to vote)", colorname(ci), modename(reqmode), map); sendservmsg(msg); checkvotes(); } } void checkintermission() { if(minremain>0) { minremain = gamemillis>=gamelimit ? 0 : (gamelimit - gamemillis + 60000 - 1)/60000; sendf(-1, 1, "ri2", SV_TIMEUP, minremain); if(!minremain && smode) smode->intermission(); } if(!interm && minremain<=0) interm = gamemillis+10000; } void startintermission() { gamelimit = min(gamelimit, gamemillis); checkintermission(); } void dodamage(clientinfo *target, clientinfo *actor, int damage, int gun, const vec &hitpush = vec(0, 0, 0)) { // gamestate &ts = target->state; // ts.dodamage(damage); // actor->state.damage += damage; // sendf(-1, 1, "ri6", SV_DAMAGE, target->clientnum, actor->clientnum, damage, ts.armour, ts.health); // if(target!=actor && !hitpush.iszero()) // { // ivec v = vec(hitpush).rescale(DNF); // sendf(ts.health<=0 ? -1 : target->ownernum, 1, "ri7", SV_HITPUSH, target->clientnum, gun, damage, v.x, v.y, v.z); // } // if(ts.health<=0) // { // target->state.deaths++; //// if(actor!=target && isteam(actor->team, target->team)) actor->state.teamkills++; //// int fragvalue = smode ? smode->fragvalue(target, actor) : (target==actor || isteam(target->team, actor->team) ? -1 : 1); // int fragvalue = smode ? smode->fragvalue(target, actor) : (target==actor ? -1 : 1); // actor->state.frags += fragvalue; // if(fragvalue>0) // { // int friends = 0, enemies = 0; // note: friends also includes the fragger //// if(m_teammode) loopv(clients) if(strcmp(clients[i]->team, actor->team)) enemies++; else friends++; //// else { friends = 1; enemies = clients.length()-1; } // friends = 1; enemies = clients.length()-1; // actor->state.effectiveness += fragvalue*friends/float(max(enemies, 1)); // } // sendf(-1, 1, "ri4", SV_DIED, target->clientnum, actor->clientnum, actor->state.frags); // target->position.setsize(0); // if(smode) smode->died(target, actor); // ts.state = CS_DEAD; // ts.lastdeath = gamemillis; // // don't issue respawn yet until DEATHMILLIS has elapsed // // ts.respawn(); // } } void explodeevent::process(clientinfo *ci) { // gamestate &gs = ci->state; // switch(gun) // { // case GUN_RL: // if(!gs.rockets.remove(id)) return; // break; // // case GUN_GL: // if(!gs.grenades.remove(id)) return; // break; // // default: // return; // } // loopv(hits) // { // hitinfo &h = hits[i]; // clientinfo *target = getinfo(h.target); // if(!target || target->state.state!=CS_ALIVE || h.lifesequence!=target->state.lifesequence || h.dist<0 || h.dist>RL_DAMRAD) continue; // // bool dup = false; // loopj(i) if(hits[j].target==h.target) { dup = true; break; } // if(dup) continue; // // int damage = guns[gun].damage; // if(gs.quadmillis) damage *= 4; // damage = int(damage*(1-h.dist/RL_DISTSCALE/RL_DAMRAD)); // if(gun==GUN_RL && target==ci) damage /= RL_SELFDAMDIV; // dodamage(target, ci, damage, gun, h.dir); // } } void shotevent::process(clientinfo *ci) { // gamestate &gs = ci->state; // int wait = millis - gs.lastshot; // if(!gs.isalive(gamemillis) || // waitGUN_PISTOL || // gs.ammo[gun]<=0) // return; // if(gun!=GUN_FIST) gs.ammo[gun]--; // gs.lastshot = millis; // gs.gunwait = guns[gun].attackdelay; // sendf(-1, 1, "ri9x", SV_SHOTFX, ci->clientnum, gun, // int(from.x*DMF), int(from.y*DMF), int(from.z*DMF), // int(to.x*DMF), int(to.y*DMF), int(to.z*DMF), // ci->ownernum); // gs.shotdamage += guns[gun].damage*(gs.quadmillis ? 4 : 1)*(gun==GUN_SG ? SGRAYS : 1); // switch(gun) // { // case GUN_RL: gs.rockets.add(id); break; // case GUN_GL: gs.grenades.add(id); break; // default: // { // int totalrays = 0, maxrays = gun==GUN_SG ? SGRAYS : 1; // loopv(hits) // { // hitinfo &h = hits[i]; // clientinfo *target = getinfo(h.target); // if(!target || target->state.state!=CS_ALIVE || h.lifesequence!=target->state.lifesequence || h.rays<1) continue; // // totalrays += h.rays; // if(totalrays>maxrays) continue; // int damage = h.rays*guns[gun].damage; // if(gs.quadmillis) damage *= 4; // dodamage(target, ci, damage, gun, h.dir); // } // break; // } // } } void pickupevent::process(clientinfo *ci) { // gamestate &gs = ci->state; // if(m_mp(gamemode) && !gs.isalive(gamemillis)) return; // pickup(ent, ci->clientnum); } bool gameevent::flush(clientinfo *ci, int fmillis) { process(ci); return true; } bool timedevent::flush(clientinfo *ci, int fmillis) { if(millis > fmillis) return false; else if(millis >= ci->lastevent) { ci->lastevent = millis; process(ci); } return true; } void clearevent(clientinfo *ci) { delete ci->events.remove(0); } void flushevents(clientinfo *ci, int millis) { while(ci->events.length()) { gameevent *ev = ci->events[0]; if(ev->flush(ci, millis)) clearevent(ci); else break; } } void processevents() { loopv(clients) { clientinfo *ci = clients[i]; // if(curtime>0 && ci->state.quadmillis) ci->state.quadmillis = max(ci->state.quadmillis-curtime, 0); flushevents(ci, gamemillis); } } void cleartimedevents(clientinfo *ci) { int keep = 0; loopv(ci->events) { if(ci->events[i]->keepable()) { if(keep < i) { for(int j = keep; j < i; j++) delete ci->events[j]; ci->events.remove(keep, i - keep); i = keep; } keep = i+1; continue; } } while(ci->events.length() > keep) delete ci->events.pop(); ci->timesync = false; } bool ispaused() { return gamepaused; } void serverupdate() { if(!gamepaused) gamemillis += curtime; if(m_demo) readdemo(); else if(!gamepaused && minremain>0) { processevents(); if(curtime) { loopv(sents) if(sents[i].spawntime) // spawn entities when timer reached { int oldtime = sents[i].spawntime; sents[i].spawntime -= curtime; if(sents[i].spawntime<=0) { sents[i].spawntime = 0; sents[i].spawned = true; sendf(-1, 1, "ri2", SV_ITEMSPAWN, i); } // else if(sents[i].spawntime<=10000 && oldtime>10000 && (sents[i].type==I_QUAD || sents[i].type==I_BOOST)) // { // sendf(-1, 1, "ri2", SV_ANNOUNCE, sents[i].type); // } } } botmgr::checkbot(); if(smode) smode->update(); } while(bannedips.length() && bannedips[0].time-totalmillis>4*60*60000) bannedips.remove(0); loopv(connects) if(totalmillis-connects[i]->connectmillis>15000) disconnect_client(connects[i]->clientnum, DISC_TIMEOUT); if(masterupdate) { clientinfo *m = currentmaster>=0 ? getinfo(currentmaster) : NULL; sendf(-1, 1, "ri3", SV_CURRENTMASTER, currentmaster, m ? m->privilege : 0); masterupdate = false; } if(!gamepaused && m_timed && smapname[0] && gamemillis-curtime>0 && gamemillis/60000!=(gamemillis-curtime)/60000) checkintermission(); if(interm && gamemillis>interm) { if(demorecord) enddemorecord(); interm = 0; checkvotes(true); } } struct crcinfo { int crc, matches; crcinfo(int crc, int matches) : crc(crc), matches(matches) {} static int compare(const crcinfo *x, const crcinfo *y) { if(x->matches > y->matches) return -1; if(x->matches < y->matches) return 1; return 0; } }; void checkmaps(int req = -1) { if(m_edit || !smapname[0]) return; vector crcs; int total = 0, unsent = 0, invalid = 0; loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_SPECTATOR || ci->state.clienttype != CLIENT_PLAYER) continue; total++; if(!ci->clientmap[0]) { if(ci->mapcrc < 0) invalid++; else if(!ci->mapcrc) unsent++; } else { crcinfo *match = NULL; loopvj(crcs) if(crcs[j].crc == ci->mapcrc) { match = &crcs[j]; break; } if(!match) crcs.add(crcinfo(ci->mapcrc, 1)); else match->matches++; } } if(total - unsent < min(total, 4)) return; crcs.sort(crcinfo::compare); string msg; loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_SPECTATOR || ci->state.clienttype != CLIENT_PLAYER || ci->clientmap[0] || ci->mapcrc >= 0 || (req < 0 && ci->warned)) continue; formatstring(msg)("%s has modified map \"%s\"", colorname(ci), smapname); sendf(req, 1, "ris", SV_SERVMSG, msg); if(req < 0) ci->warned = true; } if(crcs.empty() || crcs.length() < 2) return; loopv(crcs) { crcinfo &info = crcs[i]; if(i || info.matches <= crcs[i+1].matches) loopvj(clients) { clientinfo *ci = clients[j]; if(ci->state.state==CS_SPECTATOR || ci->state.clienttype != CLIENT_PLAYER || !ci->clientmap[0] || ci->mapcrc != info.crc || (req < 0 && ci->warned)) continue; formatstring(msg)("%s has modified map \"%s\"", colorname(ci), smapname); sendf(req, 1, "ris", SV_SERVMSG, msg); if(req < 0) ci->warned = true; } } } void sendservinfo(clientinfo *ci) { sendf(ci->clientnum, 1, "ri5", SV_SERVINFO, ci->clientnum, PROTOCOL_VERSION, ci->sessionid, serverpass[0] ? 1 : 0); } void noclients() { bannedips.shrink(0); botmgr::clearbot(); } void localconnect(int n) { clientinfo *ci = getinfo(n); ci->clientnum = ci->ownernum = n; ci->connectmillis = totalmillis; ci->sessionid = (rnd(0x1000000)*((totalmillis%10000)+1))&0xFFFFFF; ci->local = true; connects.add(ci); sendservinfo(ci); } void localdisconnect(int n) { if(m_demo) enddemoplayback(); clientdisconnect(n); } int clientconnect(int n, uint ip) { clientinfo *ci = getinfo(n); ci->clientnum = ci->ownernum = n; ci->connectmillis = totalmillis; ci->sessionid = (rnd(0x1000000)*((totalmillis%10000)+1))&0xFFFFFF; connects.add(ci); if(!m_mp(gamemode)) return DISC_PRIVATE; sendservinfo(ci); return DISC_NONE; } void clientdisconnect(int n) { clientinfo *ci = getinfo(n); if(ci->connected) { if(ci->privilege) setmaster(ci, false); if(smode) smode->leavegame(ci, true); ci->state.timeplayed += lastmillis - ci->state.lasttimeplayed; // savescore(ci); sendf(-1, 1, "ri2", SV_CDIS, n); // defformatstring(dbg)("DEBUG: server::clientdisconnect send SV_CDIS cl: %d", ci->clientnum); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); clients.removeobj(ci); botmgr::removebot(ci); if(!numclients(-1, false, true)) noclients(); // bans clear when server empties } else connects.removeobj(ci); } int reserveclients() { return 3; } int allowconnect(clientinfo *ci, const char *pwd) { if(ci->local) return DISC_NONE; if(!m_mp(gamemode)) return DISC_PRIVATE; if(serverpass[0]) { if(!checkpassword(ci, serverpass, pwd)) return DISC_PRIVATE; return DISC_NONE; } if(adminpass[0] && checkpassword(ci, adminpass, pwd)) return DISC_NONE; if(numclients(-1, false, true)>=maxclients) return DISC_MAXCLIENTS; uint ip = getclientip(ci->clientnum); loopv(bannedips) if(bannedips[i].ip==ip) return DISC_IPBAN; if(mastermode>=MM_PRIVATE && allowedips.find(ip)<0) return DISC_PRIVATE; return DISC_NONE; } bool allowbroadcast(int n) { clientinfo *ci = getinfo(n); return ci && ci->connected; } clientinfo *findauth(uint id) { loopv(clients) if(clients[i]->authreq == id) return clients[i]; return NULL; } void authfailed(uint id) { clientinfo *ci = findauth(id); if(!ci) return; ci->authreq = 0; } void authsucceeded(uint id) { clientinfo *ci = findauth(id); if(!ci) return; ci->authreq = 0; setmaster(ci, true, "", ci->authname); } void authchallenged(uint id, const char *val) { clientinfo *ci = findauth(id); if(!ci) return; sendf(ci->clientnum, 1, "risis", SV_AUTHCHAL, "", id, val); } uint nextauthreq = 0; void tryauth(clientinfo *ci, const char *user) { if(!nextauthreq) nextauthreq = 1; ci->authreq = nextauthreq++; filtertext(ci->authname, user, false, 100); if(!requestmasterf("reqauth %u %s\n", ci->authreq, ci->authname)) { ci->authreq = 0; sendf(ci->clientnum, 1, "ris", SV_SERVMSG, "not connected to authentication server"); } } void answerchallenge(clientinfo *ci, uint id, char *val) { if(ci->authreq != id) return; for(char *s = val; *s; s++) { if(!isxdigit(*s)) { *s = '\0'; break; } } if(!requestmasterf("confauth %u %s\n", id, val)) { ci->authreq = 0; sendf(ci->clientnum, 1, "ris", SV_SERVMSG, "not connected to authentication server"); } } void processmasterinput(const char *cmd, int cmdlen, const char *args) { uint id; string val; if(sscanf(cmd, "failauth %u", &id) == 1) authfailed(id); else if(sscanf(cmd, "succauth %u", &id) == 1) authsucceeded(id); else if(sscanf(cmd, "chalauth %u %s", &id, val) == 2) authchallenged(id, val); } void receivefile(int sender, uchar *data, int len) { //we upload map data and cfg's, monitored by "mapdata upload" ucharbuf p(data, len); int type = getint(p); char name[MAXTRANS]; getstring(name, p); data += p.length(); len -= p.length(); if(!len) return; switch(type) { case SV_UPLOADMAP: { clientinfo *ci = getinfo(sender); if(ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) return; if(!upload.status || upload.finished()) upload.init(ci->clientnum, name); else if(!upload.check(ci->clientnum, name)) return; if(!m_edit || len > 1024*1024) { conoutf("map is too large"); return; } upload.map = opentempfile("mapdata", "w+b"); if(!upload.map) { sendf(sender, 1, "ris", SV_SERVMSG, "failed to open temporary file for map"); upload.reset(); return; } upload.map->write(data, len); upload.status |= MD_GOTMAP; if(upload.finished()) { defformatstring(msg)("[%s uploaded map to server, \"/getmap\" to receive it]", colorname(ci)); #ifdef STANDALONE conoutf("received map from %s(%i)", ci->name, ci->clientnum); #endif sendservmsg(msg); } break; } case SV_UPLOADCFG: { clientinfo *ci = getinfo(sender); if(ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) return; if(!upload.status || upload.finished()) upload.init(ci->clientnum, name); else if(!upload.check(ci->clientnum, name)) return; upload.cfg = opentempfile("cfgdata", "w+b"); if(!upload.cfg) { sendf(sender, 1, "ris", SV_SERVMSG, "failed to open temporary file for cfg"); upload.reset(); return; } upload.cfg->write(data, len); upload.status |= MD_GOTCFG; if(upload.finished()) { defformatstring(msg)("[%s uploaded map to server, \"/getmap\" to receive it]", colorname(ci)); #ifdef STANDALONE conoutf("received map from %s(%i)", ci->name, ci->clientnum); #endif sendservmsg(msg); } break; } } } void parsepacket(int sender, int chan, packetbuf &p) // has to parse exactly each byte of the packet { if(sender<0) return; char text[MAXTRANS]; int type; clientinfo *ci = sender>=0 ? getinfo(sender) : NULL, *cq = ci, *cm = ci; if(ci && !ci->connected) { if(chan==0) return; else if(chan!=1 || getint(p)!=SV_CONNECT) { disconnect_client(sender, DISC_TAGT); return; } else { getstring(text, p); filtertext(text, text, false, MAXNAMELEN); if(!text[0]) copystring(text, "unnamed"); copystring(ci->name, text, MAXNAMELEN+1); getstring(text, p); int disc = allowconnect(ci, text); if(disc) { disconnect_client(sender, disc); return; } ci->playermodel = getint(p); if(m_demo) enddemoplayback(); connects.removeobj(ci); clients.add(ci); ci->connected = true; if(mastermode>=MM_LOCKED) ci->state.state = CS_SPECTATOR; if(currentmaster>=0) masterupdate = true; ci->state.lasttimeplayed = lastmillis; sendwelcome(ci); sendresume(ci); sendinitclient(ci); botmgr::addclient(ci); if(m_demo) setupdemoplayback(); if(servermotd[0]) sendf(sender, 1, "ris", SV_SERVMSG, servermotd); } } else if(chan==2) { receivefile(sender, p.buf, p.maxlen); return; } if(p.packet->flags&ENET_PACKET_FLAG_RELIABLE) reliablemessages = true; #define QUEUE_AI clientinfo *cm = cq; #define QUEUE_MSG { if(cm && (!cm->local || demorecord || hasnonlocalclients())) while(curmsgmessages.add(p.buf[curmsg++]); } #define QUEUE_BUF(size, body) { \ if(cm && (!cm->local || demorecord || hasnonlocalclients())) \ { \ curmsg = p.length(); \ ucharbuf buf = cm->messages.reserve(size); \ { body; } \ cm->messages.addbuf(buf); \ } \ } #define QUEUE_INT(n) QUEUE_BUF(5, putint(buf, n)) #define QUEUE_UINT(n) QUEUE_BUF(4, putuint(buf, n)) #define QUEUE_STR(text) QUEUE_BUF(2*strlen(text)+1, sendstring(text, buf)) int curmsg; while((curmsg = p.length()) < p.maxlen) switch(type = checktype(getint(p), ci)) { case SV_POS: { int pcn = getint(p); clientinfo *cp = getinfo(pcn); if(cp && pcn != sender && cp->ownernum != sender) cp = NULL; vec pos; loopi(3) pos[i] = getuint(p)/DMF; getuint(p); loopi(5) getint(p); int physstate = getuint(p); if(physstate&0x20) loopi(2) getint(p); if(physstate&0x10) getint(p); getuint(p); if(cp) { if((!ci->local || demorecord || hasnonlocalclients()) && (cp->state.state==CS_ALIVE || cp->state.state==CS_EDITING)) { cp->position.setsize(0); while(curmsgposition.add(p.buf[curmsg++]); } cp->state.o = pos; cp->gameclip = (physstate&0x80)!=0; } break; } case SV_FROMBOT: { int qcn = getint(p); if(qcn < 0) cq = ci; else { cq = getinfo(qcn); if(cq && qcn != sender && cq->ownernum != sender) cq = NULL; } break; } case SV_EDITMODE: { int val = getint(p); if(!ci->local && !m_edit) break; if(val ? ci->state.state!=CS_ALIVE && ci->state.state!=CS_DEAD : ci->state.state!=CS_EDITING) break; if(smode) { if(val) smode->leavegame(ci); else smode->entergame(ci); } if(val) { ci->state.editstate = ci->state.state; ci->state.state = CS_EDITING; ci->events.setsize(0); } else ci->state.state = ci->state.editstate; QUEUE_MSG; break; } case SV_MAPCRC: { getstring(text, p); int crc = getint(p); if(!ci) break; if(strcmp(text, smapname)) { if(ci->clientmap[0]) { ci->clientmap[0] = '\0'; ci->mapcrc = 0; } else if(ci->mapcrc > 0) ci->mapcrc = 0; break; } copystring(ci->clientmap, text); ci->mapcrc = text[0] ? crc : 1; checkmaps(); print("(%s(%i)) map CRC %s: %i", ci->name, ci->clientnum, ci->clientmap, ci->mapcrc); break; } case SV_CHECKMAPS: checkmaps(sender); break; case SV_TRYSPAWN: // if(!ci || !cq || cq->state.state!=CS_DEAD || cq->state.lastspawn>=0 || (smode && !smode->canspawn(cq))) break; if(!ci || !cq || cq->state.state!=CS_DEAD || (smode && !smode->canspawn(cq))) break; if(!ci->clientmap[0] && !ci->mapcrc) { ci->mapcrc = -1; checkmaps(); } // defformatstring(dbg)("DEBUG: server::parsepacket SV_TRYSPAWN cl: %d on: %d, clienttype: %d, state: %d", cq->clientnum, cq->ownernum, cq->state.clienttype, cq->state.state); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); cleartimedevents(cq); sendspawn(cq); break; case SV_SPAWN: { // defformatstring(dbg2)("1DEBUG: server::parsepacket SV_SPAWN"); // sendf(-1, 1, "ris", SV_SERVMSG, dbg2); if(!cq || (cq->state.state!=CS_ALIVE && cq->state.state!=CS_DEAD) ) break; cq->state.state = CS_ALIVE; if(smode) smode->spawned(cq); // // defformatstring(dbg)("2DEBUG: server::parsepacket SV_SPAWN cl: %d on: %d, state: %d, clienttype: %d", cq->clientnum, cq->ownernum, cq->state.state, cq->state.clienttype); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); QUEUE_AI; QUEUE_BUF(100, { putint(buf, SV_SPAWN); sendstate(cq->state, buf); }); // defformatstring(dbg1)("3DEBUG: server::parsepacket QUEUE SV_SPAWN cl: %d on: %d, clienttype: %d", cq->clientnum, cq->ownernum, cq->state.clienttype); // sendf(-1, 1, "ris", SV_SERVMSG, dbg1); break; } case SV_SHOOT: { shotevent *shot = new shotevent; shot->id = getint(p); shot->millis = cq ? cq->geteventmillis(gamemillis, shot->id) : 0; shot->gun = getint(p); loopk(3) shot->from[k] = getint(p)/DMF; loopk(3) shot->to[k] = getint(p)/DMF; int hits = getint(p); loopk(hits) { if(p.overread()) break; hitinfo &hit = shot->hits.add(); hit.target = getint(p); hit.lifesequence = getint(p); hit.rays = getint(p); loopk(3) hit.dir[k] = getint(p)/DNF; } if(cq) cq->addevent(shot); else delete shot; break; } case SV_EXPLODE: { explodeevent *exp = new explodeevent; int cmillis = getint(p); exp->millis = cq ? cq->geteventmillis(gamemillis, cmillis) : 0; exp->gun = getint(p); exp->id = getint(p); int hits = getint(p); loopk(hits) { if(p.overread()) break; hitinfo &hit = exp->hits.add(); hit.target = getint(p); hit.lifesequence = getint(p); hit.dist = getint(p)/DMF; loopk(3) hit.dir[k] = getint(p)/DNF; } if(cq) cq->addevent(exp); else delete exp; break; } case SV_ITEMPICKUP: { int n = getint(p); if(!cq) break; pickupevent *pickup = new pickupevent; pickup->ent = n; cq->addevent(pickup); break; } case SV_TEXT: { int mtype = getint(p); getstring(text, p); filtertext(text, text); if(mtype&CHAT_TEAM) { if(!ci || !cq || (ci->state.state==CS_SPECTATOR && !ci->local && !ci->privilege) ) break; // if(!ci || !cq || (ci->state.state==CS_SPECTATOR && !ci->local && !ci->privilege) || !m_teammode || !cq->team[0]) break; loopv(clients) { clientinfo *t = clients[i]; if(t==cq || t->state.state==CS_SPECTATOR || t->state.clienttype != CLIENT_PLAYER ) continue; // if(t==cq || t->state.state==CS_SPECTATOR || t->state.clienttype != CLIENT_PLAYER || strcmp(cq->team, t->team)) continue; sendf(t->clientnum, 1, "riiis", SV_TEXT, cq->clientnum, mtype, text); } if(mtype&CHAT_EMOTE) { print(" *%s(%i) %s", colorname(ci), ci->clientnum, text); } else print(" <%s(%i)> %s", colorname(ci), ci->clientnum, text); } else //it would probably be TEXT... otherwise { loopv(clients) { clientinfo *t = clients[i]; if(t==ci || t->state.clienttype != CLIENT_PLAYER) continue; sendf(t->clientnum, 1, "riiis", SV_TEXT, ci->clientnum, mtype, text); } if(mtype&CHAT_EMOTE) { print("*%s(%i) %s", colorname(ci), ci->clientnum, text); } else print("<%s(%i)> %s", colorname(ci), ci->clientnum, text); } break; } case SV_SWITCHNAME: { QUEUE_MSG; string tmp; copystring(tmp, ci->name); getstring(text, p); filtertext(ci->name, text, false, MAXNAMELEN); if(!ci->name[0]) copystring(ci->name, "unnamed"); QUEUE_STR(ci->name); print("%s(%i) changed name to %s", tmp, ci->clientnum, ci->name); break; } case SV_SWITCHMODEL: { cq->playermodel = getint(p); // defformatstring(dbg)("DEBUG: server::parsepacket SV_SWITCHMODEL cl: %d, bot: %d state: %d", ci->clientnum, cq->clientnum, ci->state.state); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); //sendf(-1, 1, "riii", SV_SWITCHMODEL, cq->clientnum, cq->playermodel); //ci->playermodel = getint(p); QUEUE_MSG; break; } // case SV_SWITCHTEAM: // { // getstring(text, p); // filtertext(text, text, false, MAXTEAMLEN); // if(strcmp(ci->team, text)) // { // if(m_teammode && smode && !smode->canchangeteam(ci, ci->team, text)) // sendf(sender, 1, "riis", SV_SETTEAM, sender, ci->team); // else // { // if(smode && ci->state.state==CS_ALIVE) smode->changeteam(ci, ci->team, text); // copystring(ci->team, text); // botmgr::changeteam(ci); // sendf(-1, 1, "riis", SV_SETTEAM, sender, ci->team); // } // print("%s changed teams to %s", ci->name, ci->team); // } // break; // } case SV_MAPVOTE: case SV_MAPCHANGE: { getstring(text, p); filtertext(text, text, false); int reqmode = getint(p); if(type!=SV_MAPVOTE && !mapreload) break; vote(text, reqmode, sender); break; } case SV_ITEMLIST: { if((ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) || !notgotitems || strcmp(ci->clientmap, smapname)) { while(getint(p)>=0 && !p.overread()) getint(p); break; } int n; while((n = getint(p))>=0 && nstate.state==CS_SPECTATOR) break; QUEUE_MSG; bool canspawn = canspawnitem(type); if(istate.state==CS_SPECTATOR && !ci->privilege && !ci->local) || strcmp(ci->clientmap, smapname)) { while(getint(p)>=-1 && !p.overread()) getint(p); break; } // int n; // while((n = getint(p))>=-1 && n= 0 && uid < lastmapuid) continue; // // uid < 0 ? uid = ++lastmapuid : lastmapuid = uid; // // server_entity se = { NOTUSED, 0, false, uid }; // sents.add(se); // //NOTE: send map uid - is this necessary // if(uid >= 0) sendf(-1, 1, "riii", SV_MAPUID, n, uid); // } // break; // // } case SV_EDITVAR: { int type = getint(p); getstring(text, p); string tmp; copystring(tmp, text); int a = 0; float b = 0; switch(type) { case ID_VAR: a = getint(p); break; case ID_FVAR: b = getfloat(p); break; case ID_SVAR: getstring(text, p); break; } if(!ci || ci->state.state==CS_SPECTATOR) break; switch(type) { case ID_VAR: { print("%s(%i) set map variable \"%s\" to %i", ci->name, ci->clientnum, tmp, a); break; } case ID_FVAR: { print("%s(%i) set map variable \"%s\" to %f", ci->name, ci->clientnum, tmp, b); break; } case ID_SVAR: print("%s(%i) set map variable \"%s\" to %s", ci->name, ci->clientnum, tmp, text); break; } QUEUE_MSG; break; } case SV_PING: sendf(sender, 1, "i2", SV_PONG, getint(p)); break; case SV_CLIENTPING: { int ping = getint(p); if(ci) { ci->ping = ping; loopv(ci->bots) ci->bots[i]->ping = ping; } QUEUE_MSG; break; } case SV_MASTERMODE: { int mm = getint(p); if((ci->privilege || ci->local) && mm>=MM_OPEN && mm<=MM_PRIVATE) { if((ci->privilege>=PRIV_ADMIN || ci->local) || (mastermask&(1<=MM_PRIVATE) { loopv(clients) allowedips.add(getclientip(clients[i]->clientnum)); } defformatstring(s)("mastermode is now %s (%d)", mastermodename(mastermode), mastermode); print("%s(%i) set mastermode to %s (%d)", ci->name, ci->clientnum, mastermodename(mastermode), mastermode); sendservmsg(s); } else { defformatstring(s)("mastermode %d is disabled on this server", mm); sendf(sender, 1, "ris", SV_SERVMSG, s); } } break; } case SV_CLEARBANS: { if(ci->privilege || ci->local) { bannedips.shrink(0); sendservmsg("cleared all bans"); print("%s(%i) cleared bans", ci->name, ci->clientnum); } break; } case SV_KICK: { int victim = getint(p); if((ci->privilege || ci->local) && ci->clientnum!=victim && getclientinfo(victim)) // no bots { ban &b = bannedips.add(); b.time = totalmillis; b.ip = getclientip(victim); allowedips.removeobj(b.ip); print("%s(%i) kicked %s(%i)", ci->name, ci->clientnum, ((clientinfo *)getclientinfo(victim))->name, victim); disconnect_client(victim, DISC_KICK); } break; } case SV_SPECTATOR: { int spectator = getint(p), val = getint(p); if(!ci->privilege && !ci->local && (spectator!=sender || (ci->state.state==CS_SPECTATOR && mastermode>=MM_LOCKED))) break; clientinfo *spinfo = (clientinfo *)getclientinfo(spectator); // no bots if(!spinfo || (spinfo->state.state==CS_SPECTATOR ? val : !val)) break; if(spinfo->state.state!=CS_SPECTATOR && val) { // if(spinfo->state.state==CS_ALIVE) suicide(spinfo); if(smode) smode->leavegame(spinfo); spinfo->state.state = CS_SPECTATOR; spinfo->state.timeplayed += lastmillis - spinfo->state.lasttimeplayed; if(!spinfo->local && !spinfo->privilege) botmgr::removebot(spinfo); if(spectator!=sender) { print("%s(%i) turned %s(%i) into a spectator", ci->name, ci->clientnum, spinfo->name, spinfo->clientnum); } else print("%s(%i) turned himself into a spectator", ci->name, ci->clientnum); } else if(spinfo->state.state==CS_SPECTATOR && !val) { spinfo->state.state = CS_DEAD; spinfo->state.respawn(); spinfo->state.lasttimeplayed = lastmillis; botmgr::addclient(spinfo); if(spinfo->clientmap[0] || spinfo->mapcrc) checkmaps(); if(spectator!=sender) { print("%s(%i) kicked %s(%i) out of spectator mode", ci->name, ci->clientnum, spinfo->name, spinfo->clientnum); } else print("%s(%i) kicked himself out of spectator mode", ci->name, ci->clientnum); } sendf(-1, 1, "ri3", SV_SPECTATOR, spectator, val); break; } // case SV_SETTEAM: // { // int who = getint(p); // getstring(text, p); // filtertext(text, text, false, MAXTEAMLEN); // if(!ci->privilege && !ci->local) break; // clientinfo *wi = getinfo(who); // if(!wi || !strcmp(wi->team, text)) break; // if(!smode || smode->canchangeteam(wi, wi->team, text)) // { // if(smode && wi->state.state==CS_ALIVE) // smode->changeteam(wi, wi->team, text); // copystring(wi->team, text, MAXTEAMLEN+1); // if(who!=sender) // { // print("%s(%i) forced %s(%i) onto team %s", ci->name, ci->clientnum, wi->name, wi->clientnum, wi->team); // } // else // print("%s(%i) changed to team %s", ci->name, ci->clientnum, wi->team); // } // botmgr::changeteam(wi); // sendf(-1, 1, "riis", SV_SETTEAM, who, wi->team); // break; // } case SV_FORCEINTERMISSION: if(ci->local && !hasnonlocalclients()) startintermission(); break; case SV_RECORDDEMO: { int val = getint(p); if(ci->privilegelocal) break; demonextmatch = val!=0; defformatstring(msg)("demo recording is %s for next match", demonextmatch ? "enabled" : "disabled"); sendservmsg(msg); break; } case SV_STOPDEMO: { if(ci->privilegelocal) break; stopdemo(); break; } case SV_CLEARDEMOS: { int demo = getint(p); if(ci->privilegelocal) break; cleardemos(demo); break; } case SV_LISTDEMOS: if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break; listdemos(sender); break; case SV_GETDEMO: { int n = getint(p); if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break; senddemo(sender, n); break; } case SV_GETMAP: if(upload.finished()) { sendf(sender, 1, "ris", SV_SERVMSG, "server sending map..."); defformatstring(id)("%d", lastmillis); sendfile(sender, 2, upload.cfg, "ris", SV_SENDCFG, id); sendfile(sender, 2, upload.map, "ris", SV_SENDMAP, id); } else sendf(sender, 1, "ris", SV_SERVMSG, "no map to send"); break; case SV_NEWMAP: { int size = getint(p); if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break; if(size>=0) { smapname[0] = '\0'; resetitems(); notgotitems = false; if(smode) smode->reset(true); } QUEUE_MSG; break; } case SV_SETMASTER: { int val = getint(p); getstring(text, p); setmaster(ci, val!=0, text); // don't broadcast the master password break; } case SV_BOTLIMIT: { int limit = getint(p); if(ci) botmgr::setbotlimit(ci, limit); break; } case SV_BOTBALANCE: { int balance = getint(p); if(ci) botmgr::setbotbalance(ci, balance!=0); break; } case SV_AUTHTRY: { string desc, name; getstring(desc, p, sizeof(desc)); // unused for now getstring(name, p, sizeof(name)); if(!desc[0]) tryauth(ci, name); break; } case SV_AUTHANS: { string desc, ans; getstring(desc, p, sizeof(desc)); // unused for now uint id = (uint)getint(p); getstring(ans, p, sizeof(ans)); if(!desc[0]) answerchallenge(ci, id, ans); break; } case SV_PAUSEGAME: { int val = getint(p); if(ci->privilegelocal) break; pausegame(val > 0); break; } case SV_TEXTUREREQUEST: { getstring(text, p); int slot = getint(p); if(!serverupload) return; stream* file = openrawfile(text, "rb"); if(file) { defformatstring(texmsg)("server - sending texture: %s", text); sendf(sender, 1, "ris", SV_SERVMSG, texmsg); sendfile(sender, 2, file, "risi", SV_SENDTEXTURE, text, slot); } else { defformatstring(err)("server - texture: %s not found", text); sendf(sender, 1, "ris", SV_SERVMSG, err); } break; } //__offtools__ attachments: attach stuff case SV_ATTACH: { getint(p); // defformatstring(dbg)("DEBUG: server::parsepacket SV_ATTACH cl: %d, bot: %d, %d", ci->clientnum, cq->clientnum, item); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); QUEUE_MSG; break; } //__offtools__ attachments: detach stuff case SV_DETACH: { getint(p); QUEUE_MSG; break; } case SV_REQUESTBOT: { botmgr::reqadd(ci); break; } case SV_DELETEBOT: { clientinfo* bot = getinfo(getint(p)); botmgr::deletebot(bot); break; } default: { int size = server::msgsizelookup(type); if(size==-1) { disconnect_client(sender, DISC_TAGT); return; } if(size>0) loopi(size-1) getint(p); if(ci && cq && (ci != cq || ci->state.state!=CS_SPECTATOR)) { QUEUE_AI; QUEUE_MSG; } break; } } } int laninfoport() { return MOVIECUBE_LANINFO_PORT; } int serverinfoport(int servport) { return servport < 0 ? MOVIECUBE_SERVINFO_PORT : servport+1; } int serverport(int infoport) { return infoport < 0 ? MOVIECUBE_SERVER_PORT : infoport-1; } const char *defaultmaster() { return "master.sandboxgamemaker.com"; } int masterport() { return MOVIECUBE_MASTER_PORT; } int numchannels() { return 3; } #include "extinfo.h" void serverinforeply(ucharbuf &req, ucharbuf &p) { if(!getint(req)) { extserverinforeply(req, p); return; } putint(p, numclients(-1, false, true)); putint(p, 5); // number of attrs following putint(p, PROTOCOL_VERSION); // a // generic attributes, passed back below putint(p, gamemode); // b putint(p, minremain); // c putint(p, maxclients); putint(p, serverpass[0] ? MM_PASSWORD : (!m_mp(gamemode) ? MM_PRIVATE : (mastermode || mastermask&MM_AUTOAPPROVE ? mastermode : MM_AUTH))); sendstring(smapname, p); sendstring(serverdesc, p); sendserverinforeply(p); } bool servercompatible(char *name, char *sdec, char *map, int ping, const vector &attr, int np) { return attr.length() && attr[0]==PROTOCOL_VERSION; } #include "botmgr.h" } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/characterinfo.h0000664000175000017500000000213711442705030024253 0ustar showardshoward#ifndef __CHARACTERINFO_H__ #define __CHARACTERINFO_H__ #include "playermodelinfo.h" namespace Character { enum { AO_DEAD = 0, AO_DYING, //1 AO_IDLE, //2 AO_FORWARD, //3 AO_BACKWARD,//4 AO_LEFT, //5 AO_RIGHT, //6 AO_HOLD, //7 AO_ACTION, //8 AO_GESTURE, //9 AO_PAIN, //10 AO_JUMP, //11 AO_SINK, //12 AO_SWIM, //13 AO_EDIT, //14 AO_LAG, //15 AO_NUM //16 }; struct CharacterInfo { int playermodel; vector attacheditems; int ao[AO_NUM]; bool dogesture; CharacterInfo(); ~CharacterInfo(); void setplayermodel(int i); int getplayermodel(); bool setgesture(int i); bool setao(int ao, int i); void attach(int i); void detach(int i); void resetao(); }; } #endif // __CHARACTERINFO_H__ sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/client.cpp0000664000175000017500000016007411442705030023261 0ustar showardshoward#include "game.h" namespace entities { void editent(int i, bool local) { extentity& e = *entities::getents()[i]; // if(e.type == ET_MAPMODEL && validtrigger(e.attr[2])) // { // MapEntities::StaticEntity &f = (MapEntities::StaticEntity &)e; // f.triggerstate = TRIGGER_RESET; // f.lasttrigger = 0; // setuptriggerflags(f); // } // else e.flags = 0; if(!local) game::addmsg(SV_EDITENT, "riii3i2v", i, (int)(e.o.x*DMF), (int)(e.o.y*DMF), (int)(e.o.z*DMF), e.type, e.attr.length(), e.attr.length(), e.attr.getbuf()); } } namespace game { VARP(maxradarscale, 0, 1024, 10000); //we only have one gamemode, so this is hardcoded at the moment clientmode *cmode = new defaultclientmode; void setclientmode() { //nothing to do, only one defaultmode at the moment } bool senditemstoserver = false, sendcrc = false; // after a map change, since server doesn't have map data int lastping = 0; bool connected = false, remote = false, demoplayback = false, gamepaused = false; int sessionid = 0; string connectpass = ""; VARP(deadpush, 1, 2, 20); void switchname(const char *name) { if(name[0]) { filtertext(player1->name, name, false, MAXNAMELEN); if(!player1->name[0]) copystring(player1->name, "unnamed"); addmsg(SV_SWITCHNAME, "rs", player1->name); } else conoutf("your name is: %s", colorname(player1)); } ICOMMAND(name, "s", (char *s), switchname(s)); ICOMMAND(getname, "", (), result(player1->name)); void switchplayermodel(int i) { Character::CharacterInfo& charinfo = player1->getcharinfo(); charinfo.setplayermodel(i); addmsg(SV_SWITCHMODEL, "rci", player1, charinfo.getplayermodel()); } ICOMMAND(setplayermodel, "i", (int *i), switchplayermodel(*i)); void setplayerspeed(int speed) { clamp(speed, 1, 1000); player1->maxspeed = speed; } ICOMMAND(setplayerspeed, "i", (int *i), setplayerspeed(*i)); struct authkey { char *name, *key, *desc; int lastauth; authkey(const char *name, const char *key, const char *desc) : name(newstring(name)), key(newstring(key)), desc(newstring(desc)), lastauth(0) { } ~authkey() { DELETEA(name); DELETEA(key); DELETEA(desc); } }; vector authkeys; authkey *findauthkey(const char *desc) { loopv(authkeys) if(!strcmp(authkeys[i]->desc, desc) && !strcmp(authkeys[i]->name, player1->name)) return authkeys[i]; loopv(authkeys) if(!strcmp(authkeys[i]->desc, desc)) return authkeys[i]; return NULL; } VARP(autoauth, 0, 1, 1); void addauthkey(const char *name, const char *key, const char *desc) { loopvrev(authkeys) if(!strcmp(authkeys[i]->desc, desc) && !strcmp(authkeys[i]->name, name)) delete authkeys.remove(i); if(name[0] && key[0]) authkeys.add(new authkey(name, key, desc)); } ICOMMAND(authkey, "sss", (char *name, char *key, char *desc), addauthkey(name, key, desc)); void genauthkey(const char *secret) { if(!secret[0]) { conoutf(CON_ERROR, "you must specify a secret password"); return; } vector privkey, pubkey; genprivkey(secret, privkey, pubkey); conoutf("private key: %s", privkey.getbuf()); conoutf("public key: %s", pubkey.getbuf()); } COMMAND(genauthkey, "s"); void saveauthkeys() { stream *f = openfile("auth.cfg", "w"); if(!f) { conoutf(CON_ERROR, "failed to open auth.cfg for writing"); return; } loopv(authkeys) { authkey *a = authkeys[i]; f->printf("authkey \"%s\" \"%s\" \"%s\"\n", a->name, a->key, a->desc); } conoutf("saved authkeys to auth.cfg"); delete f; } COMMAND(saveauthkeys, ""); int numchannels() { return 3; } void sendmapinfo() { sendcrc = true; if(player1->state!=CS_SPECTATOR || player1->privilege || !remote) { senditemstoserver = true; // MapEntities::sendmapuids(true); } } void writeclientinfo(stream *f) { f->printf("name \"%s\"\n", player1->name); } bool allowedittoggle() { if(connected && multiplayer(false) && !m_edit) { conoutf(CON_ERROR, "editing in multiplayer requires coop edit mode (1)"); return false; } if(identexists("allowedittoggle") && !execute("allowedittoggle")) return false; return true; } void edittoggled(bool on) { // conoutf("DEBUG: game::edittoggled - remove all characters"); //disconnect all controls // loopv(Control::controls) // { // Control::ControlNPC* ca = dynamic_cast(Control::controls[i]); // if(ca) { ca->disconnect(); } // } addmsg(SV_EDITMODE, "ri", on ? 1 : 0); disablezoom(); } ICOMMAND(flying, "", (), intret(player1->flying = !player1->flying)); const char *getclientname(int cn) { DynamicEntity *d = getclient(cn); return d ? d->name : ""; } ICOMMAND(getclientname, "i", (int *cn), result(getclientname(*cn))); int getclientmodel(int cn) { DynamicEntity *d = getclient(cn); Character::CharacterInfo& info = d->getcharinfo(); return d ? info.getplayermodel() : -1; } ICOMMAND(getclientmodel, "i", (int *cn), intret(getclientmodel(*cn))); ICOMMAND(getplayermodel, "", (), intret(getclientmodel(player1->clientnum))); bool isspectator(int cn) { DynamicEntity *d = getclient(cn); return d ? (d->state==CS_SPECTATOR) : false; } ICOMMAND(isspectator, "i", (int *cn), intret(isspectator(*cn) ? 1 : 0)); int parseplayer(const char *arg) { char *end; int n = strtol(arg, &end, 10); if(*arg && !*end) { if(n!=player1->clientnum && !clients.inrange(n)) return -1; return n; } // try case sensitive first loopv(players) { DynamicEntity *o = players[i]; if(!strcmp(arg, o->name)) return o->clientnum; } // nothing found, try case insensitive loopv(players) { DynamicEntity *o = players[i]; if(!strcasecmp(arg, o->name)) return o->clientnum; } return -1; } ICOMMAND(getclientnum, "s", (char *name), intret(name[0] ? parseplayer(name) : player1->clientnum)); void listclients(bool local) { vector buf; string cn; int numclients = 0; if(local) { formatstring(cn)("%d", player1->clientnum); buf.put(cn, strlen(cn)); numclients++; } loopv(clients) if(clients[i]) { formatstring(cn)("%d", clients[i]->clientnum); if(numclients++) buf.add(' '); buf.put(cn, strlen(cn)); } buf.add('\0'); result(buf.getbuf()); } ICOMMAND(listclients, "i", (int *local), listclients(*local!=0)); void clearbans() { addmsg(SV_CLEARBANS, "r"); } COMMAND(clearbans, ""); void kick(const char *arg) { int i = parseplayer(arg); if(i>=0 && i!=player1->clientnum) addmsg(SV_KICK, "ri", i); } COMMAND(kick, "s"); void hashpwd(const char *pwd) { if(player1->clientnum<0) return; string hash; server::hashpassword(player1->clientnum, sessionid, pwd, hash); result(hash); } COMMAND(hashpwd, "s"); void setmaster(const char *arg) { if(!arg[0]) return; int val = 1; string hash = ""; if(!arg[1] && isdigit(arg[0])) val = atoi(arg); else server::hashpassword(player1->clientnum, sessionid, arg, hash); addmsg(SV_SETMASTER, "ris", val, hash); } COMMAND(setmaster, "s"); ICOMMAND(mastermode, "i", (int *val), addmsg(SV_MASTERMODE, "ri", *val)); bool tryauth(const char *desc) { authkey *a = findauthkey(desc); if(!a) return false; a->lastauth = lastmillis; addmsg(SV_AUTHTRY, "rss", a->desc, a->name); return true; } ICOMMAND(auth, "s", (char *desc), tryauth(desc)); void togglespectator(int val, const char *who) { int i = who[0] ? parseplayer(who) : player1->clientnum; if(i>=0) addmsg(SV_SPECTATOR, "rii", i, val); } ICOMMAND(spectator, "is", (int *val, char *who), togglespectator(*val, who)); ICOMMAND(checkmaps, "", (), addmsg(SV_CHECKMAPS, "r")); VARP(localmode, STARTGAMEMODE, 1, NUMGAMEMODES ); SVARP(localmap, "moviecubedemo"); VARP(lobbymode, STARTGAMEMODE, 1, NUMGAMEMODES ); SVARP(lobbymap, "moviecubedemo"); int gamemode = INT_MAX, nextmode = INT_MAX; string clientmap = ""; void changemapserv(const char *name, int mode) // forced map change from the server { if(multiplayer(false) && !m_mp(mode)) { conoutf(CON_ERROR, "changemapserv: mode %s (%d) not supported in multiplayer", server::modename(gamemode), gamemode); loopi(NUMGAMEMODES) if(m_mp(STARTGAMEMODE + i)) { mode = STARTGAMEMODE + i; break; } } gamemode = mode; nextmode = mode; minremain = -1; if(editmode) toggleedit(); // if(m_demo) { entities::resetspawns(); return; } if((m_edit && !name[0]) || !load_world(name)) { emptymap(0, true, name); senditemstoserver = false; // MapEntities::sendmapuids(false); } startgame(); } void setmode(int mode) { if(multiplayer(false) && !m_mp(mode)) { conoutf(CON_ERROR, "setmode: mode %s (%d) not supported in multiplayer", server::modename(mode), mode); intret(0); return; } nextmode = mode; intret(1); } ICOMMAND(mode, "i", (int *val), setmode(*val)); ICOMMAND(getmode, "", (), intret(gamemode)); void changemap(const char *name, int mode) // request map change, server may ignore { // conoutf("DEBUG: client changemap"); if(m_checknot(mode, M_EDIT) && !name[0]) name = clientmap[0] ? clientmap : (remote ? lobbymap : localmap); if(!remote) { server::forcemap(name, mode); if(!connected) localconnect(); } else if(player1->state!=CS_SPECTATOR || player1->privilege) addmsg(SV_MAPVOTE, "rsi", name, mode); } void changemap(const char *name) { changemap(name, m_valid(nextmode) ? nextmode : (remote ? lobbymode : localmode)); } ICOMMAND(map, "s", (char *name), changemap(name)); void forceedit(const char *name) { changemap(name, 1); } void newmap(int size) { addmsg(SV_NEWMAP, "ri", size); } void edittrigger(const selinfo &sel, int op, int arg1, int arg2, int arg3) { if(m_edit) switch(op) { case EDIT_FLIP: case EDIT_COPY: case EDIT_PASTE: case EDIT_DELCUBE: { addmsg(SV_EDITF + op, "ri9i4", sel.o.x, sel.o.y, sel.o.z, sel.s.x, sel.s.y, sel.s.z, sel.grid, sel.orient, sel.cx, sel.cxs, sel.cy, sel.cys, sel.corner); break; } case EDIT_ROTATE: { addmsg(SV_EDITF + op, "ri9i5", sel.o.x, sel.o.y, sel.o.z, sel.s.x, sel.s.y, sel.s.z, sel.grid, sel.orient, sel.cx, sel.cxs, sel.cy, sel.cys, sel.corner, arg1); break; } case EDIT_MAT: case EDIT_FACE: case EDIT_TEX: case EDIT_REPLACE: { addmsg(SV_EDITF + op, "ri9i6", sel.o.x, sel.o.y, sel.o.z, sel.s.x, sel.s.y, sel.s.z, sel.grid, sel.orient, sel.cx, sel.cxs, sel.cy, sel.cys, sel.corner, arg1, arg2); break; } case EDIT_REMIP: { addmsg(SV_EDITF + op, "r"); break; } } } void printvar(DynamicEntity *d, ident *id) { if(id) switch(id->type) { case ID_VAR: { int val = *id->storage.i; string str; if(id->flags&IDF_HEX && id->maxval==0xFFFFFF) formatstring(str)("0x%.6X (%d, %d, %d)", val, (val>>16)&0xFF, (val>>8)&0xFF, val&0xFF); else formatstring(str)(id->flags&IDF_HEX ? "0x%X" : "%d", val); conoutf("%s set map var \"%s\" to %s", colorname(d), id->name, str); break; } case ID_FVAR: conoutf("%s set map var \"%s\" to %s", colorname(d), id->name, floatstr(*id->storage.f)); break; case ID_SVAR: conoutf("%s set map var \"%s\" to \"%s\"", colorname(d), id->name, *id->storage.s); break; } } void vartrigger(ident *id) { if(!m_edit) return; switch(id->type) { case ID_VAR: addmsg(SV_EDITVAR, "risi", ID_VAR, id->name, *id->storage.i); break; case ID_FVAR: addmsg(SV_EDITVAR, "risf", ID_FVAR, id->name, *id->storage.f); break; case ID_SVAR: addmsg(SV_EDITVAR, "riss", ID_SVAR, id->name, *id->storage.s); break; default: return; } printvar(player1, id); } void pausegame(int *val) { addmsg(SV_PAUSEGAME, "ri", *val > 0 ? 1 : 0); } COMMAND(pausegame, "i"); bool ispaused() { return gamepaused; } // collect c2s messages conveniently vector messages; int messagecn = -1, messagereliable = false; void addmsg(int type, const char *fmt, ...) { if(!connected) return; static uchar buf[MAXTRANS]; ucharbuf p(buf, sizeof(buf)); putint(p, type); int numi = 1, numf = 0, nums = 0, mcn = -1; bool reliable = false; if(fmt) { va_list args; va_start(args, fmt); while(*fmt) switch(*fmt++) { case 'r': reliable = true; break; case 'c': { DynamicEntity *d = va_arg(args, DynamicEntity *); mcn = !d || d == player1 ? -1 : d->clientnum; break; } case 'v': { int n = va_arg(args, int); int *v = va_arg(args, int *); loopi(n) putint(p, v[i]); numi += n; break; } case 'i': { int n = isdigit(*fmt) ? *fmt++-'0' : 1; loopi(n) putint(p, va_arg(args, int)); numi += n; break; } case 'f': { int n = isdigit(*fmt) ? *fmt++-'0' : 1; loopi(n) putfloat(p, (float)va_arg(args, double)); numf += n; break; } case 's': sendstring(va_arg(args, const char *), p); nums++; break; } va_end(args); } int num = nums || numf ? 0 : numi, msgsize = server::msgsizelookup(type); if(msgsize && num!=msgsize) { defformatstring(s)("inconsistent msg size for %d (%d != %d)", type, num, msgsize); fatal(s); } if(reliable) messagereliable = true; if(mcn != messagecn) { static uchar mbuf[16]; ucharbuf m(mbuf, sizeof(mbuf)); putint(m, SV_FROMBOT); putint(m, mcn); messages.put(mbuf, m.length()); messagecn = mcn; } messages.put(buf, p.length()); } void connectattempt(const char *name, const char *password, const ENetAddress &address) { copystring(connectpass, password); } void connectfail() { memset(connectpass, 0, sizeof(connectpass)); } void gameconnect(bool _remote) { connected = true; remote = _remote; if(editmode) toggleedit(); } void gamedisconnect(bool cleanup) { if(remote) stopfollowing(); connected = remote = false; player1->clientnum = -1; sessionid = 0; messages.setsize(0); messagereliable = false; messagecn = -1; player1->respawn(); // player1->lifesequence = 0; player1->state = CS_ALIVE; player1->privilege = PRIV_NONE; senditemstoserver = false; // MapEntities::sendmapuids(false); demoplayback = false; gamepaused = false; clearclients(false); if(cleanup) { nextmode = gamemode = INT_MAX; clientmap[0] = '\0'; } } void toserver(char *text) { conoutf(CON_CHAT, "<%s>\f0 %s", colorname(player1), text); addmsg(SV_TEXT, "rcis", player1, CHAT_TALK, text); } COMMANDN(say, toserver, "C"); // void sayteam(char *text) { conoutf(CON_TEAMCHAT, "<%s>\f1 %s", colorname(player1), text); addmsg(SV_TEXT, "rcis", player1, CHAT_TEAM, text); } // COMMAND(sayteam, "C"); void emote(char *text) { conoutf(CON_CHAT, "\f6* %s %s", colorname(player1), text); addmsg(SV_TEXT, "rcis", player1, CHAT_TALK|CHAT_EMOTE, text); } COMMANDN(me, emote, "C"); // void teamemote(char *text) { conoutf(CON_TEAMCHAT, "\f5* %s %s", colorname(player1), text); addmsg(SV_TEXT, "rcis", player1, CHAT_TEAM|CHAT_EMOTE, text); } // COMMANDN(meteam, teamemote, "C"); void sendposition(DynamicEntity *d) { if(d->state != CS_ALIVE && d->state != CS_EDITING) return; packetbuf q(100); putint(q, SV_POS); putint(q, d->clientnum); putuint(q, (int)(d->o.x*DMF)); // quantize coordinates to 1/4th of a cube, between 1 and 3 bytes putuint(q, (int)(d->o.y*DMF)); putuint(q, (int)((d->o.z-d->eyeheight)*DMF)); putuint(q, (int)d->yaw); putint(q, (int)d->pitch); putint(q, (int)d->roll); putint(q, (int)(d->vel.x*DVELF)); // quantize to itself, almost always 1 byte putint(q, (int)(d->vel.y*DVELF)); putint(q, (int)(d->vel.z*DVELF)); // uint physstate = d->physstate | ((d->lifesequence&1)<<6); uint physstate = d->physstate; if(d->falling.x || d->falling.y) physstate |= 0x20; if(d->falling.z) physstate |= 0x10; if((lookupmaterial(d->feetpos())&MATF_CLIP) == MAT_GAMECLIP) physstate |= 0x80; putuint(q, physstate); if(d->falling.x || d->falling.y) { putint(q, (int)(d->falling.x*DVELF)); // quantize to itself, almost always 1 byte putint(q, (int)(d->falling.y*DVELF)); } if(d->falling.z) putint(q, (int)(d->falling.z*DVELF)); // pack rest in almost always 1 byte: strafe:2, move:2, garmour: 1, yarmour: 1, quad: 1 uint flags = (d->strafe&3) | ((d->move&3)<<2); putuint(q, flags); sendclientpacket(q.finalize(), 0); } void sendmessages(DynamicEntity *d) { packetbuf p(MAXTRANS); if(sendcrc) { p.reliable(); sendcrc = false; const char *mname = getclientmap(); putint(p, SV_MAPCRC); sendstring(mname, p); putint(p, mname[0] ? getmapcrc() : 0); } // if(MapEntities::sendmapuids()) // { // MapEntities::putentities(p); // } // if(senditemstoserver) // { // if(!m_noitems || cmode!=NULL) p.reliable(); // if(!m_noitems) entities::putitems(p); // if(cmode) cmode->senditems(p); // senditemstoserver = false; // } if(messages.length()) { p.put(messages.getbuf(), messages.length()); messages.setsize(0); if(messagereliable) p.reliable(); messagereliable = false; messagecn = -1; } if(lastmillis-lastping>250) { putint(p, SV_PING); putint(p, lastmillis); lastping = lastmillis; } sendclientpacket(p.finalize(), 1); } void c2sinfo() // send update to the server { static int lastupdate = -1000; if(totalmillis - lastupdate < 33) return; // don't update faster than 30fps lastupdate = totalmillis; loopv(players) { DynamicEntity *d = players[i]; if(d->controltype != CONTROL_REMOTE) sendposition(d); } sendmessages(player1); flushclient(); } void sendintro() { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); putint(p, SV_CONNECT); sendstring(player1->name, p); string hash = ""; if(connectpass[0]) { server::hashpassword(player1->clientnum, sessionid, connectpass, hash); memset(connectpass, 0, sizeof(connectpass)); } sendstring(hash, p); Character::CharacterInfo& info = player1->getcharinfo(); putint(p, info.getplayermodel()); sendclientpacket(p.finalize(), 1); } void updatepos(DynamicEntity *d) { // update the position of other clients in the game in our world // don't care if he's in the scenery or other players, // just don't overlap with our client const float r = player1->radius+d->radius; const float dx = player1->o.x-d->o.x; const float dy = player1->o.y-d->o.y; const float dz = player1->o.z-d->o.z; const float rz = player1->aboveeye+d->eyeheight; const float fx = (float)fabs(dx), fy = (float)fabs(dy), fz = (float)fabs(dz); if(fxstate!=CS_SPECTATOR && d->state!=CS_DEAD) { if(fxo.y += dy<0 ? r-fy : -(r-fy); // push aside else d->o.x += dx<0 ? r-fx : -(r-fx); } int lagtime = lastmillis-d->lastupdate; if(lagtime) { if(d->state!=CS_SPAWNING && d->lastupdate) d->plag = (d->plag*5+lagtime)/6; d->lastupdate = lastmillis; } } void parsepositions(ucharbuf &p) { int type; while(p.remaining()) switch(type = getint(p)) { case SV_POS: // position of another client { int cn = getint(p); vec o, vel, falling; float yaw, pitch, roll; int physstate, f; o.x = getuint(p)/DMF; o.y = getuint(p)/DMF; o.z = getuint(p)/DMF; yaw = (float)getuint(p); pitch = (float)getint(p); roll = (float)getint(p); vel.x = getint(p)/DVELF; vel.y = getint(p)/DVELF; vel.z = getint(p)/DVELF; physstate = getuint(p); falling = vec(0, 0, 0); if(physstate&0x20) { falling.x = getint(p)/DVELF; falling.y = getint(p)/DVELF; } if(physstate&0x10) falling.z = getint(p)/DVELF; // int seqcolor = (physstate>>6)&1; f = getuint(p); DynamicEntity *d = getclient(cn); if(!d || d->state==CS_DEAD) continue; float oldyaw = d->yaw, oldpitch = d->pitch; d->yaw = yaw; d->pitch = pitch; d->roll = roll; d->strafe = (f&3)==3 ? -1 : f&3; f >>= 2; d->move = (f&3)==3 ? -1 : f&3; vec oldpos(d->o); if(allowmove(d)) { d->o = o; d->o.z += d->eyeheight; d->vel = vel; d->falling = falling; d->physstate = physstate & 0x0F; updatephysstate(d); updatepos(d); } if(smoothmove && d->smoothmillis>=0 && oldpos.dist(d->o) < smoothdist) { d->newpos = d->o; d->newyaw = d->yaw; d->newpitch = d->pitch; d->o = oldpos; d->yaw = oldyaw; d->pitch = oldpitch; (d->deltapos = oldpos).sub(d->newpos); d->deltayaw = oldyaw - d->newyaw; if(d->deltayaw > 180) d->deltayaw -= 360; else if(d->deltayaw < -180) d->deltayaw += 360; d->deltapitch = oldpitch - d->newpitch; d->smoothmillis = lastmillis; } else d->smoothmillis = 0; //TODO: add checkstate, d->state==CS_SPAWNING only set to CS_ALIVE if(d->state==CS_LAGGED || d->state==CS_SPAWNING) { d->state = CS_ALIVE; } break; } default: neterr("type"); return; } } void parsestate(DynamicEntity *d, ucharbuf &p, bool resume = false) { if(!d) return; //{ static DynamicEntity dummy; d = &dummy; } if(resume) { if(d==player1) getint(p); else d->state = getint(p); // conoutf("DEBUG: game::parsestate cn: %d, state: %d", d->clientnum, d->state); } } extern int deathscore; void parsemessages(int cn, DynamicEntity *d, ucharbuf &p) { static char text[MAXTRANS]; int type; bool mapchanged = false, initmap = false; while(p.remaining()) switch(type = getint(p)) { case SV_SERVINFO: // welcome messsage from the server { // conoutf("DEBUG: game::parsemessages SV_SERVINFO"); int mycn = getint(p), prot = getint(p); if(prot!=PROTOCOL_VERSION) { conoutf(CON_ERROR, "you are using a different game protocol (you: %d, server: %d)", PROTOCOL_VERSION, prot); disconnect(); return; } sessionid = getint(p); player1->clientnum = mycn; // we are now connected if(getint(p) > 0) conoutf("this server is password protected"); sendintro(); break; } case SV_WELCOME: { // conoutf("DEBUG: game::parsemessages SV_WELCOME"); int hasmap = getint(p); if(!hasmap) initmap = true; // we are the first client on this server, set map break; } case SV_PAUSEGAME: { int val = getint(p); gamepaused = val > 0; conoutf("game is %s", gamepaused ? "paused" : "resumed"); break; } case SV_CLIENT: { int cn = getint(p), len = getuint(p); ucharbuf q = p.subbuf(len); parsemessages(cn, getclient(cn), q); break; } case SV_SOUND: if(!d) return; playsound(getint(p), &d->o); break; case SV_TEXT: { int tcn = getint(p), mtype = getint(p); getstring(text, p); filtertext(text, text); DynamicEntity *t = getclient(tcn); if(t->state!=CS_DEAD && t->state!=CS_SPECTATOR) particle_textcopy(t->abovehead(), text, PART_TEXT, 2000, 0x32FF64, 4.0f, -8); if(mtype&CHAT_EMOTE) conoutf(mtype&CHAT_TEAM ? CON_TEAMCHAT : CON_CHAT, "\f%i* %s %s", mtype&CHAT_TEAM ? 5 : 6, t->name, text); else conoutf(mtype&CHAT_TEAM ? CON_TEAMCHAT : CON_CHAT, "<%s> \f%i%s", t->name, mtype&CHAT_TEAM ? 1 : 0, text); break; } case SV_MAPCHANGE: getstring(text, p); changemapserv(text, getint(p)); mapchanged = true; if(getint(p)) {} //entities::spawnitems(); else senditemstoserver = false; break; case SV_FORCEDEATH: { int cn = getint(p); DynamicEntity *d = cn==player1->clientnum ? player1 : newclient(cn); if(!d) break; if(d==player1) { if(editmode) toggleedit(); stopfollowing(); // if(deathscore) showscores(true); } else d->resetinterp(); d->state = CS_DEAD; break; } case SV_ITEMLIST: { int n; while((n = getint(p))>=0 && !p.overread()) { // if(mapchanged) entities::setspawn(n, true); getint(p); // type } break; } case SV_MAPRELOAD: // server requests next map { // defformatstring(nextmapalias)("nextmap_%s%s", (cmode ? cmode->prefixnextmap() : ""), getclientmap()); defformatstring(nextmapalias)("nextmap_%s", getclientmap()); const char *map = getalias(nextmapalias); // look up map in the cycle addmsg(SV_MAPCHANGE, "rsi", *map ? map : getclientmap(), nextmode); break; } case SV_INITCLIENT: // another client either connected or changed name/team { //TODO: add control remote, if initclient only called on connect or also called on switch name int cn = getint(p); DynamicEntity *d = newclient(cn); // conoutf("DEBUG: SV_INITCLIENT newclient cn: %d state: %d", d->clientnum, d->state); if(!d) { getstring(text, p); // getstring(text, p); getint(p); break; } getstring(text, p); filtertext(text, text, false, MAXNAMELEN); if(!text[0]) copystring(text, "unnamed"); if(d->name[0]) // already connected { if(strcmp(d->name, text)) conoutf("%s is now known as %s", colorname(d), colorname(d, text)); } else // new client { conoutf("connected: %s", colorname(d, text)); loopv(players) // clear copies since new player doesn't have them freeeditinfo(players[i]->edit); freeeditinfo(localedit); } copystring(d->name, text, MAXNAMELEN+1); Character::CharacterInfo& info = d->getcharinfo(); info.setplayermodel(getint(p)); // defformatstring(dbg)("DEBUG[%d]: game::parsemessages SV_INITCLIENT, cl: %d, on: %d, state: %d", player1->clientnum, d->clientnum, d->ownernum, d->state); // conoutf("%s", dbg); //add new control if(d->clienttype == CLIENT_PLAYER && d->clientnum != player1->clientnum) { Control::ControlRemote* control = new Control::ControlRemote; Control::controls.add(control); control->connect(d); } break; } case SV_SWITCHNAME: getstring(text, p); if(d) { filtertext(text, text, false, MAXNAMELEN); if(!text[0]) copystring(text, "unnamed"); conoutf("%s is now known as %s", colorname(d), colorname(d, text)); copystring(d->name, text, MAXNAMELEN+1); } break; case SV_SWITCHMODEL: { //int cn = getint(p); int model = getint(p); if(d) { Character::CharacterInfo& charinfo = d->getcharinfo(); charinfo.setplayermodel(model); // conoutf("DEBUG game::parsemessages SV_SWITCHMODEL cn %d model %d", d->clientnum, model); } break; } //TODO: control->connect & control->disconnect case SV_CDIS: { int n = getint(p); // conoutf("DEBUG: game::parsemessages SV_CDIS cn: %d", n); loopv(Control::controls) { if(Control::controls[i]->dynent->clientnum == n) { Control::Control* c = Control::controls[i]->cleanup(); if(c) delete c; // conoutf("DEBUG: game::parsemessages SV_CDIS - after cleanup ctl: %d, players: %d", controls.length(), players.length()); break; } } break; } case SV_SPAWN: { // conoutf("DEBUG: game::parsemessages SV_SPAWN"); if(d) { if(d->state==CS_DEAD) saveragdoll(d); d->respawn(); } parsestate(d, p); if(!d) break; d->state = CS_SPAWNING; // defformatstring(dbg)("DEBUG: game::parsemessages SV_SPAWN cl: %d, on: %d, clienttype: %d, state: %d", d->clientnum, d->ownernum, d->clienttype, d->state); // conoutf("%s", dbg); break; } case SV_SPAWNSTATE: { int scn = getint(p); DynamicEntity *s = getclient(scn); if(!s) break; //{ parsestate(NULL, p); break; } if(s->state==CS_DEAD) saveragdoll(s); if(s==player1) { if(editmode) toggleedit(); stopfollowing(); } s->respawn(); parsestate(s, p); // TODO (offtools#1#): move spawn related stuff to cmode if(s->controltype == CONTROL_NPC && editmode) { if(cmode) cmode->pickspawn(s); if(cmode) cmode->respawned(s); } addmsg(SV_SPAWN, "rc", s); s->state = CS_ALIVE; break; } case SV_RESUME: { // conoutf("DEBUG: game::parsemessages 1. SV_RESUME"); for(;;) { int cn = getint(p); if(p.overread() || cn<0) break; DynamicEntity *d = (cn == player1->clientnum ? player1 : newclient(cn)); // conoutf("DEBUG: game::parsemessages 2. SV_RESUME cn: %d, state: %d", cn, d->state); parsestate(d, p, true); } break; } case SV_ITEMSPAWN: { // int i = getint(p); // if(!entities::getents().inrange(i)) break; // //entities::setspawn(i, true); // playsound(S_ITEMSPAWN, &entities::getents()[i]->o); // const char *name = entities::itemname(i); // if(name) particle_text(entities::getents()[i]->o, name, PART_TEXT, 2000, 0x32FF64, 4.0f, -8); break; } case SV_ITEMACC: // server acknowledges that I picked up this item { int i = getint(p), cn = getint(p); DynamicEntity *d = getclient(cn); // entities::pickupeffects(i, d); break; } case SV_EDITF: // coop editing messages case SV_EDITT: case SV_EDITM: case SV_FLIP: case SV_COPY: case SV_PASTE: case SV_ROTATE: case SV_REPLACE: case SV_DELCUBE: { if(!d) return; selinfo sel; sel.o.x = getint(p); sel.o.y = getint(p); sel.o.z = getint(p); sel.s.x = getint(p); sel.s.y = getint(p); sel.s.z = getint(p); sel.grid = getint(p); sel.orient = getint(p); sel.cx = getint(p); sel.cxs = getint(p); sel.cy = getint(p), sel.cys = getint(p); sel.corner = getint(p); int dir, mode, tex, newtex, mat, filter, allfaces, insel; ivec moveo; switch(type) { case SV_EDITF: dir = getint(p); mode = getint(p); mpeditface(dir, mode, sel, false); break; case SV_EDITT: tex = getint(p); allfaces = getint(p); mpedittex(tex, allfaces, sel, false); break; case SV_EDITM: mat = getint(p); filter = getint(p); mpeditmat(mat, filter, sel, false); break; case SV_FLIP: mpflip(sel, false); break; case SV_COPY: if(d) mpcopy(d->edit, sel, false); break; case SV_PASTE: if(d) mppaste(d->edit, sel, false); break; case SV_ROTATE: dir = getint(p); mprotate(dir, sel, false); break; case SV_REPLACE: tex = getint(p); newtex = getint(p); insel = getint(p); mpreplacetex(tex, newtex, insel > 0, sel, false); break; case SV_DELCUBE: mpdelcube(sel, false); break; } break; } case SV_REMIP: { if(!d) return; conoutf("%s remipped", colorname(d)); mpremip(false); break; } case SV_EDITENT: // coop edit of ent { if(!d) return; getint(p); int i = getint(p); float x = getint(p)/DMF, y = getint(p)/DMF, z = getint(p)/DMF; int type = getint(p); int num = getint(p); int* attrs = new int[num]; loopj(num) attrs[j] = getint(p); mpeditent(i, vec(x, y, z), type, attrs, false); DELETEA(attrs); break; } case SV_EDITVAR: { if(!d) return; int type = getint(p); getstring(text, p); string name; filtertext(name, text, false, MAXSTRLEN-1); ident *id = getident(name); switch(type) { case ID_VAR: { int val = getint(p); if(id && !(id->flags&IDF_READONLY)) setvar(name, val); break; } case ID_FVAR: { float val = getfloat(p); if(id && !(id->flags&IDF_READONLY)) setfvar(name, val); break; } case ID_SVAR: { getstring(text, p); if(id && !(id->flags&IDF_READONLY)) setsvar(name, text); break; } } printvar(d, id); break; } case SV_PONG: addmsg(SV_CLIENTPING, "i", player1->ping = (player1->ping*5+lastmillis-getint(p))/6); break; case SV_CLIENTPING: if(!d) return; d->ping = getint(p); break; case SV_TIMEUP: timeupdate(getint(p)); break; case SV_SERVMSG: getstring(text, p); conoutf("%s", text); break; case SV_SENDDEMOLIST: { int demos = getint(p); if(!demos) conoutf("no demos available"); else loopi(demos) { getstring(text, p); conoutf("%d. %s", i+1, text); } break; } case SV_DEMOPLAYBACK: { int on = getint(p); if(on) player1->state = CS_SPECTATOR; else clearclients(); demoplayback = on!=0; player1->clientnum = getint(p); gamepaused = false; const char *alias = on ? "demostart" : "demoend"; if(identexists(alias)) execute(alias); break; } case SV_CURRENTMASTER: { int mn = getint(p), priv = getint(p); loopv(players) players[i]->privilege = PRIV_NONE; if(mn>=0) { DynamicEntity *m = mn==player1->clientnum ? player1 : newclient(mn); if(m) m->privilege = priv; } break; } case SV_EDITMODE: { conoutf("client SV_EDITMODE"); int val = getint(p); if(!d) break; if(val) { d->editstate = d->state; d->state = CS_EDITING; } else { d->state = d->editstate; // if(d->state==CS_DEAD) deathstate(d, true); } break; } case SV_SPECTATOR: { int sn = getint(p), val = getint(p); DynamicEntity *s; if(sn==player1->clientnum) { s = player1; if(val && remote && !player1->privilege) { senditemstoserver = false; // MapEntities::sendmapuids(false); } } else s = newclient(sn); if(!s) return; if(val) { if(s==player1) { if(editmode) toggleedit(); // if(s->state==CS_DEAD) showscores(false); disablezoom(); } s->state = CS_SPECTATOR; } else if(s->state==CS_SPECTATOR) { if(s==player1) stopfollowing(); // deathstate(s, true); } break; } #define PARSEMESSAGES 1 // #include "capture.h" // #include "ctf.h" #undef PARSEMESSAGES case SV_ANNOUNCE: { int t = getint(p); // if (t==I_QUAD) { playsound(S_V_QUAD10); conoutf(CON_GAMEINFO, "\f2quad damage will spawn in 10 seconds!"); } // else if(t==I_BOOST) { playsound(S_V_BOOST10); conoutf(CON_GAMEINFO, "\f2+10 health will spawn in 10 seconds!"); } break; } case SV_NEWMAP: { int size = getint(p); if(size>=0) emptymap(size, true, NULL); else enlargemap(true); if(d && d!=player1) { int newsize = 0; while(1<=0 ? "%s started a new map of size %d" : "%s enlarged the map to size %d", colorname(d), newsize); } break; } case SV_REQAUTH: { getstring(text, p); if(autoauth && text[0] && tryauth(text)) conoutf("server requested authkey \"%s\"", text); break; } case SV_AUTHCHAL: { getstring(text, p); authkey *a = findauthkey(text); uint id = (uint)getint(p); getstring(text, p); if(a && a->lastauth && lastmillis - a->lastauth < 60*1000) { vector buf; answerchallenge(a->key, text, buf); //conoutf(CON_DEBUG, "answering %u, challenge %s with %s", id, text, buf.getbuf()); addmsg(SV_AUTHANS, "rsis", a->desc, id, buf.getbuf()); } break; } case SV_INITBOT: { int bn = getint(p), on = getint(p), ct = getint(p), pm = getint(p); DynamicEntity *b = newclient(bn); if(!b) break; b->clienttype = (cltype)ct; b->ownernum = on; Character::CharacterInfo& info = b->getcharinfo(); info.setplayermodel(pm); // defformatstring(dbg)("DEBUG: game::parsemessages SV_INITBOT cl: %d, on: %d, state: %d", b->clientnum, b->ownernum, b->state); // conoutf("%s", dbg); if(player1->clientnum == b->ownernum) { //find uninitialized control loopv(Control::controls) { Control::ControlNPC* ca = dynamic_cast(Control::controls[i]); if(ca && !Control::controls[i]->getstate()) { // conoutf("DEBUG: game::parsemessages SV_INITBOT init ControlNPC"); ca->connect(b); break; } } } else { // conoutf("DEBUG: game::parsemessages SV_INITBOT init ControlRemote"); Control::controls.add(new Control::ControlRemote(b)); } break; } //__offtools__ attachments: attach stuff case SV_ATTACH: { int item = getint(p); if(d) { Character::CharacterInfo& info = d->getcharinfo(); info.attach(item); } break; } //__offtools__ attachments: detach stuff case SV_DETACH: { int item = getint(p); if(d) { Character::CharacterInfo& info = d->getcharinfo(); info.detach(item); } break; } default: neterr("type", cn < 0); return; } if(initmap) { int mode = gamemode; const char *map = getclientmap(); if((multiplayer(false) && !m_mp(mode)) || (mode!=1 && !map[0])) { mode = remote ? lobbymode : localmode; map = remote ? lobbymap : localmap; } changemap(map, mode); } } //offtools: test recursive directory creation void createdirrecursive(const char* path) { string pname; string save; copystring(pname,path); copystring(save, pname); int depth = 0; while(!(fileexists(pname, "dw"))) { copystring(pname,parentdir(pname)); depth++; } // conoutf("found starting dir: %s, depth: %d", pname, depth); for(int i=0; iwrite(data, len); delete demo; break; } case SV_SENDMAP: { //offtools: receive map data char name[MAXTRANS]; getstring(name, p); data += p.length(); len -= p.length(); if(gamemode!=1) return; if(!rcvmap.status || rcvmap.finished()) rcvmap.init(-1, name); else if(!rcvmap.check(-1, name)) return; defformatstring(fname)("packages/base/getmap_%s.ogz", rcvmap.mname); path(fname); rcvmap.map = openrawfile(fname, "wb"); if(!rcvmap.map) { rcvmap.reset(); return; } rcvmap.map->write(data, len); rcvmap.status |= MD_GOTMAP; conoutf("received map"); if(rcvmap.finished()) { rcvmap.reset(); string oldname; copystring(oldname, getclientmap()); defformatstring(loadmap)("getmap_%s", rcvmap.mname); load_world(loadmap, oldname[0] ? oldname : NULL); rcvmap.clear(); } break; } //offtools: receive art-cfg file case SV_SENDCFG: { char name[MAXTRANS]; getstring(name, p); data += p.length(); len -= p.length(); if(gamemode!=1) return; if(!rcvmap.status || rcvmap.finished()) rcvmap.init(-1, name); else if(!rcvmap.check(-1, name)) return; defformatstring(fname)("packages/base/getmap_%s-art.cfg", rcvmap.mname); path(fname); rcvmap.cfg = openrawfile(fname, "wb"); if(!rcvmap.cfg) { rcvmap.reset(); return; } rcvmap.cfg->write(data, len); rcvmap.status |= MD_GOTCFG; conoutf("received cfg"); if(rcvmap.finished()) { rcvmap.reset(); string oldname; copystring(oldname, getclientmap()); defformatstring(loadmap)("getmap_%s", rcvmap.mname); load_world(loadmap, oldname[0] ? oldname : NULL); rcvmap.clear(); } break; } //offtools: receive textures case SV_SENDTEXTURE: { string name; getstring(name, p); int slot = getint(p); data += p.length(); len -= p.length(); path(name); stream *tex = openrawfile(name, "wb"); if(!tex) { conoutf("could not save texture"); return; } tex->write(data, len); delete tex; reloadslot(slot); break; } } } void parsepacketclient(int chan, packetbuf &p) // processes any updates from the server { switch(chan) { case 0: parsepositions(p); break; case 1: parsemessages(-1, NULL, p); break; case 2: receivefile(p.buf, p.maxlen); break; } } void getmap() { if(gamemode!=1) { conoutf(CON_ERROR, "\"getmap\" only works in coop edit mode"); return; } conoutf("getting map..."); addmsg(SV_GETMAP, "r"); } COMMAND(getmap, ""); void stopdemo() { if(remote) { if(player1->privilegeprivilegeprivilegestate==CS_SPECTATOR && remote && !player1->privilege)) { conoutf(CON_ERROR, "\"sendmap\" only works in coop edit mode"); return; } conoutf("sending map..."); defformatstring(mname)("sendmap_%d", lastmillis); save_world(mname, true); defformatstring(fname)("packages/base/%s.ogz", mname); defformatstring(cname)("packages/base/%s-art.cfg", mname); stream *map = openrawfile(fname, "rb"); stream *cfg = openrawfile(cname, "rb"); if(map && cfg) { int len = map->size(); if(len > 1024*1024) conoutf(CON_ERROR, "map is too large: %d", len); else if(len <= 0) conoutf(CON_ERROR, "could not read map"); else { sendfile(-1, 2, cfg, "ris", SV_UPLOADCFG, mname); sendfile(-1, 2, map, "ris", SV_UPLOADMAP, mname); } delete cfg; delete map; } else conoutf(CON_ERROR, "could not read map or cfg"); remove(findfile(fname, "rb")); remove(findfile(cname, "rb")); } COMMAND(sendmap, ""); void gotoplayer(const char *arg) { if(player1->state!=CS_SPECTATOR && player1->state!=CS_EDITING) return; int i = parseplayer(arg); if(i>=0) { DynamicEntity *d = getclient(i); if(!d || d==player1) return; player1->o = d->o; vec dir; vecfromyawpitch(player1->yaw, player1->pitch, 1, 0, dir); player1->o.add(dir.mul(-32)); player1->resetinterp(); } } COMMANDN(goto, gotoplayer, "s"); void gotosel() { if(player1->state!=CS_EDITING) return; player1->o = getselpos(); vec dir; vecfromyawpitch(player1->yaw, player1->pitch, 1, 0, dir); player1->o.add(dir.mul(-32)); player1->resetinterp(); } COMMAND(gotosel, ""); const char* scriptpath() { return "data/script/"; } //-----------------Bot Commands-------------------------- ICOMMAND(botlimit, "i", (int *n), addmsg(SV_BOTLIMIT, "ri", *n)); ICOMMAND(botbalance, "i", (int *n), addmsg(SV_BOTBALANCE, "ri", *n)); void setgesture(int gesture) { Character::CharacterInfo& info = player1->getcharinfo(); info.setgesture(gesture); } ICOMMAND(setgesture, "i", (int *g), { setgesture(*g); }); void setao(int ao, int gesture) { Character::CharacterInfo& info = player1->getcharinfo(); info.setao(ao, gesture); } ICOMMAND(setao, "ii", (int *ao, int *g), { setao(*ao, *g); }); void gesture(bool on) { Character::CharacterInfo& info = player1->getcharinfo(); info.dogesture = on; } ICOMMAND(gesture, "D", (int *down), { gesture(*down!=0); }); } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/characterinfo.cpp0000664000175000017500000000462011442705030024605 0ustar showardshoward#include "game.h" //#include "characterinfo.h" namespace Character { CharacterInfo::CharacterInfo() : playermodel(0), dogesture(false) { resetao(); } CharacterInfo::~CharacterInfo() {} void CharacterInfo::setplayermodel(int i) { if(PlayerModel::PlayerModels().inrange(i)) { playermodel = i; } } int CharacterInfo::getplayermodel() { return playermodel; } bool CharacterInfo::setgesture(int i) { PlayerModel::PlayerModelInfo& pm = PlayerModel::getPlayerModelInfo(playermodel); if(PlayerModel::HasAnimation(pm, i)) { ao[AO_GESTURE] = i; return true; } else return false; } bool CharacterInfo::setao(int idxao, int idxanim) { if(idxao >= 0 && idxao < AO_NUM) { PlayerModel::PlayerModelInfo& pm = PlayerModel::getPlayerModelInfo(playermodel); if(PlayerModel::HasAnimation(pm, idxanim)) { ao[idxao] = idxanim; return true; } } return false; } void CharacterInfo::attach(int num) { attacheditems.add(num); } void CharacterInfo::detach(int num) { attacheditems.remove(num); } void CharacterInfo::resetao() { ao[AO_DEAD] = ANIM_DEAD; ao[AO_DYING] = ANIM_DYING; ao[AO_IDLE] = ANIM_IDLE; ao[AO_FORWARD] = ANIM_FORWARD; ao[AO_BACKWARD] = ANIM_BACKWARD; ao[AO_LEFT] = ANIM_LEFT; ao[AO_RIGHT] = ANIM_RIGHT; ao[AO_HOLD] = ANIM_IDLE; ao[AO_ACTION] = ANIM_ATTACK1; ao[AO_PAIN] = ANIM_PAIN; ao[AO_GESTURE] = ANIM_TAUNT; ao[AO_JUMP] = ANIM_JUMP; ao[AO_SINK] = ANIM_SINK; ao[AO_EDIT] = ANIM_EDIT; ao[AO_LAG] = ANIM_LAG; } void playerattach(int i) { CharacterInfo& info = game::player1->getcharinfo(); info.attach(i); game::addmsg(SV_ATTACH, "rci", game::player1, i); } ICOMMAND(playerattach, "i", (int *i), playerattach(*i)); void playerdetach(int i) { CharacterInfo& info = game::player1->getcharinfo(); info.detach(i); game::addmsg(SV_DETACH, "rci", game::player1, i); } ICOMMAND(playerdetach, "i", (int *i), playerdetach(*i)); } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/roadmap0000664000175000017500000000133211442705030022634 0ustar showardshowardROADMAP: -------- DynamicEntity (dynent) *remove all game mode dependent stuff like attack, frags ... NPC Manager (formerly aiman.h) *should manage multiple npc client classes (bloodfrontier ai, MovieCube actors ...) Controls *different types of Controls like ai, moviecube actors *ControlActor provide the Moviecube Actor Features from sourceforge Version *change Controls which is assigned to an npc client (change between actor and ai) Waypoint *add waypoints for actors controls Actors *port actors from current sf version Modes (gamemode, gamestate): *make usage of mode (clientmode, servmode) mandatory (we have only one: machinima) *move gamestate data (weapons ...) into a mode class (srvmode->initclientgamestate)sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/map.h0000664000175000017500000000227011442705030022216 0ustar showardshoward#ifndef MAP_H_INCLUDED #define MAP_H_INCLUDED #include "cube.h" #include "singleton.h" //Singleton Template class, used for MapToc and Manager Classes (e.g. CameraMgr, QueuedCommandMgr) //template //class Singleton //{ //public: // static C& instance () // { // static C inst; // return inst; // } // //private: // Singleton( const Singleton& ) {} // //protected: // Singleton () { } //}; class MapTocEntry; class MapObject; class MapToc : public Singleton { //vector is just a placeholder until a better solution is found (hash) vector toc; int lastid; public: MapToc(); ~MapToc(); MapTocEntry& registerentry( MapObject& mapobject ); void removeentry( int id ); MapTocEntry* lookupentry( int id ); void writetoc(stream *f); void readtoc(int idx, int id); void lock(bool lk); void clear(); }; //Interface to all Entities, we need to save into toc class MapObject { public: MapTocEntry& entry; MapObject(); ~MapObject(); int getid(); }; class MapTocEntry { int id; MapObject& object; public: MapTocEntry( MapObject& mapobject, int id ); ~MapTocEntry(); int getid(); void setid(int i); }; #endif // MAP_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/action.cpp0000664000175000017500000000226011442705030023250 0ustar showardshoward#include "action.h" ActionMove::ActionMove(extentity& e) : Action(NULL), instance(gettype()), ent(e) { conoutf("ActionMove::ActionMove %p", &instance); dst = vec(ent.o); } ActionMove::~ActionMove() {} Control::ControlNPC& ActionMove::gettype() { return dynamic_cast(*QueuedCommandMgr::getcurrent()); } bool ActionMove::checktype() { return dynamic_cast( &instance ); } bool ActionMove::process() { float dist = dst.dist(vec(instance.dynent->o)); if (dist < ent.attr[1]) //waypoint reached: TODO: make depending from speed { instance.dynent->move = instance.dynent->strafe = 0; return true; } vec dir(dst); dir.sub(instance.dynent->o); dir.normalize(); instance.dynent->move = 1; // if (d->flying) { vectoyawpitch(dir, d->yaw, d->pitch); } // else { float dummy; vectoyawpitch(dir, d->yaw, dummy); } float dummy; vectoyawpitch(dir, instance.dynent->yaw, dummy); if(game::smoothmove && instance.dynent->smoothmillis>0) game::predictplayer(instance.dynent, true); else moveplayer(instance.dynent, 1, false); return false; } ICOMMAND(cq_move, "i", (int *wp), { new ActionMove(*entities::getents()[*wp]); } ); sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/pch.cpp0000664000175000017500000000002511442705030022542 0ustar showardshoward#include "game.h" sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/clientmode.h0000664000175000017500000000223011442705030023560 0ustar showardshoward/* * clientmode.h * * Created on: 17.12.2009 * Author: offtools */ #ifndef __CLIENTMODE_H__ #define __CLIENTMODE_H__ #include "modeinfo.h" //#include "dynentities.h" namespace game { struct clientmode { virtual ~clientmode() {} virtual void preload() {} virtual int clipconsole(int w, int h) { return 0; } virtual void drawhud(DynamicEntity *d, int w, int h) {} virtual void rendergame() {} virtual void respawned(DynamicEntity *d) {} virtual void setup() {} virtual void checkitems(DynamicEntity *d) {} virtual int respawnwait(DynamicEntity *d) { return 0; } virtual void pickspawn(DynamicEntity *d) {} virtual void senditems(packetbuf &p) {} virtual const char *prefixnextmap() { return "movie"; } virtual void removeplayer(DynamicEntity *d) {} virtual void gameover() {} }; struct defaultclientmode : clientmode { defaultclientmode() {} ~defaultclientmode() {} //find a spawn points for serveral client types void pickspawn(DynamicEntity *d); }; } #endif /* __CLIENTMODE_H__ */ sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/dynlight.cpp0000664000175000017500000000224111442705030023614 0ustar showardshoward#include "game.h" #include "extentity.h" namespace game { VARP(showlighting, 0, 1, 1); VARP(showdynlights, 0, 1, 1); bool dynlightsactive[32767]; void initdynlights() { for(int i = 0; i != 32767; i++) { dynlightsactive[i] = true; } } void setdynlightactivity(int *who, int *active) { if (*who > 32767 || *who <= 0) return; else if (!*active) dynlightsactive[*who] = false; else dynlightsactive[*who] = true; } COMMAND(setdynlightactivity, "ii"); #define renderfocus(i,f) { extentity &e = *entities::getents()[i]; f; } void renderentlight(extentity &e) { vec color(e.attr[1], e.attr[2], e.attr[3]); color.div(255.f); adddynlight(vec(e.o), float(e.attr[0] != 0 ? e.attr[0] > 0 ? e.attr[0] : 0 : getworldsize() ), color); } void adddynlights() { vector ents = entities::getents(); loopv(ents) { if((ents[i]->attr[4] > -1 && ents[i]->type == DYNLIGHT && dynlightsactive[ents[i]->attr[4]] && (!editmode || showdynlights)) //dynlights || ((entgroup.find(i) >= 0 || enthover == i) && (ents[i]->type == LIGHT) && (editmode && showlighting))) //normal lights { renderfocus(i, renderentlight(e)); } } } } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/mapentities.cpp0000664000175000017500000000400711442705030024316 0ustar showardshoward#include "game.h" namespace MapEntities { // vector ents; // bool senduids = false; // int getmapuid(extentity &e) { return ((StaticEntity&)e).getid(); } // // StaticEntity *findmapuid(int id) // { // loopv(ents) if(ents[i]->getid() == id) // { // return ents[i]; // } // return NULL; // } // // StaticEntity *findmapuid(int id, int type) // { // loopv(ents) if(ents[i]->getid() == id && ents[i]->type == type) // { // return ents[i]; // } // return NULL; // } // void setmapuid(int i, int uid) // { // if(!ents.inrange(i)) return; // // if(ents[i]->uid >= 0) // { // if(uid == ents[i]->uid) return; // else fatal("Error: MapEntities::setmapuid - uid differs from server uid, uid: %d %d", ents[i]->uid, uid); // } // ents[i]->uid = uid; // } // // void sendmapuids(bool send) { senduids = send; } // bool sendmapuids() { return senduids; } void putentities(packetbuf &p) { // putint(p, SV_MAPENTITIES); // loopv(ents) // { // putint(p, i); // } // putint(p, -2); // sendmapuids(false); } // // void delentity(StaticEntity *e) // { // delete e; // } // void delentity(extentity *e) // { // delete e; // } // // void clearents() // { // while(ents.length()) delentity(ents.pop()); // } // // void listwaypoints() // { // vector buf; // string lst; // loopv(ents) if(ents[i]->type == WAYPOINT) // { // StaticEntity& e = *ents[i]; // formatstring(lst)("%d", e.getid()); // buf.put(lst, strlen(lst)); // if(i < (ents.length()-1)) buf.add(' '); // } // buf.add('\0'); // result(buf.getbuf()); // } // ICOMMAND(listwaypoints, "", (), listwaypoints()); } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/moviecube.cpp0000664000175000017500000006535611506742670024004 0ustar showardshoward#include "game.h" #include "extentity.h" namespace game { int maptime = 0, maprealtime = 0, minremain = 0; int respawnent = -1; int lastspawnattempt = 0; int following = -1, followdir = 0; DynamicEntity *player1 = NULL; // our client vector players; // other clients bool clientoption(const char *arg) { return false; } void follow(char *arg) { ///TODO: set active camera follow // if(arg[0] ? player1->state==CS_SPECTATOR : following>=0) // { // following = arg[0] ? parseplayer(arg) : -1; // if(following==player1->clientnum) following = -1; // followdir = 0; // conoutf("follow %s", following>=0 ? "on" : "off"); // } } // COMMAND(follow, "s"); void nextfollow(int dir) { if(player1->state!=CS_SPECTATOR || clients.empty()) { stopfollowing(); return; } int cur = following >= 0 ? following : (dir < 0 ? clients.length() - 1 : 0); loopv(clients) { cur = (cur + dir + clients.length()) % clients.length(); if(clients[cur] && clients[cur]->state!=CS_SPECTATOR) { if(following<0) conoutf("follow on"); following = cur; followdir = dir; return; } } stopfollowing(); } ICOMMAND(nextfollow, "i", (int *dir), nextfollow(*dir < 0 ? -1 : 1)); const char *getclientmap() { return clientmap; } void resetgamestate() { // if(m_classicsp) // { clearmovables(); ///TODO: check new style triggers // resettriggers(); // } } DynamicEntity *spawnstate(DynamicEntity *d) // reset player state not persistent accross spawns { d->respawn(); d->spawnstate(gamemode); return d; } void respawnself() { if(paused || ispaused()) return; if(m_mp(gamemode)) { // if(player1->respawned!=player1->lifesequence) // { // addmsg(SV_TRYSPAWN, "rc", player1); // player1->respawned = player1->lifesequence; // } } else { spawnplayer(player1); #ifndef NEWGUI // if (deathscore) showscores(false); #endif // lasthit = 0; if(cmode) cmode->respawned(player1); } } bool intersect(dynent *d, const vec &from, const vec &to) // if lineseg hits entity bounding box { float dist; vec bottom(d->o), top(d->o); bottom.z -= d->eyeheight; top.z += d->aboveeye; return linecylinderintersect(from, to, bottom, top, d->radius, dist); } dynent *intersectclosest(const vec &from, const vec &to, DynamicEntity *at) { dynent *best = NULL; float bestdist = 1e16f; loopi(numdynents()) { dynent *o = iterdynents(i); if(o==at || o->state!=CS_ALIVE) continue; if(!intersect(o, from, to)) continue; float dist = at->o.dist(o->o); if(disto, worldpos)) return players[i]; return NULL; } void stopfollowing() { if(following<0) return; following = -1; followdir = 0; conoutf("follow off"); } DynamicEntity *followingplayer() { if(player1->state!=CS_SPECTATOR || following<0) return NULL; DynamicEntity *target = getclient(following); if(target && target->state!=CS_SPECTATOR) return target; return NULL; } DynamicEntity *hudplayer() { if(thirdperson) return player1; DynamicEntity *target = followingplayer(); return target ? target : player1; } void setupcamera() {} bool detachcamera() { return false; } bool collidecamera() { // switch(player1->state) // { // case CS_EDITING: return false; // case CS_SPECTATOR: return followingplayer()!=NULL; // } // return true; return !editmode; } VARP(smoothmove, 0, 75, 100); VARP(smoothdist, 0, 32, 64); void predictplayer(DynamicEntity *d, bool move) { d->o = d->newpos; d->yaw = d->newyaw; d->pitch = d->newpitch; if(move) { moveplayer(d, 1, false); d->newpos = d->o; } float k = 1.0f - float(lastmillis - d->smoothmillis)/smoothmove; if(k>0) { d->o.add(vec(d->deltapos).mul(k)); d->yaw += d->deltayaw*k; if(d->yaw<0) d->yaw += 360; else if(d->yaw>=360) d->yaw -= 360; d->pitch += d->deltapitch*k; } } //TODO: check if local or not - remove slowmosp, add new mode VARFP(slowmosp, 0, 0, 1, { if(m_sp && !slowmosp) setvar("gamespeed", 100); }); // void checkslowmo() // { // static int lastslowmohealth = 0; // setvar("gamespeed", intermission ? 100 : clamp(player1->health, 25, 200), true, false); // if(player1->healthmaxhealth && lastmillis-max(maptime, lastslowmohealth)>player1->health*player1->health/2) // { // lastslowmohealth = lastmillis; // player1->health++; // } // } void updatecontrols() { //check events, update ... loopv(Control::controls) { Control::controls[i]->update(); } } void updateworld() // main game update loop { if(!maptime) { maptime = lastmillis; maprealtime = totalmillis; return; } if(!curtime) { gets2c(); if(player1->clientnum>=0) c2sinfo(); return; } physicsframe(); // ai::trydropwaypoints(); // otherplayers(curtime); // ai::update(); moveragdolls(); gets2c(); updatemovables(curtime); // if(!multiplayer(false)) entities::checktriggers(); updatecontrols(); //Camera::update(); if(player1->clientnum>=0) c2sinfo(); // do this last, to reduce the effective frame lag } void spawnplayer(DynamicEntity *d) // place at random spawn { if(cmode) cmode->pickspawn(d); else findplayerspawn(d, d==player1 && respawnent>=0 ? respawnent : -1); spawnstate(d); if(d==player1) { if(editmode) d->state = CS_EDITING; else if(d->state != CS_SPECTATOR) d->state = CS_ALIVE; } else d->state = CS_ALIVE; } VARP(spawnwait, 0, 0, 1000); void respawn() { if(player1->state==CS_DEAD) { int wait = cmode ? cmode->respawnwait(player1) : 0; if(wait>0) { lastspawnattempt = lastmillis; //conoutf(CON_GAMEINFO, "\f2you must wait %d second%s before respawn!", wait, wait!=1 ? "s" : ""); return; } // if(lastmillis < player1->lastpain + spawnwait) return; if(m_dmsp) { changemap(clientmap, gamemode); return; } // if we die in SP we try the same map again respawnself(); } } bool canjump() { // if(!intermission) respawn(); respawn(); // return player1->state!=CS_DEAD && !intermission; return player1->state!=CS_DEAD; } bool allowmove(physent *d) { if(d->type!=ENT_PLAYER) return true; // return !((DynamicEntity *)d)->lasttaunt || lastmillis-((DynamicEntity *)d)->lasttaunt>=1000; return true; } void timeupdate(int timeremain) { minremain = timeremain; if(!timeremain) { // intermission = true; // player1->attacking = false; if(cmode) cmode->gameover(); conoutf(CON_GAMEINFO, "\f2intermission:"); conoutf(CON_GAMEINFO, "\f2game has ended!"); #ifndef NEWGUI // showscores(true); #endif disablezoom(); } else if(timeremain > 0) { conoutf(CON_GAMEINFO, "\f2time remaining: %d %s", timeremain, timeremain==1 ? "minute" : "minutes"); } } vector clients; DynamicEntity *newclient(int cn) // ensure valid entity { conoutf("DEBUG: game::newclient %d", cn); if(cn < 0 || cn > max(0xFF, MAXCLIENTS + MAXBOTS)) { neterr("clientnum", false); return NULL; } if(cn == player1->clientnum) return player1; while(cn >= clients.length()) clients.add(NULL); if(!clients[cn]) { DynamicEntity *d = new DynamicEntity; conoutf("DEBUG: newclient DynamicEntity %d", cn); d->clientnum = cn; clients[cn] = d; players.add(d); } return clients[cn]; } DynamicEntity *getclient(int cn) // ensure valid entity { if(cn == player1->clientnum) return player1; return clients.inrange(cn) ? clients[cn] : NULL; } void clientdisconnected(int cn, bool notify) { conoutf("DEBUG: game::clientdisconnected cn: %d", cn); if(!clients.inrange(cn)) return; if(following==cn) { if(followdir) nextfollow(followdir); else stopfollowing(); } DynamicEntity *d = clients[cn]; if(!d) return; if(notify && d->name[0]) conoutf("player %s disconnected", colorname(d)); removetrackedparticles(d); removetrackeddynlights(d); if(cmode) cmode->removeplayer(d); players.removeobj(d); DELETEP(clients[cn]); cleardynentcache(); } void clearclients(bool notify) { loopv(clients) if(clients[i]) clientdisconnected(i, notify); } void initclient() { player1 = spawnstate(new DynamicEntity); players.add(player1); Control::Control* cp = Control::controls.add(&Control::GetPlayer()); cp->connect(player1); //adds a basic camera //CameraManager::New("0"); // Extentities::Init(); Extentities::Init(); Cutscenes::Init(); } VARP(showmodeinfo, 0, 1, 1); void setwindowcaption() { defformatstring(capt)("Sandbox %s: %s - %s", version, server::modename(gamemode, "unknown"), getclientmap()[0] ? getclientmap() : "[new map]"); SDL_WM_SetCaption(capt, NULL); } void startgame() { // conoutf("DEBUG: cl startgame modename %d", gamemode); clearmovables(); clearragdolls(); setclientmode(); ///TODO: clearactions(); // intermission = false; maptime = 0; if(cmode) { cmode->preload(); cmode->setup(); } conoutf(CON_GAMEINFO, "\f2game mode is %s", server::modename(gamemode)); if(m_sp) { defformatstring(scorename)("bestscore_%s", getclientmap()); const char *best = getalias(scorename); if(*best) conoutf(CON_GAMEINFO, "\f2try to beat your best score so far: %s", best); } else { const char *info = m_valid(gamemode) ? gamemodes[gamemode - STARTGAMEMODE].info : NULL; if(showmodeinfo && info) conoutf(CON_GAMEINFO, "\f0%s", info); } // if(player1->playermodel != getclientmodel(player)) switchplayermodel(getplayermodel()); // showscores(false); disablezoom(); // lasthit = 0; if(identexists("mapstart")) execute("mapstart"); } void startmap(const char *name) // called just after a map load { // conoutf("DEBUG: game::startmap"); // ai::savewaypoints(); // ai::clearwaypoints(true); // MapToc::Get().lock(true); // toclocked = 1; initdynlights(); respawnent = -1; // so we don't respawn at an old spot if(!m_mp(gamemode)) spawnplayer(player1); else findplayerspawn(player1, -1); // entities::resetspawns(); //Camera::reset(); copystring(clientmap, name ? name : ""); sendmapinfo(); } const char *getmapinfo() { return showmodeinfo && m_valid(gamemode) ? gamemodes[gamemode - STARTGAMEMODE].info : NULL; } void physicstrigger(physent *d, bool local, int floorlevel, int waterlevel, int material) { if(d->state!=CS_ALIVE||d->type==ENT_INANIMATE) return; switch(material) { case MAT_LAVA: if (waterlevel==0) break; playsound(S_BURN, d==player1 ? NULL : &d->o); loopi(60) { vec o = d->o; o.z -= d->eyeheight *i/60.0f; regular_particle_flame(PART_FLAME, o, 6, 2, 0x903020, 3, 2.0f); regular_particle_flame(PART_SMOKE, vec(o.x, o.y, o.z + 8.0f), 6, 2, 0x303020, 1, 4.0f, 100.0f, 2000.0f, -20); } break; case MAT_WATER: if (waterlevel==0) break; playsound(waterlevel > 0 ? S_SPLASH1 : S_SPLASH2 , d==player1 ? NULL : &d->o); particle_splash(PART_WATER, 200, 200, d->o, (watercolor.x<<16) | (watercolor.y<<8) | watercolor.z, 0.5); break; default: if (floorlevel==0) break; playsound(floorlevel > 0 ? S_JUMP : S_LAND, local ? NULL : &d->o); break; } } void dynentcollide(physent *d, physent *o, const vec &dir) { switch(d->type) { //case ENT_AI: if(dir.z > 0) stackmonster((monster *)d, o); break; case ENT_INANIMATE: if(dir.z > 0) stackmovable((movable *)d, o); break; } } void bounced(physent *d, const vec &surface) {} void msgsound(int n, physent *d) { if(!d || d==player1) { addmsg(SV_SOUND, "ci", d, n); playsound(n); } else { // if(d->type==ENT_PLAYER && ((DynamicEntity *)d)->ai) if(d->type==ENT_PLAYER) //TODO: check bot addmsg(SV_SOUND, "ci", d, n); playsound(n, &d->o); } } int numdynents() { return players.length()+movables.length(); } dynent *iterdynents(int i) { if(iname; loopv(players) if(d!=players[i] && !strcmp(name, players[i]->name)) return true; return false; } const char *colorname(DynamicEntity *d, const char *name, const char *prefix) { if(!name) name = d->name; if(name[0] && !duplicatename(d, name) && d->controltype == CONTROL_PLAYER) return name; static string cname[3]; static int cidx = 0; cidx = (cidx+1)%3; formatstring(cname[cidx])(d->controltype == CONTROL_PLAYER ? "%s%s \fs\f5(%d)\fr" : "%s%s \fs\f5[%d]\fr", prefix, name, d->clientnum); return cname[cidx]; } void suicide(physent *d) { // if(d==player1 || (d->type==ENT_PLAYER && ((DynamicEntity *)d)->ai)) // if(d==player1) // { // if(d->state!=CS_ALIVE) return; // DynamicEntity *pl = (DynamicEntity *)d; // if(!m_mp(gamemode)) killed(pl, pl); // else if(pl->suicided!=pl->lifesequence) // { // addmsg(SV_SUICIDE, "rc", pl); // pl->suicided = pl->lifesequence; // } // } // else if(d->type==ENT_AI) suicidemonster((monster *)d); // if(d->type==ENT_INANIMATE) suicidemovable((movable *)d); } // ICOMMAND(nap, "", (), suicide(player1)); void drawicon(int icon, float x, float y, float sz) { settexture("packages/hud/items.png"); glBegin(GL_QUADS); float tsz = 0.25f, tx = tsz*(icon%4), ty = tsz*(icon/4); glTexCoord2f(tx, ty); glVertex2f(x, y); glTexCoord2f(tx+tsz, ty); glVertex2f(x+sz, y); glTexCoord2f(tx+tsz, ty+tsz); glVertex2f(x+sz, y+sz); glTexCoord2f(tx, ty+tsz); glVertex2f(x, y+sz); glEnd(); } float abovegameplayhud(int w, int h) { switch(hudplayer()->state) { case CS_EDITING: case CS_SPECTATOR: return 1; default: return 1650.0f/1800.0f; } } void drawhudicons(DynamicEntity *d) { } void gameplayhud(int w, int h) { // SB::RenderHud(w,h); // glPushMatrix(); // glScalef(h/1800.0f, h/1800.0f, 1); // // if(player1->state==CS_SPECTATOR) // { // int pw, ph, tw, th, fw, fh; // text_bounds(" ", pw, ph); // text_bounds("SPECTATOR", tw, th); // th = max(th, ph); // DynamicEntity *f = followingplayer(); // text_bounds(f ? colorname(f) : " ", fw, fh); // fh = max(fh, ph); // draw_text("SPECTATOR", w*1800/h - tw - pw, 1650 - th - fh); // if(f) draw_text(colorname(f), w*1800/h - fw - pw, 1650 - fh); // } // // /*DynamicEntity *d = hudplayer(); // if(d->state!=CS_EDITING) // { // if(d->state!=CS_SPECTATOR) drawhudicons(d); // if(cmode) cmode->drawhud(d, w, h); // }*/ // // glPopMatrix(); } int clipconsole(int w, int h) { if(cmode) return cmode->clipconsole(w, h); return 0; } // VARP(teamcrosshair, 0, 1, 1); VARP(hitcrosshair, 0, 425, 1000); const char *defaultcrosshair(int index) { switch(index) { case 3: return "packages/crosshairs/edit.png"; case 2: return "packages/crosshairs/hit.png"; case 1: return "packages/crosshairs/teammate.png"; default: return "packages/crosshairs/default.png"; } } int selectcrosshair(float &r, float &g, float &b) { DynamicEntity *d = hudplayer(); if(editmode) { r = g = 0.5f; b = 1; return 3; } if(d->state==CS_SPECTATOR || d->state==CS_DEAD) return -1; if(d->state!=CS_ALIVE) return 0; int crosshair = 0; // if(lasthit && lastmillis - lasthit < hitcrosshair) crosshair = 2; // // if(crosshair!=1 && !m_insta) // { // if(d->health<=25) { r = 1.0f; g = b = 0; } // else if(d->health<=50) { r = 1.0f; g = 0.5f; b = 0; } // } // if(d->gunwait) { r *= 0.5f; g *= 0.5f; b *= 0.5f; } return crosshair; } void lighteffects(dynent *e, vec &color, vec &dir) { #if 0 DynamicEntity *d = (DynamicEntity *)e; if(d->state!=CS_DEAD && d->quadmillis) { float t = 0.5f + 0.5f*sinf(2*M_PI*lastmillis/1000.0f); color.y = color.y*(1-t) + t; } #endif } void particletrack(physent *owner, vec &o, vec &d) { if(owner->type!=ENT_PLAYER && owner->type!=ENT_AI) return; DynamicEntity *pl = (DynamicEntity *)owner; // if(pl->muzzle.x < 0 || pl->lastattackgun != pl->gunselect) return; if(pl->muzzle.x < 0) return; float dist = o.dist(d); o = pl->muzzle; if(dist <= 0) d = o; else { vecfromyawpitch(owner->yaw, owner->pitch, 1, 0, d); float newdist = raycube(owner->o, d, dist, RAY_CLIPMAT|RAY_ALPHAPOLY); d.mul(min(newdist, dist)).add(owner->o); } } void dynlighttrack(physent *owner, vec &o) { if(owner->type!=ENT_PLAYER && owner->type!=ENT_AI) return; DynamicEntity *pl = (DynamicEntity *)owner; // if(pl->muzzle.x < 0 || pl->lastattackgun != pl->gunselect) return; o = pl->muzzle; } #ifndef NEWGUI bool serverinfostartcolumn(g3d_gui *g, int i) { static const char *names[] = { "ping ", "players ", "map ", "mode ", "master ", "host ", "port ", "description " }; static const int struts[] = { 0, 0, 12, 12, 8, 13, 6, 24 }; if(size_t(i) >= sizeof(names)/sizeof(names[0])) return false; g->pushlist(); g->text(names[i], 0xFFFF80, !i ? "server" : NULL); if(struts[i]) g->strut(struts[i]); g->mergehits(true); return true; } void serverinfoendcolumn(g3d_gui *g, int i) { g->mergehits(false); g->poplist(); } bool serverinfoentry(g3d_gui *g, int i, const char *name, int port, const char *sdesc, const char *map, int ping, const vector &attr, int np) { if(ping < 0 || attr.empty() || attr[0]!=PROTOCOL_VERSION) { switch(i) { case 0: if(g->button(" ", 0xFFFFDD, "server")&G3D_UP) return true; break; case 1: case 2: case 3: case 4: if(g->button(" ", 0xFFFFDD)&G3D_UP) return true; break; case 5: if(g->buttonf("%s ", 0xFFFFDD, NULL, name)&G3D_UP) return true; break; case 6: if(g->buttonf("%d ", 0xFFFFDD, NULL, port)&G3D_UP) return true; break; case 7: if(ping < 0) { if(g->button(sdesc, 0xFFFFDD)&G3D_UP) return true; } else if(g->buttonf("[%s protocol] ", 0xFFFFDD, NULL, attr.empty() ? "unknown" : (attr[0] < PROTOCOL_VERSION ? "older" : "newer"))&G3D_UP) return true; break; } return false; } switch(i) { case 0: if(g->buttonf("%d ", 0xFFFFDD, "server", ping)&G3D_UP) return true; break; case 1: if(attr.length()>=4) { if(g->buttonf("%d/%d ", 0xFFFFDD, NULL, np, attr[3])&G3D_UP) return true; } else if(g->buttonf("%d ", 0xFFFFDD, NULL, np)&G3D_UP) return true; break; case 2: if(g->buttonf("%.25s ", 0xFFFFDD, NULL, map)&G3D_UP) return true; break; case 3: if(g->buttonf("%s ", 0xFFFFDD, NULL, attr.length()>=2 ? server::modename(attr[1], "") : "")&G3D_UP) return true; break; case 4: if(g->buttonf("%s ", 0xFFFFDD, NULL, attr.length()>=5 ? server::mastermodename(attr[4], "") : "")&G3D_UP) return true; break; case 5: if(g->buttonf("%s ", 0xFFFFDD, NULL, name)&G3D_UP) return true; break; case 6: if(g->buttonf("%d ", 0xFFFFDD, NULL, port)&G3D_UP) return true; break; case 7: if(g->buttonf("%.25s", 0xFFFFDD, NULL, sdesc)&G3D_UP) return true; break; } return false; } #endif bool showenthelpers() { if(m_edit || editmode) return true; return false; } bool needminimap() { return 0; } bool allowdoublejump() {return false;} bool mousemove(int &dx, int &dy, float &cursens) {return false;} //NOTE FIXME TODO @offtools, get rid of the camera hack and use this to update the camera and do cutscenes and... stuff bool recomputecamera(physent *&camera1, physent &tempcamera, bool &detachedcamera, float &thirdpersondistance) { // using namespace Camera; ///TODO: leave thirdperson 1|2 as it is if(editmode || !thirdperson) return false; detachedcamera = true; // CameraManager::Update(); return true; } void writemapdata(stream *f) { f->printf("\n//=============Map TOC (moviecube)=============\n\n"); // MapToc::Get().writetoc(f); } // any data written into this vector will get saved with the map data. Must take care to do own versioning, and endianess if applicable. Will not get called when loading maps from other games, so provide defaults. void writegamedata(vector &extras) {} void readgamedata(vector &extras) {} const char *gameident() { return "movie"; } const char *autoexec() { return "autoexec.cfg"; } const char *savedservers() { return "servers.cfg"; } void loadconfigs() { execfile("auth.cfg", false); } void g3d_gamemenus() {} VARP(allowdownload, 0, 0, 1); //offtools: download stuff if server supports it //offtools: scriptprefix SVARP(scriptprefix, "data/script/"); //__offtools__: fallback on missing texture void texturefailed(char *file, int slot) { if (multiplayer(false) && m_edit)// && allowdownload) { conoutf("debug: file requested by texture command doesnt exists: %s", file); addmsg(SV_TEXTUREREQUEST, "rsi", file, slot); } } //__offtools__: fallback on missing mapmodel void mmodelfailed(const char *name, int idx) { conoutf("mmodel failed %s : %d", name, idx); if (multiplayer(false) && m_edit)// && allowdownload) { conoutf("[debug]: dummy - download requested mmodel \"%s\" from server", name); } } //__offtools__: fallback on missing map void mapfailed(const char *name) { conoutf("map failed %s", name); if (multiplayer(false) && m_edit)// && allowdownload) { conoutf("[debug]: dummy - download requested map \"%s\" from server", name); } } //__offtools__ moviecube needs this, usefull to query model animations (especially addional ones) void registeranimation(char *loadname, char* anim, int num) { PlayerModel::RegisterAnimation(loadname, anim, num); } // void dummyarglist(char **arg, int num) // { // loopi(num) // { // conoutf("ARG[%d]: %s", i, arg[i]); // } // } // ICOMMAND(dummyarglist, "V", (char** arg, int* num), dummyarglist(arg, *num)); } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/camera.cpp0000664000175000017500000000374611442705030023235 0ustar showardshoward#include "camera.h" namespace Cutscenes { // vector cameras; // int current = -1; // void Init() { ScriptManagerRegister("cutscene"); } // void Update() // { // if ( current >= 0 ) // { // cameras[current]->process(); // camera1 = cameras[current]; // } // } } Cutscene::Cutscene(EntityScript::Script& s) : EntityScript::Instance(s) { registersignal("reachedwaypoint", SIGNAL_BUILTIN, "i"); } Cutscene::~Cutscene() {} void Cutscene::debug() { conoutf("Cutscene::debug"); } ActionScene::ActionScene(int d) : Action(NULL), startmillis(-1), duration(d) {} ActionScene::~ActionScene() {} float ActionScene::multiplier(bool total = false) { if(!duration) return 1; if(total) return min(1, (lastmillis - startmillis) / (float)duration); else { int elapsed = curtime; if(lastmillis >= startmillis + duration) elapsed -= (lastmillis - startmillis - duration); return (float) elapsed / duration; } } ActionCameraMove::ActionCameraMove(extentity& e, int d) : ActionScene(d), ent(e), dx(0), dy(0), dz(0) { start = dest = vec(0,0,0); startmillis = lastmillis; vec dest = ent.o; start = vec(camera1->o); dest.sub(start); dx = dest.x; dy = dest.y; dz = dest.z; } ActionCameraMove::~ActionCameraMove() {} bool ActionCameraMove::process() { // if(startmillis + duration >= lastmillis) // { // EntityScript::GetInstance()->o = vec(dx, dy, dz).mul(multiplier(true)).add(start); // return false; // } // // .emmitsignal("reachedwaypoint", 0); // conoutf("TEST: ActionCameraMove::process: %p",) return true; } //ICOMMAND(move, "ii", (int *id, int *d), // { // new ActionMove(*entities::getents()[*id], *d); // } //); ICOMMAND(test_action, "", (), { Action* action = new CommandMove(); } ); sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/control.cpp0000664000175000017500000001722211442705030023457 0ustar showardshoward//////////////////////////////////////////////////////// // control.cpp // // Created on: 08.12.2009 // Author: offtools //////////////////////////////////////////////////////// #include "game.h" namespace Control { int lastid = -1; //--------------Control Player----------------------- Control::Control() : uid(-1), dynent(NULL), isinit(false) {} Control::~Control() {} //--------------Control Player----------------------- ControlPlayer::ControlPlayer() : Control(), k_left(false), k_right(false), k_up(false), k_down(false), k_rise(false), k_des(false), k_yawleft(false), k_yawright(false), k_action1(false), k_action2(false) { uid = -1; dynent = NULL; isinit = false; } ControlPlayer::~ControlPlayer() {} void ControlPlayer::connect(DynamicEntity* de) { dynent = de; dynent->controltype = CONTROL_PLAYER; isinit = true; } void ControlPlayer::spawn() { if(!editmode) { dynent->state = CS_ALIVE; game::addmsg(SV_TRYSPAWN, "rc", dynent); } } void ControlPlayer::update() { if(isinit) { ///TODO: check time, make turn depending on fps if(k_yawleft) dynent->yaw -= 1; else if(k_yawright) dynent->yaw += 1; moveplayer(dynent, 10, true); ///TODO: move to DynamicEntity //game::swayhudgun(curtime); //entities::checkitems(dynent); } } void ControlPlayer::disconnect() {} Control* ControlPlayer::cleanup() { return NULL; } void ControlPlayer::forward(int down) { k_up = down!=0; dynent->move = k_up ? 1 : (k_down ? -1 : 0); } void ControlPlayer::backward(int down) { k_down = down!=0; dynent->move = k_down ? -1 : (k_up ? 1 : 0); } void ControlPlayer::right(int down) { k_right = down!=0; dynent->strafe = k_right ? 1 : (k_left ? -1 : 0); } void ControlPlayer::left(int down) { k_left = down!=0; dynent->strafe = k_left ? -1 : (k_right ? 1 : 0); } void ControlPlayer::turnleft(int down) { k_yawleft = down!=0; } void ControlPlayer::turnright(int down) { k_yawright = down!=0; } //--------------Control Remote----------------------- ControlRemote::ControlRemote() : Control() { uid = -1; dynent = NULL; isinit = false; } ControlRemote::~ControlRemote() { cleanup(); } void ControlRemote::connect(DynamicEntity* de) { dynent = de; dynent->controltype = CONTROL_REMOTE; isinit = true; } void ControlRemote::spawn() {} void ControlRemote::update() { if(isinit) { //game::otherplayers if(dynent->state==CS_DEAD && dynent->ragdoll) moveragdoll(dynent); const int lagtime = lastmillis-dynent->lastupdate; if(!lagtime) { return; } else if(lagtime>1000 && dynent->state==CS_ALIVE) { dynent->state = CS_LAGGED; return; } if(dynent->state==CS_ALIVE || dynent->state==CS_EDITING) { if(game::smoothmove && dynent->smoothmillis>0) game::predictplayer(dynent, true); else moveplayer(dynent, 1, false); } else if(dynent->state==CS_DEAD && !dynent->ragdoll) moveplayer(dynent, 1, true); } } void ControlRemote::disconnect() {} Control* ControlRemote::cleanup() { controls.removeobj(this); game::clientdisconnected(dynent->clientnum); return this; } //--------------Control Ai----------------------- ControlAi::ControlAi() { uid = ++lastid; dynent = NULL; isinit = false; } void ControlAi::connect(DynamicEntity* de) { dynent = de; dynent->controltype = CONTROL_AI; copystring(dynent->name, "blood-ai"); isinit = true; } void ControlAi::spawn() {} void ControlAi::update() {} void ControlAi::disconnect() {} Control* ControlAi::cleanup() { return NULL; } //--------------Control Actor----------------------- ControlNPC::ControlNPC(QueuedCommand& qu) : Control(), Instance(qu) { if(!editmode) { uid = ++lastid; } else { uid = -1; } dynent = NULL; registersignal("reachedwaypoint"); registersignal("collidewall"); registersignal("collideent"); isinit = false; } ControlNPC::~ControlNPC() { } void ControlNPC::connect(DynamicEntity* de) { if(!de) fatal("Controler::Character : no valid Dynamic Entity. Exit!"); dynent = de; ///TODO: set name ActionInstance defformatstring(s)("%p", this); copystring(dynent->name, s); ///TODO: set and send basic infos like name, model ... // filtertext(dynent->name, lib.librarydescr, false, MAXNAMELEN); game::addmsg(SV_SWITCHNAME, "rs", dynent->name); dynent->controltype = CONTROL_NPC; dynent->lastupdate = lastmillis; ///TODO: spawn behaviour in edit and normal mode //first spawn, no actions defined in Actionlib // if(editmode) // { dynent->o = vec(game::player1->o); droptofloor(dynent->o, 0, 0); vec sp = vec(0,0,0); vecfromyawpitch(game::player1->yaw, 0, 50, 0, sp); dynent->o.add(sp); dynent->o.z += dynent->eyeheight; game::addmsg(SV_TRYSPAWN, "rc", dynent); // } Instance::init(); isinit = true; } void ControlNPC::spawn() {} void ControlNPC::update() { if(isinit) { process(); if(dynent->state == CS_LAGGED) { dynent->lastupdate = lastmillis; //TODO: add a real check } } } void ControlNPC::disconnect() { isinit = false; game::addmsg(SV_DELETEBOT, "ri", dynent->clientnum); } Control* ControlNPC::cleanup() { controls.removeobj(this); game::clientdisconnected(dynent->clientnum); return this; } ICOMMAND(cq_character, "s", (char *s), { QueuedCommand* c = QueuedCommandMgr::findqueued(s); if(c) { ControlNPC* controler = new ControlNPC(*c); controls.add(controler); game::addmsg(SV_REQUESTBOT, "r"); //return controler->uid; // new ControlNPC(*c); // character->init(); } } ); ////////////////////////////////////////////////////////////////////// //Control - external Interface Functions ////////////////////////////////////////////////////////////////////// ControlPlayer& GetPlayer() { static ControlPlayer player; return player; } ICOMMAND(moveforward, "D", (int *down), { GetPlayer().forward(*down); }); ICOMMAND(movebackward, "D", (int *down), { GetPlayer().backward(*down); }); ICOMMAND(moveright, "D", (int *down), { GetPlayer().right(*down); }); ICOMMAND(moveleft, "D", (int *down), { GetPlayer().left(*down); }); ICOMMAND(turnleft, "D", (int *down), { GetPlayer().turnleft(*down); }); ICOMMAND(turnright, "D", (int *down), { GetPlayer().turnright(*down); }); vector controls; } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/changelog0000664000175000017500000000062111442705030023140 0ustar showardshowardchangelog: 20091204: *removed monsters *basic waypoint entity added *Control class (will be used as common interface for NPC clients like actors or ai) *command: addnpc adds an NPC client with ControlActor to the first waypoint in map *deactivated ai until Control class is fully working *added some workarounds for controls in aiman.h (aiman will be changed to npcmananager for actor and ai later) sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/playermodelinfo.cpp0000664000175000017500000001234111442705030025165 0ustar showardshoward#include "playermodelinfo.h" namespace PlayerModel { vector playermodels; PlayerModelInfo::PlayerModelInfo(const char* _name) : name(newstring(_name)), ragdoll(true), selectable(true) {} void PlayerModelInfo::registeranimation(char *anim, int num) { loopv(animinfo) if( strcmp(animinfo[i]->descr, anim ) == 0) { return; } animinfo.add(new animationinfo(anim, num)); conoutf("PlayerModelInfo::registeranimation: %s", animinfo.last()->descr); } void PlayerModelInfo::registeritem( int part, char* model, int rule) { iteminfo.add(new attachmentinfo(part, model, rule)); } bool PlayerModelInfo::hasanimation(int anim) { loopv(animinfo) { if(animinfo[i]->index == anim) return true; } return false; } char* PlayerModelInfo::getname() { return name; } vector PlayerModels() { return playermodels; } PlayerModelInfo& getPlayerModelInfo(int i) { if(playermodels.inrange(i)) return *playermodels[i]; else return *playermodels[0]; } void RegisterAnimation(char *loadname, char* anim, int num) { loopv(playermodels) { if(strcmp(loadname, playermodels[i]->name) == 0) { playermodels[i]->registeranimation(anim, num); return; } } } bool HasAnimation(PlayerModelInfo& pm, int anim) { return pm.hasanimation(anim); } const char* GetName(PlayerModelInfo& pm) { return pm.getname(); } int RegisterModel(const char *s) { loopv(playermodels) { if(strcmp(playermodels[i]->name, s) == 0) { conoutf("DEBUG: PlayerModel::RegisterModel - model: %s already registered", playermodels[i]->name); return -1; } } playermodels.add(new PlayerModelInfo(s)); preloadmodel(s); return playermodels.length() - 1; } ICOMMAND(registercharactermodel, "s", (char *s), intret(RegisterModel(s))); void RegisterItem(int playermodel, int part, char* model, int rule) { if(loadmodel(model) && playermodels.inrange(playermodel)) { PlayerModelInfo* info = playermodels[playermodel]; info->registeritem(part, model, rule); conoutf("DEBUG: PlayerModel::RegisterItem - register item model: %s", model); } else { conoutf("PlayerModel::RegisterItem - could not register model: %s", model); return; } } ICOMMAND(registercharacteritem, "iisi", (int *i, int *p, char *s, int *r), RegisterItem(*i, *p, s, *r)); void BuildModelAttach(PlayerModelInfo& pm, int itemnum, modelattach& a) { if(!pm.iteminfo.inrange(itemnum)) return; int animrule = pm.iteminfo[itemnum]->rule; int bpart = pm.iteminfo[itemnum]->bodypart; const char* tag = pm.iteminfo[itemnum]->gettag(bpart); int animtime; switch (pm.iteminfo[itemnum]->rule) { case ATTACH_ANIM_IDLE: { animrule = ANIM_IDLE|ANIM_LOOP; animtime = 0; break; } case ATTACH_ANIM_FULL: { animrule = -1; animtime = 0; break; } case ATTACH_ANIM_NONE: default: { animrule = -1; animtime = 0; break; } } a = modelattach(tag, pm.iteminfo[itemnum]->model, animrule, animtime); } void listanimations(int idx) { vector buf; string lst; if(playermodels.inrange(idx)) { PlayerModelInfo* info = playermodels[idx]; loopv(info->animinfo) { formatstring(lst)("%d:%s", info->animinfo[i]->index, info->animinfo[i]->descr); buf.put(lst, strlen(lst)); if(i < (info->animinfo.length()-1)) buf.add(' '); } buf.add('\0'); result(buf.getbuf()); } } ICOMMAND(listmodelanimations, "i", (int *i), listanimations(*i)); void listitems(int idx) { vector buf; string lst; if(playermodels.inrange(idx)) { PlayerModelInfo* info = playermodels[idx]; loopv(info->iteminfo) { int bpart = info->iteminfo[i]->bodypart; formatstring(lst)("%s:%s", info->iteminfo[i]->getbodypart(bpart), info->iteminfo[i]->model); buf.put(lst, strlen(lst)); if(i < (info->animinfo.length()-1)) buf.add(' '); } buf.add('\0'); result(buf.getbuf()); } } ICOMMAND(listmodelitems, "i", (int *i), listitems(*i)); void listplayermodels() { vector buf; string lst; loopv(playermodels) { formatstring(lst)("%s", GetName( getPlayerModelInfo(i)) ); buf.put(lst, strlen(lst)); if(i < (playermodels.length()-1)) buf.add(' '); } buf.add('\0'); result(buf.getbuf()); } ICOMMAND(listplayermodels, "i", (), listplayermodels()); } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/extinfo.h0000664000175000017500000001235011442705030023115 0ustar showardshoward #define EXT_ACK -1 #define EXT_VERSION 104 #define EXT_NO_ERROR 0 #define EXT_ERROR 1 #define EXT_PLAYERSTATS_RESP_IDS -10 #define EXT_PLAYERSTATS_RESP_STATS -11 #define EXT_UPTIME 0 #define EXT_PLAYERSTATS 1 //#define EXT_TEAMSCORE 2 /* Client: ----- A: 0 EXT_UPTIME B: 0 EXT_PLAYERSTATS cn #a client number or -1 for all players# C: 0 EXT_TEAMSCORE Server: -------- A: 0 EXT_UPTIME EXT_ACK EXT_VERSION uptime #in seconds# B: 0 EXT_PLAYERSTATS cn #send by client# EXT_ACK EXT_VERSION 0 or 1 #error, if cn was > -1 and client does not exist# ... EXT_PLAYERSTATS_RESP_IDS pid(s) #1 packet# EXT_PLAYERSTATS_RESP_STATS pid playerdata #1 packet for each player# C: 0 EXT_TEAMSCORE EXT_ACK EXT_VERSION 0 or 1 #error, no teammode# remaining_time gamemode loop(teamdata [numbases bases] or -1) Errors: -------------- B:C:default: 0 command EXT_ACK EXT_VERSION EXT_ERROR */ void extinfoplayer(ucharbuf &p, clientinfo *ci) { ucharbuf q = p; putint(q, EXT_PLAYERSTATS_RESP_STATS); // send player stats following putint(q, ci->clientnum); //add player id putint(q, ci->ping); sendstring(ci->name, q); // sendstring(ci->team, q); // putint(q, ci->state.frags); // putint(q, ci->state.flags); // putint(q, ci->state.deaths); // putint(q, ci->state.teamkills); // putint(q, ci->state.damage*100/max(ci->state.shotdamage,1)); // putint(q, ci->state.health); // putint(q, ci->state.armour); // putint(q, ci->state.gunselect); putint(q, ci->privilege); putint(q, ci->state.state); uint ip = getclientip(ci->clientnum); q.put((uchar*)&ip, 3); sendserverinforeply(q); } // void extinfoteams(ucharbuf &p) // { // putint(p, m_teammode ? 0 : 1); // putint(p, gamemode); // putint(p, minremain); // if(!m_teammode) return; // // vector scores; // // //most taken from scoreboard.h // if(smode && smode->hidefrags()) // { // smode->getteamscores(scores); // loopv(clients) if(clients[i]->team[0]) // { // clientinfo *ci = clients[i]; // teamscore *ts = NULL; // loopvj(scores) if(!strcmp(scores[j].team, ci->team)) { ts = &scores[j]; break; } // if(!ts) scores.add(teamscore(ci->team, 0)); // } // } // else // { // loopv(clients) if(clients[i]->team[0]) // { // clientinfo *ci = clients[i]; // teamscore *ts = NULL; // loopvj(scores) if(!strcmp(scores[j].team, ci->team)) { ts = &scores[j]; break; } // if(!ts) scores.add(teamscore(ci->team, ci->state.frags)); // else ts->score += ci->state.frags; // } // } // // loopv(scores) // { // sendstring(scores[i].team, p); // putint(p, scores[i].score); // // if(!smode || !smode->extinfoteam(scores[i].team, p)) // putint(p,-1); //no bases follow // } // } void extserverinforeply(ucharbuf &req, ucharbuf &p) { int extcmd = getint(req); // extended commands //Build a new packet putint(p, EXT_ACK); //send ack putint(p, EXT_VERSION); //send version of extended info switch(extcmd) { case EXT_UPTIME: { putint(p, uint(totalmillis)/1000); //in seconds break; } case EXT_PLAYERSTATS: { int cn = getint(req); //a special player, -1 for all clientinfo *ci = NULL; if(cn >= 0) { loopv(clients) if(clients[i]->clientnum == cn) { ci = clients[i]; break; } if(!ci) { putint(p, EXT_ERROR); //client requested by id was not found sendserverinforeply(p); return; } } putint(p, EXT_NO_ERROR); //so far no error can happen anymore ucharbuf q = p; //remember buffer position putint(q, EXT_PLAYERSTATS_RESP_IDS); //send player ids following if(ci) putint(q, ci->clientnum); else loopv(clients) putint(q, clients[i]->clientnum); sendserverinforeply(q); if(ci) extinfoplayer(p, ci); else loopv(clients) extinfoplayer(p, clients[i]); return; } // case EXT_TEAMSCORE: // { // extinfoteams(p); // break; // } default: { putint(p, EXT_ERROR); break; } } sendserverinforeply(p); } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/render.cpp0000664000175000017500000002332711442705030023261 0ustar showardshoward#include "game.h" #include "extentity.h" namespace game { VARP(ragdoll, 0, 1, 1); VARP(ragdollmillis, 0, 10000, 300000); VARP(ragdollfade, 0, 1000, 300000); VARP(forceplayermodels, 0, 0, 1); VARP(defaultplayermodel, 0, 0, 8); vector ragdolls; void saveragdoll(DynamicEntity *d) { if(!d->ragdoll || !ragdollmillis || !ragdollfade) return; DynamicEntity *r = new DynamicEntity(*d); r->lastupdate = ragdollfade; r->edit = NULL; // r->ai = NULL; // r->attackchan = r->idlechan = -1; // if(d==player1) r->playermodel = playermodel; ragdolls.add(r); d->ragdoll = NULL; } void clearragdolls() { ragdolls.deletecontents(); } void moveragdolls() { loopv(ragdolls) { DynamicEntity *d = ragdolls[i]; if(lastmillis > d->lastupdate + ragdollmillis) { delete ragdolls.remove(i--); continue; } moveragdoll(d); } } void renderplayer(DynamicEntity *d, float fade, bool mainpass) { using namespace Character; CharacterInfo& info = d->getcharinfo(); int playermodel = info.playermodel; PlayerModel::PlayerModelInfo& mdl = PlayerModel:: getPlayerModelInfo(playermodel); const char* name = PlayerModel::GetName(mdl); int lastaction = d->lastaction; int lastpain = -1; bool hold = false; int actiondelay = 300; bool ragdoll = false; //__offtools__: add attachments (clothes) int ai = 0; int num = info.attacheditems.length() + 1; modelattach* attached = new modelattach[num]; loopv(info.attacheditems) { PlayerModel::BuildModelAttach(mdl, info.attacheditems[i], attached[i]); } // if(mainpass) // { // d->muzzle = vec(-1, -1, -1); // a[ai++] = modelattach("tag_muzzle", &d->muzzle); // } int anim = hold ? info.ao[AO_HOLD]|ANIM_LOOP : info.ao[AO_IDLE]|ANIM_LOOP; //if !hold set hold to ANIM_IDLE float yaw = d->yaw+90; float pitch = d->pitch; int basetime = 0; int action = info.dogesture ? -info.ao[AO_GESTURE] : 0; switch(d->state) { case CS_DEAD: { anim = info.ao[AO_DYING]; basetime = lastpain; if(ragdoll) { //if(!d->ragdoll || d->ragdoll->millis < basetime) anim |= ANIM_RAGDOLL; } else { pitch *= max(1.0f - (lastmillis-basetime)/500.0f, 0.0f); if(lastmillis-basetime>1000) anim = info.ao[AO_DEAD]|ANIM_LOOP; } break; } case CS_EDITING: case CS_SPECTATOR: { anim = info.ao[AO_EDIT]|ANIM_LOOP; break; } case CS_LAGGED: { anim = ANIM_LAG|ANIM_LOOP; break; } default: { if(lastmillis-lastpain < 300) { anim = info.ao[AO_PAIN]; basetime = lastpain; } else if(lastpain < lastaction && (action < 0 || (d->type != ENT_AI && lastmillis-lastaction < actiondelay))) { anim = action < 0 ? -action : action; basetime = lastaction; } if(d->inwater && d->physstate<=PHYS_FALL) anim |= (((game::allowmove(d) && (d->move || d->strafe)) || d->vel.z+d->falling.z>0 ? info.ao[AO_SWIM] : info.ao[AO_SINK])|ANIM_LOOP)<timeinair>100) anim |= (info.ao[AO_JUMP]|ANIM_END)<move || d->strafe)) { if(d->move>0) anim |= (info.ao[AO_FORWARD]|ANIM_LOOP)<strafe) anim |= ((d->strafe>0 ? info.ao[AO_LEFT] : info.ao[AO_RIGHT])|ANIM_LOOP)<move<0) anim |= (info.ao[AO_BACKWARD]|ANIM_LOOP)<>ANIM_SECONDARY)&ANIM_INDEX) anim >>= ANIM_SECONDARY; break; } } //remove ragdoll if not needed //if(d->ragdoll && (!ragdoll || anim!=ANIM_DYING)) DELETEP(d->ragdoll); if(!((anim>>ANIM_SECONDARY)&ANIM_INDEX)) anim |= (ANIM_IDLE|ANIM_LOOP)<type==ENT_PLAYER) flags |= MDL_FULLBRIGHT; else flags |= MDL_CULL_DIST; if(d->state==CS_LAGGED) fade = min(fade, 0.3f); else flags |= MDL_DYNSHADOW; rendermodel(NULL, name, anim, d->feetpos(), yaw, pitch, 0, flags, d, attached[0].tag ? attached : NULL, basetime, 0, fade); DELETEA(attached); } void renderentities() { const vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; int revs = 10; switch(e.type) { case TELEPORT: if(e.attr[1] < 0) continue; break; case GENERIC: { float dist = e.o.dist(vec(game::player1->o)); if (dist < e.attr[0]) { particle_splash(PART_STEAM, 80, 200, e.o, 0xBFBFBF, 2, 150, 10); } break; } default: if(!e.spawned) continue; } const char *mdlname = entities::entmodel(e); if(mdlname) { vec p = e.o; p.z += 1+sinf(lastmillis/100.0+e.o.x+e.o.y)/20; rendermodel(&e.light, mdlname, ANIM_MAPMODEL|ANIM_LOOP, p, lastmillis/(float)revs, 0, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED); } } } void rendergame(bool mainpass) { startmodelbatches(); DynamicEntity *exclude = isthirdperson() ? NULL : followingplayer(); loopv(players) { DynamicEntity *d = players[i]; if(d == player1 || d->state==CS_SPECTATOR || d->state==CS_SPAWNING || d == exclude ) continue; renderplayer(d, 1, mainpass); copystring(d->info, colorname(d)); } loopv(ragdolls) { DynamicEntity *d = ragdolls[i]; float fade = 1.0f; if(ragdollmillis && ragdollfade) fade -= clamp(float(lastmillis - (d->lastupdate + max(ragdollmillis - ragdollfade, 0)))/min(ragdollmillis, ragdollfade), 0.0f, 1.0f); renderplayer(d, fade, mainpass); } //if(isthirdperson() && !followingplayer()) renderplayer(player1, getplayermodelinfo(player1), 1, mainpass); if(isthirdperson() && !followingplayer()) renderplayer(player1, 1, mainpass); //if(!followingplayer()) renderplayer(player1, 1, mainpass); rendermovables(); renderentities(); if(cmode) cmode->rendergame(); endmodelbatches(); } VARP(hudgun, 0, 1, 1); VARP(hudgunsway, 0, 1, 1); VARP(chainsawhudgun, 0, 1, 1); VAR(testhudgun, 0, 0, 1); FVAR(swaystep, 1, 35.0f, 100); FVAR(swayside, 0, 0.04f, 1); FVAR(swayup, 0, 0.05f, 1); float swayfade = 0, swayspeed = 0, swaydist = 0; vec swaydir(0, 0, 0); void swayhudgun(int curtime) { DynamicEntity *d = hudplayer(); if(d->state != CS_SPECTATOR) { if(d->physstate >= PHYS_SLOPE) { swayspeed = min(sqrtf(d->vel.x*d->vel.x + d->vel.y*d->vel.y), d->maxspeed); swaydist += swayspeed*curtime/1000.0f; swaydist = fmod(swaydist, 2*swaystep); swayfade = 1; } else if(swayfade > 0) { swaydist += swayspeed*swayfade*curtime/1000.0f; swaydist = fmod(swaydist, 2*swaystep); swayfade -= 0.5f*(curtime*d->maxspeed)/(swaystep*1000.0f); } float k = pow(0.7f, curtime/10.0f); swaydir.mul(k); vec vel(d->vel); vel.add(d->falling); swaydir.add(vec(vel).mul((1-k)/(15*max(vel.magnitude(), d->maxspeed)))); } } dynent guninterp; SVARP(hudgunsdir, ""); void drawhudmodel(DynamicEntity *d, int anim, float speed = 0, int base = 0) {} void drawhudgun() {} void renderavatar() { drawhudgun(); } vec hudgunorigin(int gun, const vec &from, const vec &to, DynamicEntity *d) { if(d->muzzle.x >= 0) return d->muzzle; vec offset(from); if(d!=hudplayer() || isthirdperson()) { vec front, right; vecfromyawpitch(d->yaw, d->pitch, 1, 0, front); offset.add(front.mul(d->radius)); if(d->type!=ENT_AI) { offset.z += (d->aboveeye + d->eyeheight)*0.75f - d->eyeheight; vecfromyawpitch(d->yaw, 0, 0, -1, right); offset.add(right.mul(0.5f*d->radius)); offset.add(front); } return offset; } offset.add(vec(to).sub(from).normalize().mul(2)); if(hudgun) { offset.sub(vec(camup).mul(1.0f)); offset.add(vec(camright).mul(0.8f)); } else offset.sub(vec(camup).mul(0.8f)); return offset; } void preload() { PlayerModel::RegisterModel("uh/chars/man"); // entities::preloadentities(); } } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/mapentities.h0000664000175000017500000000215111442705030023761 0ustar showardshoward#ifndef __MAP_ENTITIES_H__ #define __MAP_ENTITIES_H__ #include "game.h" #include "map.h" namespace MapEntities { // class StaticEntity : public extentity, public MapObject // { // public: // int triggerstate, lasttrigger; // // StaticEntity() : triggerstate(TRIGGER_RESET), lasttrigger(0) {} // ~StaticEntity() {} // // void setuid(int i) { } // int getuid() { return uid; } // }; // extern vector ents; // int getmapuid(extentity &e); // StaticEntity* findmapuid(int uid); // StaticEntity* findmapuid(int uid, int type); // void setmapuid(int i, int uid); // void sendmapuids(bool send); //set flag // bool sendmapuids(); //query flag void putentities(packetbuf &p); //send map entities with uid to server // void initdynlights(); // void adddynlights(); // void renderentlight(StaticEntity &e); //wrapper functions - see entities.h // void delentity(StaticEntity *e); // void delentity(extentity *e); // void clearents(); } #endif // __MAP_ENTITIES_H__ sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/servmode.h0000664000175000017500000000304511442705030023266 0ustar showardshoward/* * server.h * * Created on: 17.12.2009 * Author: offtools */ #ifndef __SERVER_H__ #define __SERVER_H__ #include "modeinfo.h" namespace server { struct clientinfo; struct servmode { virtual ~servmode() {} virtual void entergame(clientinfo *ci) {} virtual void leavegame(clientinfo *ci, bool disconnecting = false) {} virtual void moved(clientinfo *ci, const vec &oldpos, bool oldclip, const vec &newpos, bool newclip) {} virtual bool canspawn(clientinfo *ci, bool connecting = false) { return true; } virtual void spawned(clientinfo *ci) {} virtual int fragvalue(clientinfo *victim, clientinfo *actor) { return 0; } virtual void died(clientinfo *victim, clientinfo *actor) {} virtual bool canchangeteam(clientinfo *ci, const char *oldteam, const char *newteam) { return false; } virtual void changeteam(clientinfo *ci, const char *oldteam, const char *newteam) {} virtual void initclient(clientinfo *ci, packetbuf &p, bool connecting) {} virtual void update() {} virtual void reset(bool empty) {} virtual void intermission() {} virtual bool hidefrags() { return true; } virtual int getteamscore(const char *team) { return 0; } virtual void getteamscores() {} virtual bool extinfoteam(const char *team, ucharbuf &p) { return false; } }; struct defaultservmode : servmode { defaultservmode() {} ~defaultservmode() {} }; } #endif /* __SERVER_H__ */ sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/control.h0000664000175000017500000000544611442705030023131 0ustar showardshoward/* * control.h * * Created on: 13.12.2009 * Author: offtools */ #ifndef __CONTROL_H__ #define __CONTROL_H__ struct DynamicEntity; namespace Control { class Control { //base class of an Control //Controlers provide functions for actors, ai, players ... //Control manipulate, control DynamicEntities (clients) on clientside public: int uid; DynamicEntity* dynent; bool isinit; //if false - waiting for a client Control(); virtual ~Control(); //init client, has dynent (client) now virtual void connect(DynamicEntity* de) = 0; //spawn client virtual void spawn() = 0; //update client virtual void update() = 0; //connect client //virtual void connect() = 0; //disconnect client virtual void disconnect() = 0; //called after client was disconnected from server or by Destructor virtual Control* cleanup() = 0; //check state, only init at the moment bool getstate() { return isinit; } }; ///TODO: should be a Singleton class ControlPlayer : public Control { public: bool k_left, k_right, k_up, k_down; bool k_rise, k_des; bool k_yawleft, k_yawright; bool k_action1, k_action2; ControlPlayer(); ~ControlPlayer(); void connect(DynamicEntity* de); void spawn(); void update(); void disconnect(); Control* cleanup(); //movement & action controls void forward(int down); void backward(int down); void left(int down); void right(int down); void turnleft(int down); void turnright(int down); }; //All remote clients // Bots and Players from other clients class ControlRemote : public Control { public: ControlRemote(); ControlRemote(DynamicEntity* de) : Control() { connect(de); } ~ControlRemote(); void connect(DynamicEntity* de); void spawn(); void update(); void disconnect(); Control* cleanup(); }; class ControlAi : public Control { public: ControlAi(); ~ControlAi() {} void connect(DynamicEntity* de); void spawn(); void update(); void disconnect(); Control* cleanup(); }; class ControlNPC : public Control, public Instance { public: ControlNPC(QueuedCommand& qu); ~ControlNPC(); void connect(DynamicEntity* de); void spawn(); void update(); void disconnect(); Control* cleanup(); }; } #endif /* __CONTROL_H__ */ sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/movable.cpp0000664000175000017500000001505111442705030023422 0ustar showardshoward// movable.cpp: implements physics for inanimate models #include "game.h" #include "extentity.h" extern int physsteps; namespace game { enum { BOXWEIGHT = 25, BARRELHEALTH = 50, BARRELWEIGHT = 25, PLATFORMWEIGHT = 1000, PLATFORMSPEED = 8, EXPLODEDELAY = 200 }; vector teleports; struct movable : dynent { int etype, mapmodel, health, weight, exploding, tag, dir; physent *stacked; vec stackpos; movable(const entity &e) : etype(e.type), mapmodel(e.attr[1]), health(e.type==BARREL ? (e.attr[3] ? e.attr[3] : BARRELHEALTH) : 0), weight(e.type==PLATFORM || e.type==ELEVATOR ? PLATFORMWEIGHT : (e.attr[2] ? e.attr[2] : (e.type==BARREL ? BARRELWEIGHT : BOXWEIGHT))), exploding(0), tag(e.type==PLATFORM || e.type==ELEVATOR ? e.attr[2] : 0), dir(e.type==PLATFORM || e.type==ELEVATOR ? (e.attr[3] < 0 ? -1 : 1) : 0), stacked(NULL), stackpos(0, 0, 0) { state = CS_ALIVE; type = ENT_INANIMATE; yaw = float((e.attr[0]+7)-(e.attr[0]+7)%15); if(e.type==PLATFORM || e.type==ELEVATOR) { maxspeed = e.attr[3] ? fabs(float(e.attr[3])) : PLATFORMSPEED; if(tag) vel = vec(0, 0, 0); else if(e.type==PLATFORM) { vecfromyawpitch(yaw, 0, 1, 0, vel); vel.mul(dir*maxspeed); } else vel = vec(0, 0, dir*maxspeed); } const char *mdlname = mapmodelname(e.attr[1]); if(mdlname) setbbfrommodel(this, mdlname); } void hitpush(int damage, const vec &dir, dynent *actor, int gun) { if(etype!=BOX && etype!=BARREL) return; vec push(dir); push.mul(80*damage/weight); vel.add(push); } void explode(dynent *at) { state = CS_DEAD; exploding = 0; //game::explode(true, (dynent *)at, o, this, guns[GUN_BARREL].damage, GUN_BARREL); } ///TODO: enable explosing by trigger void damaged(int damage, dynent *at, int gun = -1) { if(etype!=BARREL || state!=CS_ALIVE || exploding) return; health -= damage; if(health>0) return; // if(gun==GUN_BARREL) exploding = lastmillis + EXPLODEDELAY; // else explode(at); } void suicide() { state = CS_DEAD; if(etype==BARREL) explode(player1); } }; vector movables; void clearmovables() { if(movables.length()) { cleardynentcache(); movables.deletecontents(); } if(!m_dmsp && !m_classicsp) return; teleports.setsize(0); vector &ents = entities::getents(); loopv(ents) { const entity &e = *ents[i]; if(e.type!=BOX && e.type!=BARREL && e.type!=PLATFORM && e.type!=ELEVATOR) { if(e.type==TELEPORT) teleports.add(i); continue; } movable *m = new movable(e); movables.add(m); m->o = e.o; entinmap(m); updatedynentcache(m); } } void triggerplatform(int tag, int newdir) { newdir = max(-1, min(1, newdir)); loopv(movables) { movable *m = movables[i]; if(m->state!=CS_ALIVE || (m->etype!=PLATFORM && m->etype!=ELEVATOR) || m->tag!=tag) continue; if(!newdir) { if(m->tag) m->vel = vec(0, 0, 0); else m->vel.neg(); } else { if(m->etype==PLATFORM) { vecfromyawpitch(m->yaw, 0, 1, 0, m->vel); m->vel.mul(newdir*m->dir*m->maxspeed); } else m->vel = vec(0, 0, newdir*m->dir*m->maxspeed); } } } ICOMMAND(platform, "ii", (int *tag, int *newdir), triggerplatform(*tag, *newdir)); void stackmovable(movable *d, physent *o) { d->stacked = o; d->stackpos = o->o; } void updatemovables(int curtime) { if(!curtime) return; loopv(movables) { movable *m = movables[i]; if(m->state!=CS_ALIVE) continue; if(m->etype==PLATFORM || m->etype==ELEVATOR) { if(m->vel.iszero()) continue; for(int remaining = curtime; remaining>0;) { int step = min(remaining, 20); remaining -= step; if(!moveplatform(m, vec(m->vel).mul(step/1000.0f))) { if(m->tag) { m->vel = vec(0, 0, 0); break; } else m->vel.neg(); } } } else if(m->exploding && lastmillis >= m->exploding) { m->explode(m); adddecal(DECAL_BURN, m->o, vec(0, 0, 1), RL_DAMRAD/2); } else if(m->maymove() || (m->stacked && (m->stacked->state!=CS_ALIVE || m->stackpos != m->stacked->o))) { if(physsteps > 0) m->stacked = NULL; moveplayer(m, 1, true); } loopvj(teleports) { extentity &e = *entities::getents()[teleports[j]]; if(vec(e.o.x, e.o.y, 0).dist(vec(m->o.x, m->o.y, 0)) <= m->radius && vec(0, 0, e.o.z).dist(vec(0,0, m->o.z - 0.5 * m->eyeheight)) <= 0.5 * m->eyeheight) { loopvk(entities::getents()) {extentity &f = *entities::getents()[k]; if(f.type == TELEDEST && f.attr[1] == e.attr[0]) {m->o = m->newpos = f.o; m->yaw = f.attr[0]; break;}} } } } } void rendermovables() { loopv(movables) { movable &m = *movables[i]; if(m.state!=CS_ALIVE) continue; vec o = m.feetpos(); const char *mdlname = mapmodelname(m.mapmodel); if(!mdlname) continue; rendermodel(NULL, mdlname, ANIM_MAPMODEL|ANIM_LOOP, o, m.yaw, 0, 0, MDL_LIGHT | MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED, &m); } } void suicidemovable(movable *m) { m->suicide(); } void hitmovable(int damage, movable *m, dynent *at, const vec &vel, int gun) { m->hitpush(damage, vel, at, gun); m->damaged(damage, at, gun); } } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/trigger.cpp0000664000175000017500000002645311442705030023450 0ustar showardshoward#include "game.h" #include "extentity.h" //TODO: handle trigger for mp and sp using namespace game; // enum // { // TRIG_COLLIDE = 1<<0, // TRIG_TOGGLE = 1<<1, // TRIG_ONCE = 0<<2, // TRIG_MANY = 1<<2, // TRIG_DISAPPEAR = 1<<3, // TRIG_AUTO_RESET = 1<<4, // TRIG_RUMBLE = 1<<5, // TRIG_LOCKED = 1<<6, // TRIG_ENDSP = 1<<7 // }; // // static const int NUMTRIGGERTYPES = 32; // // static const int triggertypes[NUMTRIGGERTYPES] = // { // 0, // TRIG_ONCE, // 1 // TRIG_RUMBLE, // 2 // TRIG_TOGGLE, // 3 // TRIG_TOGGLE | TRIG_RUMBLE, // 4 // TRIG_MANY, // 5 // TRIG_MANY | TRIG_RUMBLE, // 6 // TRIG_MANY | TRIG_TOGGLE, // 7 // TRIG_MANY | TRIG_TOGGLE | TRIG_RUMBLE, // 8 // TRIG_COLLIDE | TRIG_TOGGLE | TRIG_RUMBLE, // 9 // TRIG_COLLIDE | TRIG_TOGGLE | TRIG_AUTO_RESET | TRIG_RUMBLE, // 10 // TRIG_COLLIDE | TRIG_TOGGLE | TRIG_LOCKED | TRIG_RUMBLE, // 11 // TRIG_DISAPPEAR, // 12 // TRIG_DISAPPEAR | TRIG_RUMBLE, // 13 // TRIG_DISAPPEAR | TRIG_COLLIDE | TRIG_LOCKED, // 14 // 0 /* reserved 15 */, // 0 /* reserved 16 */, // 0 /* reserved 17 */, // 0 /* reserved 18 */, // 0 /* reserved 19 */, // 0 /* reserved 20 */, // 0 /* reserved 21 */, // 0 /* reserved 22 */, // 0 /* reserved 23 */, // 0 /* reserved 24 */, // 0 /* reserved 25 */, // 0 /* reserved 26 */, // 0 /* reserved 27 */, // 0 /* reserved 28 */, // TRIG_DISAPPEAR | TRIG_RUMBLE | TRIG_ENDSP, // 29 // 0 /* reserved 30 */, // 0 /* reserved 31 */, // }; // // #define validtrigger(type) (triggertypes[(type) & (NUMTRIGGERTYPES-1)]!=0) // #define checktriggertype(type, flag) (triggertypes[(type) & (NUMTRIGGERTYPES-1)] & (flag)) // // static inline void setuptriggerflags(MapEntities::StaticEntity &e) // { // e.flags = extentity::F_ANIM; // if(checktriggertype(e.attr[2], TRIG_COLLIDE|TRIG_DISAPPEAR)) e.flags |= extentity::F_NOSHADOW; // if(!checktriggertype(e.attr[2], TRIG_COLLIDE)) e.flags |= extentity::F_NOCOLLIDE; // switch(e.triggerstate) // { // case TRIGGERING: // if(checktriggertype(e.attr[2], TRIG_COLLIDE) && lastmillis-e.lasttrigger >= 500) e.flags |= extentity::F_NOCOLLIDE; // break; // case TRIGGERED: // if(checktriggertype(e.attr[2], TRIG_COLLIDE)) e.flags |= extentity::F_NOCOLLIDE; // break; // case TRIGGER_DISAPPEARED: // e.flags |= extentity::F_NOVIS | extentity::F_NOCOLLIDE; // break; // } // } // void resettriggers() // { // loopv(MapEntities::ents) // { // MapEntities::StaticEntity &e = *MapEntities::ents[i]; // if(e.type != ET_MAPMODEL || !validtrigger(e.attr[2])) continue; // e.triggerstate = TRIGGER_RESET; // e.lasttrigger = 0; // setuptriggerflags(e); // } // } // // void unlocktriggers(int tag, int oldstate = TRIGGER_RESET, int newstate = TRIGGERING) // { // loopv(MapEntities::ents) // { // MapEntities::StaticEntity &e = *MapEntities::ents[i]; // if(e.type != ET_MAPMODEL || !validtrigger(e.attr[2])) continue; // if(e.attr[3] == tag && e.triggerstate == oldstate && checktriggertype(e.attr[2], TRIG_LOCKED)) // { // if(newstate == TRIGGER_RESETTING && checktriggertype(e.attr[2], TRIG_COLLIDE) && overlapsdynent(e.o, e.attr[4] ? e.attr[4] : 20)) continue; // e.triggerstate = newstate; // e.lasttrigger = lastmillis; // if(checktriggertype(e.attr[2], TRIG_RUMBLE)) playsound(S_RUMBLE, &e.o); // } // } // } // // ICOMMAND(trigger, "ii", (int *tag, int *state), // { // if(*state) unlocktriggers(*tag); // else unlocktriggers(*tag, TRIGGERED, TRIGGER_RESETTING); // }); // // VAR(triggerstate, -1, 0, 1); // // void doleveltrigger(int trigger, int state) // { // defformatstring(aliasname)("level_trigger_%d", trigger); // if(identexists(aliasname)) // { // triggerstate = state; // execute(aliasname); // } // } // // void checktriggers() // { // if(player1->state != CS_ALIVE) return; // vec o = player1->feetpos(); // loopv(MapEntities::ents) // { // MapEntities::StaticEntity &e = *MapEntities::ents[i]; // if(e.type != ET_MAPMODEL || !validtrigger(e.attr[2])) continue; // switch(e.triggerstate) // { // case TRIGGERING: // case TRIGGER_RESETTING: // if(lastmillis-e.lasttrigger>=1000) // { // if(e.attr[3]) // { // if(e.triggerstate == TRIGGERING) unlocktriggers(e.attr[3]); // else unlocktriggers(e.attr[3], TRIGGERED, TRIGGER_RESETTING); // } // if(checktriggertype(e.attr[2], TRIG_DISAPPEAR)) e.triggerstate = TRIGGER_DISAPPEARED; // else if(e.triggerstate==TRIGGERING && checktriggertype(e.attr[2], TRIG_TOGGLE)) e.triggerstate = TRIGGERED; // else e.triggerstate = TRIGGER_RESET; // } // setuptriggerflags(e); // break; // case TRIGGER_RESET: // if(e.lasttrigger) // { // if(checktriggertype(e.attr[2], TRIG_AUTO_RESET|TRIG_MANY|TRIG_LOCKED) && e.o.dist(o)-player1->radius>= (e.attr[4] ? e.attr[4] : (checktriggertype(e.attr[2], TRIG_COLLIDE) ? 20 : 12))) // e.lasttrigger = 0; // break; // } // else if(e.o.dist(o)-player1->radius>= (e.attr[4] ? e.attr[4] :(checktriggertype(e.attr[2], TRIG_COLLIDE) ? 20 : 12))) break; // else if(checktriggertype(e.attr[2], TRIG_LOCKED)) // { // if(!e.attr[3]) break; // doleveltrigger(e.attr[3], -1); // e.lasttrigger = lastmillis; // break; // } // e.triggerstate = TRIGGERING; // e.lasttrigger = lastmillis; // setuptriggerflags(e); // if(checktriggertype(e.attr[2], TRIG_RUMBLE)) playsound(S_RUMBLE, &e.o); // //if(checktriggertype(e.attr[2], TRIG_ENDSP)) endsp(false); // if(e.attr[3]) doleveltrigger(e.attr[3], 1); // break; // case TRIGGERED: // if(e.o.dist(o)-player1->radius< (e.attr[4] ? e.attr[4] : (checktriggertype(e.attr[2], TRIG_COLLIDE) ? 20 : 12))) // { // if(e.lasttrigger) break; // } // else if(checktriggertype(e.attr[2], TRIG_AUTO_RESET)) // { // if(lastmillis-e.lasttrigger<6000) break; // } // else if(checktriggertype(e.attr[2], TRIG_MANY)) // { // e.lasttrigger = 0; // break; // } // else break; // if(checktriggertype(e.attr[2], TRIG_COLLIDE) && overlapsdynent(e.o, e.attr[4] ? e.attr[4] : 20)) break; // e.triggerstate = TRIGGER_RESETTING; // e.lasttrigger = lastmillis; // setuptriggerflags(e); // if(checktriggertype(e.attr[2], TRIG_RUMBLE)) playsound(S_RUMBLE, &e.o); //// if(checktriggertype(e.attr[2], TRIG_ENDSP)) endsp(false); // if(e.attr[3]) doleveltrigger(e.attr[3], 0); // break; // } // } // } // void animatemapmodel(const extentity &e, int &anim, int &basetime) // { // const MapEntities::StaticEntity &f = (const MapEntities::StaticEntity &)e; // if(validtrigger(f.attr[2])) switch(f.triggerstate) // { // case TRIGGER_RESET: anim = ANIM_TRIGGER|ANIM_START; break; // case TRIGGERING: anim = ANIM_TRIGGER; basetime = f.lasttrigger; break; // case TRIGGERED: anim = ANIM_TRIGGER|ANIM_END; break; // case TRIGGER_RESETTING: anim = ANIM_TRIGGER|ANIM_REVERSE; basetime = f.lasttrigger; break; // } // } void teleport(int n, DynamicEntity *d) // also used by monsters { int e = -1, tag = entities::getents()[n]->attr[0], beenhere = -1; for(;;) { e = findentity(TELEDEST, e+1); if(e==beenhere || e<0) { conoutf(CON_WARN, "no teleport destination for tag %d", tag); return; } if(beenhere<0) beenhere = e; if(entities::getents()[e]->attr[1]==tag) { d->o = entities::getents()[e]->o; d->yaw = entities::getents()[e]->attr[0]; d->pitch = 0; d->vel = vec(0, 0, 0);//vec(cosf(RAD*(d->yaw-90)), sinf(RAD*(d->yaw-90)), 0); entinmap(d); updatedynentcache(d); // ai::inferwaypoints(d, ents[n]->o, ents[e]->o, 16.f); msgsound(S_TELEPORT, d); break; } } } void trypickup(int n, DynamicEntity *d) { switch(entities::getents()[n]->type) { default: if(d->canpickup(entities::getents()[n]->type)) { addmsg(SV_ITEMPICKUP, "rci", d, n); entities::getents()[n]->spawned = false; // even if someone else gets it first } break; case TELEPORT: { if(d->lastpickup==entities::getents()[n]->type && lastmillis-d->lastpickupmillis<500) break; d->lastpickup = entities::getents()[n]->type; d->lastpickupmillis = lastmillis; teleport(n, d); break; } // case RESPAWNPOINT: // if(d!=player1) break; // if(n==respawnent) break; // respawnent = n; // conoutf(CON_GAMEINFO, "\f2respawn point set!"); // playsound(S_V_RESPAWNPOINT); // break; case JUMPPAD: { if(d->lastpickup==entities::getents()[n]->type && lastmillis-d->lastpickupmillis<300) break; d->lastpickup = entities::getents()[n]->type; d->lastpickupmillis = lastmillis; vec v((int)(char)entities::getents()[n]->attr[2]*10.0f, (int)(char)entities::getents()[n]->attr[1]*10.0f, entities::getents()[n]->attr[0]*12.5f); d->timeinair = 0; // if(d->ai) d->ai->becareful = true; d->falling = vec(0, 0, 0); // d->vel = v; d->vel.z = 0; d->vel.add(v); msgsound(S_JUMPPAD, d); break; } } } void checkitems(DynamicEntity *d) { if(d->state!=CS_ALIVE) return; vec o = d->feetpos(); loopv(entities::getents()) { extentity &e = *entities::getents()[i]; if(e.type==NOTUSED) continue; if(!e.spawned && e.type!=TELEPORT && e.type!=JUMPPAD) continue; float dist = e.o.dist(o); if(dist<(e.type==TELEPORT ? 16 : 12)) trypickup(i, d); } } // void resetspawns() { loopv(entities::getents()) entities::getents()[i]->spawned = false; } // void spawnitems() {} // void setspawn(int i, bool on) // { // if(entities::getents().inrange(i)) entities::getents()[i]->spawned = on; // } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/playermodelinfo.h0000664000175000017500000001201011442705030024623 0ustar showardshoward#ifndef __PLAYERMODELINFO_H__ #define __PLAYERMODELINFO_H__ //#include "cube.h" #include "engine.h" //if you get a fdopen error, comment this and uncomment #include "cube.h" ///////////////////////////////////////////////////////////// // Playermodel Definition ///////////////////////////////////////////////////////////// namespace PlayerModel { ///////////////////////////////////////////////////////// // __offtools__: attachments (items, clothes ...) // following tags should appear in the model config file ///////////////////////////////////////////////////////// enum { ATTACH_HEAD = 0, ATTACH_NECK, ATTACH_LEFTSHOULDER, ATTACH_RIGHTSHOULDER, ATTACH_LEFTARM, ATTACH_RIGHTARM, ATTACH_LEFTFOREARM, ATTACH_RIGHTFOREARM, ATTACH_LEFTHAND, ATTACH_RIGHTHAND, ATTACH_BELLY, ATTACH_HIP, ATTACH_LEFTTHIGH, ATTACH_RIGHTTHIGH, ATTACH_LEFTSHIN, ATTACH_RIGHTSHIN, ATTACH_LEFTFOOT, ATTACH_RIGHTFOOT, ATTACH_ARMOUR, ATTACH_WEAPON, ATTACH_POWERUP, ATTACH_MUZZLE, ATTACH_NUMPARTS }; ////////////////////////////////////////////////////////// //__offtools__: //tag_name, body part name translations used in gui ////////////////////////////////////////////////////////// static const struct attachinfo { const char* part; const char* tag; } taginfo[ATTACH_NUMPARTS] = { { "Head", "tag_head" }, { "Neck", "tag_neck" }, { "LeftShoulder", "tag_lshoulder" }, { "RightShoulder", "tag_rshoulder" }, { "LeftArm", "tag_larm" }, { "RightArm", "tag_rarm" }, { "LeftForearm", "tag_lforearm" }, { "RightForearm", "tag_rforearm" }, { "LeftHand", "tag_lhand" }, { "RightHand", "tag_rhand" }, { "Belly", "tag_belly" }, { "Hip", "tag_hip" }, { "LeftThigh", "tag_lthigh" }, { "RightThigh", "tag_rthigh" }, { "LeftShin", "tag_lshin" }, { "RightShin", "tag_rshin" }, { "LeftFoot", "tag_lfoot" }, { "RightFoot", "tag_rfoot" }, { "Armour", "tag_armour" }, { "Weapon", "tag_weapon" }, { "Powerup", "tag_powerup" }, { "Muzzle", "tag_muzzle" } }; /////////////////////////////////////////////////////////// // offtools: // animation handling of the attachments (not implemented) // // handle animation: // ATTACH_ANIM_NONE - static, no animation // ATTACH_ANIM_IDLE - only use idle animation // ATTACH_ANIM_FULL - use current animation of model // // ao (animation overwrite, e.g. holding a flag) // not implemeted /////////////////////////////////////////////////////////// enum { ATTACH_ANIM_NONE = 0, ATTACH_ANIM_IDLE, ATTACH_ANIM_FULL, ATTACH_ANIM_NUMRULES }; ////////////////////////////////////////////////////////// //__offtools__: //Playermodel Definition ////////////////////////////////////////////////////////// struct PlayerModelInfo { struct animationinfo { int index; string descr; animationinfo(char* s, int num) : index(num) { strcpy(descr, s); } }; struct attachmentinfo { int bodypart; int rule; string model; attachmentinfo(int _part, char* _model, int _rule) : bodypart(_part), rule(_rule) { strcpy(model, _model); } const char* gettag(int bpart) { if(bpart < ATTACH_NUMPARTS || bpart >= 0) { return taginfo[bpart].tag; } else { return NULL; } } const char* getbodypart(int bpart) { if(bpart < ATTACH_NUMPARTS || bpart >= 0) { return taginfo[bpart].part; } else { return NULL; } } }; char* name; bool ragdoll, selectable; vector animinfo; vector iteminfo; PlayerModelInfo(const char* _name); void registeranimation(char *anim, int num); void registeritem( int part, char* model, int rule); bool hasanimation(int anim); char* getname(); }; int RegisterModel(const char *s); void RegisterItem(int playermodel, int part, char* model, int rule); void RegisterAnimation(char *loadname, char* anim, int num); void BuildModelAttach(PlayerModelInfo& pm, int itemnum, modelattach& a); bool HasAnimation(PlayerModelInfo& pm, int anim); const char* GetName(PlayerModelInfo& pm); vector PlayerModels(); PlayerModelInfo& getPlayerModelInfo(int i); } #endif // __PLAYERMODELINFO_H__ sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/botmgr.h0000664000175000017500000001642311442705030022740 0ustar showardshoward// server-side bot manager //changelog: // 20091219 // *removed test on privilege in reqadd // 20091220 // *set ownership always to clients who requested the bot (TODO: make this more flexible for use in addition with ai) //TODO: remove all game type dependent stuff and put it into servmodes namespace botmgr { bool dorefresh = false; VARN(serverbotlimit, botlimit, 0, 8, MAXBOTS); VARN(serverbotbalance, botbalance, 0, 1, 1); static inline bool validbotclient(clientinfo *ci) { return ci->clientnum >= 0 && ci->state.clienttype == CLIENT_PLAYER && (ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege); } clientinfo *findbotclient(clientinfo *exclude = NULL) { clientinfo *least = NULL; loopv(clients) { clientinfo *ci = clients[i]; if(!validbotclient(ci) || ci==exclude) continue; if(!least || ci->bots.length() < least->bots.length()) least = ci; } return least; } bool addbot(clientinfo* rc, int limit) { //TODO: clean up function int numai = 0, cn = -1, maxai = limit >= 0 ? min(limit, MAXBOTS) : MAXBOTS; loopv(bots) //count number of initialized bot { clientinfo *ci = bots[i]; if(!ci || ci->ownernum < 0) { if(cn < 0) cn = i; continue; } numai++; } if(numai >= maxai) return false; //test number of bots against maxbots, exit if limit reached if(bots.inrange(cn)) { clientinfo *ci = bots[cn]; if(ci) { // reuse a slot that was going to removed //clientinfo *owner = findbotclient(); //owner should be client who requested bot //ci->ownernum = owner ? owner->clientnum : -1; ci->ownernum = rc->clientnum; ci->botreinit = 2; dorefresh = true; return true; } } else { cn = bots.length(); bots.add(NULL); } if(!bots[cn]) { bots[cn] = new clientinfo; } clientinfo *ci = bots[cn]; ci->clientnum = MAXCLIENTS + cn; ci->state.clienttype = CLIENT_BOT; //clientinfo *owner = findbotclient(); //ci->ownernum = owner ? owner->clientnum : -1; ci->ownernum = rc->clientnum; if(rc) rc->bots.add(ci); else fatal("non exisitend player requested bot"); clients.add(ci); ci->state.lasttimeplayed = lastmillis; ci->state.state = CS_DEAD; ci->playermodel = 0; ci->botreinit = 2; ci->connected = true; dorefresh = true; return true; } void deletebot(clientinfo *ci) { int cn = ci->clientnum - MAXCLIENTS; if(!bots.inrange(cn)) return; if(smode) smode->leavegame(ci, true); sendf(-1, 1, "ri2", SV_CDIS, ci->clientnum); clientinfo *owner = (clientinfo *)getclientinfo(ci->ownernum); if(owner) owner->bots.removeobj(ci); clients.removeobj(ci); DELETEP(bots[cn]); dorefresh = true; } bool deletebot() { loopvrev(bots) if(bots[i] && bots[i]->ownernum >= 0) { deletebot(bots[i]); return true; } return false; } void reinitbot(clientinfo *ci) { if(ci->ownernum < 0) deletebot(ci); else if(ci->botreinit >= 1) { // defformatstring(dbg)("DEBUG: botmgr::reinitbot send SV_INITBOT cl: %d on: %d, clienttype: %d, ", ci->clientnum, ci->ownernum, ci->state.clienttype); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); sendf(-1, 1, "ri5", SV_INITBOT, ci->clientnum, ci->ownernum, ci->state.clienttype, ci->playermodel); if(ci->botreinit == 2) { ci->reassign(); if(ci->state.state==CS_ALIVE) { // defformatstring(dbg)("DEBUG: botmgr::reinitbot sendresume cl: %d on: %d, clienttype: %d", ci->clientnum, ci->ownernum, ci->state.clienttype); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); sendspawn(ci); } else { // defformatstring(dbg)("DEBUG: botmgr::reinitbot sendresume cl: %d on: %d, clienttype: %d", ci->clientnum, ci->ownernum, ci->state.clienttype); // sendf(-1, 1, "ris", SV_SERVMSG, dbg); sendresume(ci); } } ci->botreinit = 0; } } void shiftbot(clientinfo *ci, clientinfo *owner) { clientinfo *prevowner = (clientinfo *)getclientinfo(ci->ownernum); if(prevowner) prevowner->bots.removeobj(ci); if(!owner) { ci->botreinit = 0; ci->ownernum = -1; } else { ci->botreinit = 2; ci->ownernum = owner->clientnum; owner->bots.add(ci); } dorefresh = true; } void removebot(clientinfo *ci) { // either schedules a removal, or someone else to assign to loopvrev(ci->bots) shiftbot(ci->bots[i], findbotclient(ci)); } bool reassignbot() { clientinfo *hi = NULL, *lo = NULL; loopv(clients) { clientinfo *ci = clients[i]; if(!validbotclient(ci)) continue; if(!lo || ci->bots.length() < lo->bots.length()) lo = ci; if(!hi || ci->bots.length() > hi->bots.length()) hi = ci; } if(hi && lo && hi->bots.length() - lo->bots.length() > 1) { loopvrev(hi->bots) { shiftbot(hi->bots[i], lo); return true; } } return false; } void checksetup() { // if(m_teammode && botbalance) balanceteams(); loopvrev(bots) if(bots[i]) reinitbot(bots[i]); } void clearbot() { // clear and remove all ai immediately loopvrev(bots) if(bots[i]) deletebot(bots[i]); } void checkbot() { if(!dorefresh) return; dorefresh = false; if(m_botmode && numclients(-1, false, true)) { checksetup(); while(reassignbot()); } else clearbot(); } void reqadd(clientinfo *ci) { // if(!ci->local && !ci->privilege) { // return; // } if(!addbot(ci, !ci->local && ci->privilege < PRIV_ADMIN ? botlimit : -1)) sendf(ci->clientnum, 1, "ris", SV_SERVMSG, "failed to create or assign bot"); } void reqdel(clientinfo *ci) { if(!ci->local && !ci->privilege) return; if(!deletebot()) sendf(ci->clientnum, 1, "ris", SV_SERVMSG, "failed to remove any bots"); } void setbotlimit(clientinfo *ci, int limit) { if(ci && !ci->local && ci->privilege < PRIV_ADMIN) return; botlimit = clamp(limit, 0, MAXBOTS); dorefresh = true; defformatstring(msg)("bot limit is now %d", botlimit); sendservmsg(msg); } void setbotbalance(clientinfo *ci, bool balance) { // if(ci && !ci->local && !ci->privilege) return; // botbalance = balance ? 1 : 0; // dorefresh = true; // defformatstring(msg)("bot team balancing is now %s", botbalance ? "enabled" : "disabled"); // sendservmsg(msg); } void changemap() { dorefresh = true; loopv(clients) if(clients[i]->local || clients[i]->privilege) return; // if(!botbalance) setbotbalance(NULL, true); } void addclient(clientinfo *ci) { if(ci->state.clienttype == CLIENT_PLAYER) dorefresh = true; } void changeteam(clientinfo *ci) { if(ci->state.clienttype == CLIENT_PLAYER) dorefresh = true; } } sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/modeinfo.h0000664000175000017500000000457011442705030023246 0ustar showardshoward/* * modeinfo.h * * Created on: 18.12.2009 * Author: tha */ //TODO: // *add trigger flag // *add new slowmo mode #ifndef __MODEINFO_H__ #define __MODEINFO_H__ //Mode Flags - features used that came with engine or moviecube enum { M_BOTS = 1<<0, M_CAMERA = 1<<1, M_TRIGGER = 1<<2, M_OVERTIME = 1<<3, M_EDIT = 1<<4, M_LOCAL = 1<<5, M_LOBBY = 1<<6, M_DEMO = 1<<7, M_TEAM = 1<<8, M_NOITEMS = 1<<9, M_NOAMMO = 1<<10, M_DMSP = 1<<11, M_CLASSICSP = 1<<12, M_SLOWMO = 1<<13 }; static struct gamemodeinfo { const char *name; int flags; const char *info; } gamemodes[] = { { "lobby", M_LOBBY, "Run around freely, just visit the map"}, { "movie", M_BOTS | M_CAMERA, "Spawn Characters and use Cameras to shot your movie" }, { "coop edit", M_EDIT | M_BOTS | M_CAMERA, "Edit cooperatively with friends over the LAN or internet" }, { "demo", M_DEMO | M_LOCAL, "playback recorded demos" }, }; #define STARTGAMEMODE (1) #define NUMGAMEMODES ((int)(sizeof(gamemodes)/sizeof(gamemodes[0]))) #define m_valid(mode) ((mode) >= STARTGAMEMODE && (mode) < STARTGAMEMODE + NUMGAMEMODES) #define m_check(mode, flag) (m_valid(mode) && gamemodes[(mode) - STARTGAMEMODE].flags&(flag)) #define m_checknot(mode, flag) (m_valid(mode) && !(gamemodes[(mode) - STARTGAMEMODE].flags&(flag))) #define m_checkall(mode, flag) (m_valid(mode) && (gamemodes[(mode) - STARTGAMEMODE].flags&(flag)) == (flag)) #define m_noitems (m_check(gamemode, M_NOITEMS)) #define m_noammo (m_check(gamemode, M_NOAMMO|M_NOITEMS)) #define m_teammode (m_check(gamemode, M_TEAM)) #define m_overtime (m_check(gamemode, M_OVERTIME)) #define isteam(a,b) (m_teammode && strcmp(a, b)==0) #define m_demo (m_check(gamemode, M_DEMO)) #define m_edit (m_check(gamemode, M_EDIT)) #define m_lobby (m_check(gamemode, M_LOBBY)) #define m_timed (m_checknot(gamemode, M_DEMO|M_EDIT|M_LOCAL|M_LOBBY)) #define m_botmode (m_checknot(gamemode, M_DEMO|M_LOCAL)) #define m_mp(mode) (m_checknot(mode, M_LOCAL)) #define m_sp (m_check(gamemode, M_DMSP | M_CLASSICSP)) #define m_dmsp (m_check(gamemode, M_DMSP)) #define m_classicsp (m_check(gamemode, M_CLASSICSP)) #endif /* __MODEINFO_H__ */ sandboxgamemaker-2.7.1+dfsg/src/moviecube_exp/action.h0000664000175000017500000000055211442705030022717 0ustar showardshoward#ifndef ACTION_H_INCLUDED #define ACTION_H_INCLUDED #include "game.h" #include "control.h" class ActionMove : Action { public: ActionMove(extentity& wp); ~ActionMove(); bool checktype(); bool process(); private: Control::ControlNPC& instance; extentity& ent; vec dst; Control::ControlNPC& gettype(); }; #endif // ACTION_H_INCLUDED sandboxgamemaker-2.7.1+dfsg/src/qtlaunch/0000775000175000017500000000000011660234752020266 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/qtlaunch/mainwindow.cpp0000664000175000017500000000526011442705030023137 0ustar showardshoward#include "launcher.h" void mainwindow::aboutqt() { QApplication::aboutQt(); } void mainwindow::aboutus() { About->show(); } void mainwindow::reset() { IO::reset(); refreshWidgets(); } void mainwindow::quit() { QApplication::closeAllWindows(); } void mainwindow::run() { //only allow one instance at a time if(Executable->state() == QProcess::NotRunning) { QString exe = "bin/sandbox_"; #ifdef Q_OS_LINUX exe += "client_32_"; //TODO detect 64bit unix/linux #endif exe += Games->currentText(); #ifdef Q_OS_WIN exe += ".exe"; #endif IO::writeCfg(); QStringList args; if(homedir.path() != "") args << QString("-q" + QDir::toNativeSeparators(homedir.path())); args << "-r"; loopv(i, packagedirs) { args << QString("-k" + QDir::toNativeSeparators(packagedirs[i])); } Executable->setStandardOutputFile("stdout.txt"); Executable->setStandardErrorFile("stderror.txt"); Executable->start(exe, args); } } //This is executed when sandbox quits/crashes/whatever void mainwindow::closed() { IO::readCfg(); refreshWidgets(); } void mainwindow::refreshWidgets() { } void mainwindow::createWidgets() { QGridLayout *window = new QGridLayout(this); window->setMargin(0); /** The Toolbar */ { FileMenu = new QMenu("File", this); Reset = FileMenu->addAction("Reset"); Reset->setMenuRole(QAction::ApplicationSpecificRole); connect(Reset, SIGNAL(triggered()), this, SLOT(reset())); FileMenu->addSeparator(); Quit = FileMenu->addAction("Exit"); Quit->setMenuRole(QAction::QuitRole); connect(Quit, SIGNAL(triggered()), this, SLOT(quit())); AboutMenu = new QMenu("About", this); AboutQt = AboutMenu->addAction("About Qt"); AboutQt->setMenuRole(QAction::AboutQtRole); connect(AboutQt, SIGNAL(triggered()), this, SLOT(aboutqt())); AboutUs = AboutMenu->addAction("About Sandbox"); AboutUs->setMenuRole(QAction::AboutRole); connect(AboutUs, SIGNAL(triggered()), this, SLOT(aboutus())); Menu = new QMenuBar(this); Menu->addMenu(FileMenu); Menu->addMenu(AboutMenu); window->addWidget(Menu, 0, 0, 1, 2); } /** Stuff to select the game and launch it and select the map */ { QGridLayout *launch = new QGridLayout(); window->addLayout(launch, 1, 0, 2, 1); QStringList GameList; GameList << "fps" << "krs" << "movie" << "rpg" << "ssp"; Games = new QComboBox(this); Games->addItems(GameList); launch->addWidget(Games, 0, 0); Executable = new QProcess(this); connect(Executable, SIGNAL(finished(int)), this, SLOT(closed())); Launch = new QPushButton("Launch", this); connect(Launch, SIGNAL(released()), this, SLOT(run())); launch->addWidget(Launch, 1, 0); } /** */ /** */ //setLayout(window); } sandboxgamemaker-2.7.1+dfsg/src/qtlaunch/launcher.h0000664000175000017500000000322711442705030022232 0ustar showardshoward#include #define loop(v, c) for(int v = 0; v < (c); v++) #define looprev(v, c) for(int v = (c) - 1; v >= 0; v--) #define loopv(v, c) for(int v = 0; v < (c).count(); v++) #define loopvrev(v, c) for(int v = (c).count() - 1; v >= 0; v--) class aboutwindow : public QWidget { Q_OBJECT public: aboutwindow(); ~aboutwindow() {} private: //Logo? //Info private slots: //close }; extern aboutwindow *About; class mainwindow : public QWidget { Q_OBJECT public: mainwindow() {} ~mainwindow() {} void createWidgets(); void refreshWidgets(); private: //The Toolbar QMenuBar *Menu; QMenu *FileMenu; QAction *Reset, *Quit; QMenu *AboutMenu; QAction *AboutQt, *AboutUs; //Widgets for selecting and launching the game QComboBox *Games; QProcess *Executable; QPushButton *Launch; //Widgets for modifying init.cfg //Widgets for playing around with packagedirs private slots: void reset(); void quit(); void aboutqt(); void aboutus(); void run(); void closed(); //commitpackagedir //deletepackagedir //run //quit }; enum { VAR_FULLSCREEN = 0, VAR_SCRW, VAR_SCRH, VAR_COLOURB, VAR_DEPTHB, VAR_STENCILB, VAR_FSAA, VAR_VSYNC, VAR_SHADERS, VAR_SPRECISION, VAR_GLSL, VAR_SCHAN, VAR_SFREQ, VAR_SBUFLEN, VAR_MAX }; extern QDir homedir; extern QStringList packagedirs; extern QByteArray variables[]; namespace IO { extern void reset(); //reads and writes binary dat file which saves the current homedir, lastmap and loaded packagedirs extern void readDat(); extern void writeDat(); //reads and writes init.cfg; this depends on it being valid extern void readCfg(); extern void writeCfg(); }sandboxgamemaker-2.7.1+dfsg/src/qtlaunch/main.cpp0000664000175000017500000000057511442705030021713 0ustar showardshoward#include "launcher.h" aboutwindow *About; int main(int argc, char **argv) { QApplication app(argc, argv); IO::reset(); IO::readDat(); IO::readCfg(); mainwindow window; window.createWidgets(); window.setWindowTitle("Platinum Arts Sandbox - Launcher"); window.show(); About = new aboutwindow(); int ret = app.exec(); IO::writeCfg(); IO::writeDat(); return ret; }sandboxgamemaker-2.7.1+dfsg/src/qtlaunch/aboutwindow.cpp0000664000175000017500000000014611442705030023323 0ustar showardshoward#include "launcher.h" aboutwindow::aboutwindow() { setWindowTitle("About Platinum Arts Sandbox"); } sandboxgamemaker-2.7.1+dfsg/src/qtlaunch/io.cpp0000664000175000017500000000577211500012604021373 0ustar showardshoward#include "launcher.h" QDir homedir; QStringList packagedirs; QByteArray variables[VAR_MAX]; const char *varnames[] = { "fullscreen", "1", "scr_w", "1024", "scr_h", "768", "colorbits", "0", "depthbits", "0", "stencilbits", "0", "fsaa", "0", "vsync", "1", "shaders", "1", "shaderprecision", "0", "forceglsl", "0", "soundchans", "32", "soundfreq", "22050", "soundbufferlen", "1024", }; namespace IO { void reset() { #ifdef Q_OS_WIN // works with WIN64 too homedir.setPath("."); if(!homedir.exists(QString("my_stuff"))) homedir.mkdir(QString("my_stuff")); homedir.cd(QString("my_stuff")); #elif Q_OS_DARWIN //FIXME //homedir #else //linux :3 homedir.setPath(QDir::homePath()); if(!homedir.exists(QString(".platinumarts"))) homedir.mkdir(QString(".platinumarts")); homedir.cd(QString(".platinumarts")); #endif packagedirs.clear(); loop(i, VAR_MAX) variables[i] = varnames[i*2 + 1]; } QFile *openfile(QString file, bool write) { if(write) return new QFile(homedir.filePath(file)); if(homedir.exists(file)) return new QFile(homedir.filePath(file)); QDir tmp; loopv(i, packagedirs) { tmp.setPath(packagedirs[i]); if(tmp.exists(file)) return new QFile(tmp.filePath(file)); } tmp.setPath(QDir::currentPath()); if(tmp.exists(file)) return new QFile(tmp.filePath(file)); return NULL; } void refreshSearchPaths() { } void setHomedir() {} void addPackagedir() {} void removePackagedir() {} void readDat() { QFile dat("launcher.dat"); dat.open(QIODevice::ReadOnly); if(!dat.isOpen()) return; homedir.setPath(dat.readLine()); while(!dat.atEnd()) packagedirs << dat.readLine(); dat.close(); refreshSearchPaths(); } void writeDat() { QFile dat("launcher.dat"); dat.open(QIODevice::WriteOnly|QIODevice::Text); dat.write(homedir.path().toAscii()); loopv(i, packagedirs) { dat.putChar('\n'); dat.write(packagedirs[i].toAscii()); } dat.close(); } void readCfg() { QFile *init = openfile("init.cfg", false); init->open(QIODevice::ReadOnly|QIODevice::Text); //we assume that the file is unmodified - mostly while(!init->atEnd()) { QByteArray buf = init->readLine(); buf = buf.simplified(); if(buf[0] == '/' && buf[1] == '/') continue; int var = -1; loop(i, VAR_MAX) { if(buf.startsWith(varnames[2 * i])) { var = i; break; } } if(var != -1) { variables[var] = buf.right(buf.count() - QByteArray(varnames[2 * var]).count() ); } } init->close(); delete init; } void writeCfg() { QFile *init = openfile("init.cfg", true); init->open(QIODevice::WriteOnly|QIODevice::Text); init->write("//This file was generated by the Sandbox Launcher\n//Do not modify this file unless you know what you're doing\n//Modify settigns in game or via the launcher\n\n"); loop(i, VAR_MAX) { init->write(varnames[i * 2]); init->putChar('\t'); init->write(variables[i]); init->putChar('\n'); } init->close(); delete init; } }sandboxgamemaker-2.7.1+dfsg/src/qtlaunch/readme0000664000175000017500000000052111442705030021432 0ustar showardshowardTo compile, you will require the Qt development files execute the following command to create the makefile qmake -project . && qmake -makefile *.pro To compile the launcher, type make To run it after compilation ./qtlaunch NOTE that it must be run form the root sandbox directory, as it looks for the sandbox binaries in ./bin/sandboxgamemaker-2.7.1+dfsg/src/engine/0000775000175000017500000000000011660234726017715 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/engine/texture.h0000664000175000017500000005420211544613352021566 0ustar showardshoward// GL_ARB_vertex_program, GL_ARB_fragment_program extern PFNGLGENPROGRAMSARBPROC glGenPrograms_; extern PFNGLDELETEPROGRAMSARBPROC glDeletePrograms_; extern PFNGLBINDPROGRAMARBPROC glBindProgram_; extern PFNGLPROGRAMSTRINGARBPROC glProgramString_; extern PFNGLGETPROGRAMIVARBPROC glGetProgramiv_; extern PFNGLPROGRAMENVPARAMETER4FARBPROC glProgramEnvParameter4f_; extern PFNGLPROGRAMENVPARAMETER4FVARBPROC glProgramEnvParameter4fv_; extern PFNGLENABLEVERTEXATTRIBARRAYARBPROC glEnableVertexAttribArray_; extern PFNGLDISABLEVERTEXATTRIBARRAYARBPROC glDisableVertexAttribArray_; extern PFNGLVERTEXATTRIBPOINTERARBPROC glVertexAttribPointer_; // GL_EXT_gpu_program_parameters #ifndef GL_EXT_gpu_program_parameters #define GL_EXT_gpu_program_parameters 1 typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params); typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params); #endif extern PFNGLPROGRAMENVPARAMETERS4FVEXTPROC glProgramEnvParameters4fv_; extern PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC glProgramLocalParameters4fv_; // GL_ARB_shading_language_100, GL_ARB_shader_objects, GL_ARB_fragment_shader, GL_ARB_vertex_shader extern PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObject_; extern PFNGLDELETEOBJECTARBPROC glDeleteObject_; extern PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObject_; extern PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObject_; extern PFNGLSHADERSOURCEARBPROC glShaderSource_; extern PFNGLCOMPILESHADERARBPROC glCompileShader_; extern PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameteriv_; extern PFNGLATTACHOBJECTARBPROC glAttachObject_; extern PFNGLGETINFOLOGARBPROC glGetInfoLog_; extern PFNGLLINKPROGRAMARBPROC glLinkProgram_; extern PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocation_; extern PFNGLUNIFORM1FARBPROC glUniform1f_; extern PFNGLUNIFORM2FARBPROC glUniform2f_; extern PFNGLUNIFORM3FARBPROC glUniform3f_; extern PFNGLUNIFORM4FARBPROC glUniform4f_; extern PFNGLUNIFORM1FVARBPROC glUniform1fv_; extern PFNGLUNIFORM2FVARBPROC glUniform2fv_; extern PFNGLUNIFORM3FVARBPROC glUniform3fv_; extern PFNGLUNIFORM4FVARBPROC glUniform4fv_; extern PFNGLUNIFORM1IARBPROC glUniform1i_; extern PFNGLBINDATTRIBLOCATIONARBPROC glBindAttribLocation_; extern PFNGLGETACTIVEUNIFORMARBPROC glGetActiveUniform_; #ifndef GL_ARB_uniform_buffer_object #define GL_ARB_uniform_buffer_object 1 #define GL_UNIFORM_BUFFER 0x8A11 #define GL_UNIFORM_BUFFER_BINDING 0x8A28 #define GL_UNIFORM_BUFFER_START 0x8A29 #define GL_UNIFORM_BUFFER_SIZE 0x8A2A #define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B #define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C #define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D #define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E #define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F #define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 #define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 #define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 #define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 #define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 #define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 #define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 #define GL_UNIFORM_TYPE 0x8A37 #define GL_UNIFORM_SIZE 0x8A38 #define GL_UNIFORM_NAME_LENGTH 0x8A39 #define GL_UNIFORM_BLOCK_INDEX 0x8A3A #define GL_UNIFORM_OFFSET 0x8A3B #define GL_UNIFORM_ARRAY_STRIDE 0x8A3C #define GL_UNIFORM_MATRIX_STRIDE 0x8A3D #define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E #define GL_UNIFORM_BLOCK_BINDING 0x8A3F #define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 #define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 #define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 #define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 #define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 #define GL_INVALID_INDEX 0xFFFFFFFFu typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar* *uniformNames, GLuint *uniformIndices); typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName); typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); #endif #ifndef GL_INVALID_INDEX #define GL_INVALID_INDEX 0xFFFFFFFFu #endif #ifndef GL_VERSION_3_0 #define GL_VERSION_3_0 1 typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); #elif GL_GLEXT_VERSION < 43 typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); #endif // GL_ARB_uniform_buffer_object extern PFNGLGETUNIFORMINDICESPROC glGetUniformIndices_; extern PFNGLGETACTIVEUNIFORMSIVPROC glGetActiveUniformsiv_; extern PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex_; extern PFNGLGETACTIVEUNIFORMBLOCKIVPROC glGetActiveUniformBlockiv_; extern PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding_; extern PFNGLBINDBUFFERBASEPROC glBindBufferBase_; extern PFNGLBINDBUFFERRANGEPROC glBindBufferRange_; #ifndef GL_EXT_bindable_uniform #define GL_EXT_bindable_uniform 1 #define GL_MAX_VERTEX_BINDABLE_UNIFORMS_EXT 0x8DE2 #define GL_MAX_FRAGMENT_BINDABLE_UNIFORMS_EXT 0x8DE3 #define GL_MAX_GEOMETRY_BINDABLE_UNIFORMS_EXT 0x8DE4 #define GL_MAX_BINDABLE_UNIFORM_SIZE_EXT 0x8DED #define GL_UNIFORM_BUFFER_EXT 0x8DEE #define GL_UNIFORM_BUFFER_BINDING_EXT 0x8DEF typedef void (APIENTRYP PFNGLUNIFORMBUFFEREXTPROC) (GLuint program, GLint location, GLuint buffer); typedef GLint (APIENTRYP PFNGLGETUNIFORMBUFFERSIZEEXTPROC) (GLuint program, GLint location); typedef GLintptr (APIENTRYP PFNGLGETUNIFORMOFFSETEXTPROC) (GLuint program, GLint location); #endif // GL_EXT_bindable_uniform extern PFNGLUNIFORMBUFFEREXTPROC glUniformBuffer_; extern PFNGLGETUNIFORMBUFFERSIZEEXTPROC glGetUniformBufferSize_; extern PFNGLGETUNIFORMOFFSETEXTPROC glGetUniformOffset_; extern int renderpath; enum { R_FIXEDFUNCTION = 0, R_ASMSHADER, R_GLSLANG, R_ASMGLSLANG }; enum { SHPARAM_LOOKUP = 0, SHPARAM_VERTEX, SHPARAM_PIXEL, SHPARAM_UNIFORM }; #define RESERVEDSHADERPARAMS 16 #define MAXSHADERPARAMS 8 struct ShaderParam { const char *name; int type, index, loc; float val[4]; }; struct LocalShaderParamState : ShaderParam { float curval[4]; GLenum format; LocalShaderParamState() : format(GL_FLOAT_VEC4_ARB) { memset(curval, -1, sizeof(curval)); } LocalShaderParamState(const ShaderParam &p) : ShaderParam(p), format(GL_FLOAT_VEC4_ARB) { memset(curval, -1, sizeof(curval)); } }; struct ShaderParamState { enum { CLEAN = 0, INVALID, DIRTY }; const char *name; float val[4]; bool local; int dirty; ShaderParamState() : name(NULL), local(false), dirty(INVALID) { memset(val, -1, sizeof(val)); } }; enum { SHADER_DEFAULT = 0, SHADER_NORMALSLMS = 1<<0, SHADER_ENVMAP = 1<<1, SHADER_GLSLANG = 1<<2, SHADER_OPTION = 1<<3, SHADER_INVALID = 1<<8, SHADER_DEFERRED = 1<<9 }; #define MAXSHADERDETAIL 3 #define MAXVARIANTROWS 5 extern int shaderdetail; struct Slot; struct VSlot; struct UniformLoc { const char *name, *blockname; int loc, version, binding, stride, offset, size; void *data; UniformLoc(const char *name = NULL, const char *blockname = NULL, int binding = -1, int stride = -1) : name(name), blockname(blockname), loc(-1), version(-1), binding(binding), stride(stride), offset(-1), size(-1), data(NULL) {} }; struct AttribLoc { const char *name; int loc; AttribLoc(const char *name = NULL, int loc = -1) : name(name), loc(loc) {} }; struct Shader { static Shader *lastshader; char *name, *vsstr, *psstr, *defer; int type; GLuint vs, ps; GLhandleARB program, vsobj, psobj; vector defaultparams; Shader *detailshader, *variantshader, *altshader, *fastshader[MAXSHADERDETAIL]; vector variants[MAXVARIANTROWS]; bool standard, forced, used, native; Shader *reusevs, *reuseps; int numextparams; LocalShaderParamState *extparams; uchar *extvertparams, *extpixparams; vector uniformlocs; vector attriblocs; Shader() : name(NULL), vsstr(NULL), psstr(NULL), defer(NULL), type(SHADER_DEFAULT), vs(0), ps(0), program(0), vsobj(0), psobj(0), detailshader(NULL), variantshader(NULL), altshader(NULL), standard(false), forced(false), used(false), native(true), reusevs(NULL), reuseps(NULL), numextparams(0), extparams(NULL), extvertparams(NULL), extpixparams(NULL) { loopi(MAXSHADERDETAIL) fastshader[i] = this; } ~Shader() { DELETEA(name); DELETEA(vsstr); DELETEA(psstr); DELETEA(defer); DELETEA(extparams); DELETEA(extvertparams); extpixparams = NULL; } void fixdetailshader(bool force = true, bool recurse = true); void allocenvparams(Slot *slot = NULL); void flushenvparams(Slot *slot = NULL); void setslotparams(Slot &slot, VSlot &vslot); void bindprograms(); bool hasoption(int row) { if(!detailshader || detailshader->variants[row].empty()) return false; return (detailshader->variants[row][0]->type&SHADER_OPTION)!=0; } void setvariant_(int col, int row, Shader *fallbackshader) { Shader *s = fallbackshader; for(col = min(col, detailshader->variants[row].length()-1); col >= 0; col--) if(!(detailshader->variants[row][col]->type&SHADER_INVALID)) { s = detailshader->variants[row][col]; break; } if(lastshader!=s) s->bindprograms(); } void setvariant(int col, int row, Shader *fallbackshader) { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; setvariant_(col, row, fallbackshader); lastshader->flushenvparams(); } void setvariant(int col, int row) { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; setvariant_(col, row, detailshader); lastshader->flushenvparams(); } void setvariant(int col, int row, Slot &slot, VSlot &vslot, Shader *fallbackshader) { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; setvariant_(col, row, fallbackshader); lastshader->flushenvparams(&slot); lastshader->setslotparams(slot, vslot); } void setvariant(int col, int row, Slot &slot, VSlot &vslot) { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; setvariant_(col, row, detailshader); lastshader->flushenvparams(&slot); lastshader->setslotparams(slot, vslot); } void set_() { if(lastshader!=detailshader) detailshader->bindprograms(); } void set() { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; set_(); lastshader->flushenvparams(); } void set(Slot &slot, VSlot &vslot) { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; set_(); lastshader->flushenvparams(&slot); lastshader->setslotparams(slot, vslot); } bool compile(); void cleanup(bool invalid = false); static int uniformlocversion(); }; #define SETSHADER(name) \ do { \ static Shader *name##shader = NULL; \ if(!name##shader) name##shader = lookupshaderbyname(#name); \ name##shader->set(); \ } while(0) struct ImageData { int w, h, bpp, levels, align, pitch; GLenum compressed; uchar *data; void *owner; void (*freefunc)(void *); ImageData() : data(NULL), owner(NULL), freefunc(NULL) {} ImageData(int nw, int nh, int nbpp, int nlevels = 1, int nalign = 0, GLenum ncompressed = GL_FALSE) { setdata(NULL, nw, nh, nbpp, nlevels, nalign, ncompressed); } ImageData(int nw, int nh, int nbpp, uchar *data) : owner(NULL), freefunc(NULL) { setdata(data, nw, nh, nbpp); } ImageData(SDL_Surface *s) { wrap(s); } ~ImageData() { cleanup(); } void setdata(uchar *ndata, int nw, int nh, int nbpp, int nlevels = 1, int nalign = 0, GLenum ncompressed = GL_FALSE) { w = nw; h = nh; bpp = nbpp; levels = nlevels; align = nalign; pitch = align ? 0 : w*bpp; compressed = ncompressed; data = ndata ? ndata : new uchar[calcsize()]; if(!ndata) { owner = this; freefunc = NULL; } } int calclevelsize(int level) const { return ((max(w>>level, 1)+align-1)/align)*((max(h>>level, 1)+align-1)/align)*bpp; } int calcsize() const { if(!align) return w*h*bpp; int lw = w, lh = h, size = 0; loopi(levels) { if(lw<=0) lw = 1; if(lh<=0) lh = 1; size += ((lw+align-1)/align)*((lh+align-1)/align)*bpp; if(lw*lh==1) break; lw >>= 1; lh >>= 1; } return size; } void disown() { data = NULL; owner = NULL; freefunc = NULL; } void cleanup() { if(owner==this) delete[] data; else if(freefunc) (*freefunc)(owner); disown(); } void replace(ImageData &d) { cleanup(); *this = d; if(owner == &d) owner = this; d.disown(); } void wrap(SDL_Surface *s) { setdata((uchar *)s->pixels, s->w, s->h, s->format->BytesPerPixel); pitch = s->pitch; owner = s; freefunc = (void (*)(void *))SDL_FreeSurface; } }; // management of texture slots // each texture slot can have multiple texture frames, of which currently only the first is used // additional frames can be used for various shaders struct Texture { enum { IMAGE = 0, CUBEMAP = 1, TYPE = 0xFF, STUB = 1<<8, TRANSIENT = 1<<9, COMPRESSED = 1<<10, FLAGS = 0xF0 }; char *name; int type, w, h, xs, ys, bpp, clamp; bool mipmap, canreduce; GLuint id; uchar *alphamask; Texture() : alphamask(NULL) {} }; struct frame { GLuint num; int slot; //solely for cfg generation frame(int _s, GLuint _n) : num(_n), slot(_s) {} }; struct TexAnim { vector frames; int pos; int delay; int lastupdate, pausemillis; bool on; TexAnim(int _s, GLuint _if): pos(0), delay(500), lastupdate(0), pausemillis(0), on(false) { frames.add(frame(_s, _if)); } }; enum { TEX_DIFFUSE = 0, TEX_UNKNOWN, TEX_DECAL, TEX_NORMAL, TEX_GLOW, TEX_SPEC, TEX_DEPTH, TEX_ENVMAP }; enum { VSLOT_SHPARAM = 0, VSLOT_SCALE, VSLOT_ROTATION, VSLOT_OFFSET, VSLOT_SCROLL, VSLOT_LAYER, VSLOT_ALPHA, VSLOT_COLOR, VSLOT_NUM }; struct VSlot { Slot *slot; VSlot *next; int index, changed; vector params; bool linked; float scale; int rotation, xoffset, yoffset; float scrollS, scrollT; int layer; float alphafront, alphaback; vec colorscale; vec glowcolor, pulseglowcolor; float pulseglowspeed; vec envscale; int skipped; VSlot(Slot *slot = NULL, int index = -1) : slot(slot), next(NULL), index(index), changed(0), skipped(0) { reset(); if(slot) addvariant(slot); } void addvariant(Slot *slot); void reset() { params.shrink(0); linked = false; scale = 1; rotation = xoffset = yoffset = 0; scrollS = scrollT = 0; layer = 0; alphafront = 0.5f; alphaback = 0; colorscale = vec(1, 1, 1); glowcolor = vec(1, 1, 1); pulseglowcolor = vec(0, 0, 0); pulseglowspeed = 0; envscale = vec(0, 0, 0); } void cleanup() { linked = false; } }; struct Slot { struct Tex { int type; Texture *t; string name; int combined; }; int index; vector sts; Shader *shader; vector params; VSlot *variants; bool loaded; uint texmask; char *autograss; Texture *grasstex, *thumbnail; char *layermaskname; int layermaskmode; float layermaskscale; ImageData *layermask; bool ffenv; Slot(int index = -1) : index(index), variants(NULL), autograss(NULL), layermaskname(NULL), layermask(NULL) { reset(); } void reset() { sts.shrink(0); shader = NULL; params.shrink(0); loaded = false; texmask = 0; DELETEA(autograss); grasstex = NULL; thumbnail = NULL; DELETEA(layermaskname); layermaskmode = 0; layermaskscale = 1; if(layermask) DELETEP(layermask); ffenv = false; } void cleanup() { loaded = false; grasstex = NULL; thumbnail = NULL; loopv(sts) { Tex &t = sts[i]; t.t = NULL; t.combined = -1; } } }; inline void VSlot::addvariant(Slot *slot) { if(!slot->variants) slot->variants = this; else { VSlot *prev = slot->variants; while(prev->next) prev = prev->next; prev->next = this; } } struct MSlot : Slot, VSlot { MSlot() : VSlot(this) {} void reset() { Slot::reset(); VSlot::reset(); } void cleanup() { Slot::cleanup(); VSlot::cleanup(); } }; struct cubemapside { GLenum target; const char *name; bool flipx, flipy, swapxy; }; extern cubemapside cubemapsides[6]; extern Texture *notexture; extern Shader *defaultshader, *rectshader, *cubemapshader, *notextureshader, *nocolorshader, *foggedshader, *foggednotextureshader, *stdworldshader, *lineshader, *foggedlineshader; extern int reservevpparams, maxvpenvparams, maxvplocalparams, maxfpenvparams, maxfplocalparams, maxvsuniforms, maxfsuniforms; extern Shader *lookupshaderbyname(const char *name); extern Shader *useshaderbyname(const char *name); extern Texture *loadthumbnail(Slot &slot); extern void resetslotshader(); extern void setslotshader(Slot &s); extern void linkslotshader(Slot &s, bool load = true); extern void linkvslotshader(VSlot &s, bool load = true); extern void linkslotshaders(); extern void setenvparamf(const char *name, int type, int index, float x = 0, float y = 0, float z = 0, float w = 0); extern void setenvparamfv(const char *name, int type, int index, const float *v); extern void flushenvparamf(const char *name, int type, int index, float x = 0, float y = 0, float z = 0, float w = 0); extern void flushenvparamfv(const char *name, int type, int index, const float *v); extern void setlocalparamf(const char *name, int type, int index, float x = 0, float y = 0, float z = 0, float w = 0); extern void setlocalparamfv(const char *name, int type, int index, const float *v); extern void invalidateenvparams(int type, int start, int count); extern ShaderParam *findshaderparam(Slot &s, const char *name, int type, int index); extern ShaderParam *findshaderparam(VSlot &s, const char *name, int type, int index); extern const char *getshaderparamname(const char *name); extern int maxtmus, nolights, nowater, nomasks; extern void inittmus(); extern void resettmu(int n); extern void scaletmu(int n, int rgbscale, int alphascale = 0); extern void colortmu(int n, float r = 0, float g = 0, float b = 0, float a = 0); extern void setuptmu(int n, const char *rgbfunc = NULL, const char *alphafunc = NULL); #define MAXDYNLIGHTS 5 #define DYNLIGHTBITS 6 #define DYNLIGHTMASK ((1< slots; extern vector vslots; sandboxgamemaker-2.7.1+dfsg/src/engine/textedit.h0000664000175000017500000005663311655776734021753 0ustar showardshoward struct editline { enum { CHUNKSIZE = 256 }; char *text; int len, maxlen; editline() : text(NULL), len(0), maxlen(0) {} editline(const char *init) : text(NULL), len(0), maxlen(0) { set(init); } bool empty() { return len <= 0; } void clear() { DELETEA(text); len = maxlen = 0; } bool grow(int total, const char *fmt = "", ...) { if(total + 1 <= maxlen) return false; maxlen = (total + CHUNKSIZE) - total%CHUNKSIZE; char *newtext = new char[maxlen]; if(fmt) { va_list args; va_start(args, fmt); _vsnprintf(newtext, maxlen, fmt, args); va_end(args); } DELETEA(text); text = newtext; return true; } void set(const char *str, int slen = -1) { if(slen < 0) { slen = strlen(str); if(!grow(slen, "%s", str)) memcpy(text, str, slen + 1); } else { grow(slen); memcpy(text, str, slen); text[slen] = '\0'; } len = slen; } void prepend(const char *str) { int slen = strlen(str); if(!grow(slen + len, "%s%s", str, text ? text : "")) { memmove(&text[slen], text, len + 1); memcpy(text, str, slen + 1); } len += slen; } void append(const char *str) { int slen = strlen(str); if(!grow(len + slen, "%s%s", text ? text : "", str)) memcpy(&text[len], str, slen + 1); len += slen; } bool read(stream *f, int chop = -1) { if(chop < 0) chop = INT_MAX; else chop++; set(""); while(len + 1 < chop && f->getline(&text[len], min(maxlen, chop) - len)) { len += strlen(&text[len]); if(len > 0 && text[len-1] == '\n') { text[--len] = '\0'; return true; } if(len + 1 >= maxlen && len + 1 < chop) grow(len + CHUNKSIZE, "%s", text); } if(len + 1 >= chop) { char buf[CHUNKSIZE]; while(f->getline(buf, sizeof(buf))) { int blen = strlen(buf); if(blen > 0 && buf[blen-1] == '\n') return true; } } return false; } void del(int start, int count) { if(!text) return; if(start < 0) { count += start; start = 0; } if(count <= 0 || start >= len) return; if(start + count > len) count = len - start - 1; memmove(&text[start], &text[start+count], len + 1 - (start + count)); len -= count; } void chop(int newlen) { if(!text) return; len = clamp(newlen, 0, len); text[len] = '\0'; } void insert(char *str, int start, int count = 0) { if(count <= 0) count = strlen(str); start = clamp(start, 0, len); grow(len + count, "%s", text ? text : ""); memmove(&text[start + count], &text[start], len - start + 1); memcpy(&text[start], str, count); len += count; } void combinelines(vector &src) { if(src.empty()) set(""); else loopv(src) { if(i) append("\n"); if(!i) set(src[i].text, src[i].len); else insert(src[i].text, len, src[i].len); } } }; struct editor { int mode; //editor mode - 1= keep while focused, 2= keep while used in gui, 3= keep forever (i.e. until mode changes) bool active, rendered; const char *name; const char *filename; int cx, cy; // cursor position - ensured to be valid after a region() or currentline() int mx, my; // selection mark, mx=-1 if following cursor - avoid direct access, instead use region() int maxx, maxy; // maxy=-1 if unlimited lines, 1 if single line editor int scrolly; // vertical scroll offset bool linewrap; int pixelwidth; // required for up/down/hit/draw/bounds int pixelheight; // -1 for variable sized, i.e. from bounds() vector lines; // MUST always contain at least one line! editor(const char *name, int mode, const char *initval) : mode(mode), active(true), rendered(false), name(newstring(name)), filename(NULL), cx(0), cy(0), mx(-1), maxx(-1), maxy(-1), scrolly(0), linewrap(false), pixelwidth(-1), pixelheight(-1) { //printf("editor %08x '%s'\n", this, name); lines.add().set(initval ? initval : ""); } ~editor() { //printf("~editor %08x '%s'\n", this, name); DELETEA(name); DELETEA(filename); clear(NULL); } void clear(const char *init = "") { cx = cy = 0; mark(false); loopv(lines) lines[i].clear(); lines.shrink(0); if(init) lines.add().set(init); } void setfile(const char *fname) { DELETEA(filename); if(fname) filename = newstring(fname); } void load() { if(!filename) return; clear(NULL); stream *file = openutf8file(filename, "rb"); if(file) { while(lines.add().read(file, maxx) && (maxy < 0 || lines.length() <= maxy)); lines.pop().clear(); delete file; } if(lines.empty()) lines.add().set(""); } void save() { if(!filename) return; stream *file = openutf8file(filename, "wb"); if(!file) return; loopv(lines) file->putline(lines[i].text); delete file; } void mark(bool enable) { mx = (enable) ? cx : -1; my = cy; } void selectall() { mx = my = INT_MAX; cx = cy = 0; } // constrain results to within buffer - s=start, e=end, return true if a selection range // also ensures that cy is always within lines[] and cx is valid bool region(int &sx, int &sy, int &ex, int &ey) { int n = lines.length(); assert(n != 0); if(cy < 0) cy = 0; else if(cy >= n) cy = n-1; int len = lines[cy].len; if(cx < 0) cx = 0; else if(cx > len) cx = len; if(mx >= 0) { if(my < 0) my = 0; else if(my >= n) my = n-1; len = lines[my].len; if(mx > len) mx = len; } sx = (mx >= 0) ? mx : cx; sy = (mx >= 0) ? my : cy; ex = cx; ey = cy; if(sy > ey) { swap(sy, ey); swap(sx, ex); } else if(sy==ey && sx > ex) swap(sx, ex); return (sx != ex) || (sy != ey); } bool region() { int sx, sy, ex, ey; return region(sx, sy, ex, ey); } // also ensures that cy is always within lines[] and cx is valid editline ¤tline() { int n = lines.length(); assert(n != 0); if(cy < 0) cy = 0; else if(cy >= n) cy = n-1; if(cx < 0) cx = 0; else if(cx > lines[cy].len) cx = lines[cy].len; return lines[cy]; } void copyselectionto(editor *b) { if(b==this) return; b->clear(NULL); int sx, sy, ex, ey; region(sx, sy, ex, ey); loopi(1+ey-sy) { if(b->maxy != -1 && b->lines.length() >= b->maxy) break; int y = sy+i; char *line = lines[y].text; int len = lines[y].len; if(y == sy && y == ey) { line += sx; len = ex - sx; } else if(y == sy) line += sx; else if(y == ey) len = ex; b->lines.add().set(line, len); } if(b->lines.empty()) b->lines.add().set(""); } char *tostring() { int len = 0; loopv(lines) len += lines[i].len + 1; char *str = newstring(len); int offset = 0; loopv(lines) { editline &l = lines[i]; memcpy(&str[offset], l.text, l.len); offset += l.len; str[offset++] = '\n'; } str[offset] = '\0'; return str; } char *selectiontostring() { vector buf; int sx, sy, ex, ey; region(sx, sy, ex, ey); loopi(1+ey-sy) { int y = sy+i; char *line = lines[y].text; int len = lines[y].len; if(y == sy && y == ey) { line += sx; len = ex - sx; } else if(y == sy) line += sx; else if(y == ey) len = ex; buf.put(line, len); buf.add('\n'); } buf.add('\0'); return newstring(buf.getbuf(), buf.length()-1); } void removelines(int start, int count) { loopi(count) lines[start+i].clear(); lines.remove(start, count); } void del() // removes the current selection (if any) { int sx, sy, ex, ey; if(!region(sx, sy, ex, ey)) { mark(false); return; } if(sy == ey) { if(sx == 0 || ex == lines[ey].len) removelines(sy, 1); else lines[sy].del(sx, ex - sx); } else { if(ey > sy+2) { removelines(sy+1, ey-(sy+2)); ey = sy+1; } if(ex == lines[ey].len) removelines(ey, 1); else lines[ey].del(0, ex); if(sx == 0) removelines(sy, 1); else lines[sy].del(sx, lines[sy].len - sx); } if(lines.empty()) lines.add().set(""); mark(false); cx = sx; cy = sy; } void insert(char ch) { del(); editline ¤t = currentline(); if(ch == '\n') { if(maxy == -1 || cy < maxy-1) { editline newline(¤t.text[cx]); current.chop(cx); cy = min(lines.length(), cy+1); lines.insert(cy, newline); } else current.chop(cx); cx = 0; } else { int len = current.len; if(maxx >= 0 && len > maxx-1) len = maxx-1; if(cx <= len) current.insert(&ch, cx++, 1); } } void insert(const char *s) { while(*s) insert(*s++); } void insertallfrom(editor *b) { if(b==this) return; del(); if(b->lines.length() == 1 || maxy == 1) { editline ¤t = currentline(); char *str = b->lines[0].text; int slen = b->lines[0].len; if(maxx >= 0 && b->lines[0].len + cx > maxx) slen = maxx-cx; if(slen > 0) { int len = current.len; if(maxx >= 0 && slen + cx + len > maxx) len = max(0, maxx-(cx+slen)); current.insert(str, cx, slen); cx += slen; } } else { loopv(b->lines) { if(!i) { lines[cy++].append(b->lines[i].text); } else if(i >= b->lines.length()) { cx = b->lines[i].len; lines[cy].prepend(b->lines[i].text); } else if(maxy < 0 || lines.length() < maxy) lines.insert(cy++, editline(b->lines[i].text)); } } } void key(int code, int cooked) { switch(code) { case SDLK_UP: if(linewrap) { int x, y; char *str = currentline().text; text_pos(str, cx+1, x, y, pixelwidth); if(y > 0) { cx = text_visible(str, x, y-FONTH, pixelwidth); break; } } cy--; break; case SDLK_DOWN: if(linewrap) { int x, y, width, height; char *str = currentline().text; text_pos(str, cx, x, y, pixelwidth); text_bounds(str, width, height, pixelwidth); y += FONTH; if(y < height) { cx = text_visible(str, x, y, pixelwidth); break; } } cy++; break; case -4: cy--; break; case -5: cy++; break; case SDLK_PAGEUP: cy-=pixelheight/FONTH; break; case SDLK_PAGEDOWN: cy+=pixelheight/FONTH; break; case SDLK_HOME: cx = cy = 0; break; case SDLK_END: cx = cy = INT_MAX; break; case SDLK_LEFT: cx--; break; case SDLK_RIGHT: cx++; break; case SDLK_DELETE: { del(); editline ¤t = currentline(); if(cx < current.len) current.del(cx, 1); else if(cy < lines.length()-1) { //combine with next line current.append(lines[cy+1].text); removelines(cy+1, 1); } break; } case SDLK_BACKSPACE: { del(); editline ¤t = currentline(); if(cx > 0) current.del(--cx, 1); else if(cy > 0) { //combine with previous line cx = lines[cy-1].len; lines[cy-1].append(current.text); removelines(cy--, 1); } break; } case SDLK_LSHIFT: case SDLK_RSHIFT: break; case SDLK_RETURN: cooked = '\n'; // fall through default: insert(cooked); break; } } void hit(int hitx, int hity, bool dragged) { int maxwidth = linewrap?pixelwidth:-1; int h = 0; for(int i = scrolly; i < lines.length(); i++) { int width, height; text_bounds(lines[i].text, width, height, maxwidth); if(h + height > pixelheight) break; if(hity >= h && hity <= h+height) { int x = text_visible(lines[i].text, hitx, hity-h, maxwidth); if(dragged) { mx = x; my = i; } else { cx = x; cy = i; }; break; } h+=height; } } int limitscrolly() { int maxwidth = linewrap?pixelwidth:-1; int slines = lines.length(); for(int ph = pixelheight; slines > 0 && ph > 0;) { int width, height; text_bounds(lines[slines-1].text, width, height, maxwidth); if(height > ph) break; ph -= height; slines--; } return slines; } void draw(int x, int y, int color, bool hit) { int maxwidth = linewrap?pixelwidth:-1; int sx, sy, ex, ey; bool selection = region(sx, sy, ex, ey); // fix scrolly so that is always on screen if(cy < scrolly) scrolly = cy; else { if(scrolly < 0) scrolly = 0; int h = 0; for(int i = cy; i >= scrolly; i--) { int width, height; text_bounds(lines[i].text, width, height, maxwidth); if(h + height > pixelheight) { scrolly = i+1; break; } h += height; } } if(selection) { // convert from cursor coords into pixel coords int psx, psy, pex, pey; text_pos(lines[sy].text, sx, psx, psy, maxwidth); text_pos(lines[ey].text, ex, pex, pey, maxwidth); int maxy = lines.length(); int h = 0; for(int i = scrolly; i < maxy; i++) { int width, height; text_bounds(lines[i].text, width, height, maxwidth); if(h + height > pixelheight) { maxy = i; break; } if(i == sy) psy += h; if(i == ey) { pey += h; break; } h += height; } maxy--; if(ey >= scrolly && sy <= maxy) { // crop top/bottom within window if(sy < scrolly) { sy = scrolly; psy = 0; psx = 0; } if(ey > maxy) { ey = maxy; pey = pixelheight - FONTH; pex = pixelwidth; } notextureshader->set(); glDisable(GL_TEXTURE_2D); glColor3ub(0xA0, 0x80, 0x80); glBegin(GL_QUADS); if(psy == pey) { glVertex2f(x+psx, y+psy); glVertex2f(x+pex, y+psy); glVertex2f(x+pex, y+pey+FONTH); glVertex2f(x+psx, y+pey+FONTH); } else { glVertex2f(x+psx, y+psy); glVertex2f(x+psx, y+psy+FONTH); glVertex2f(x+pixelwidth, y+psy+FONTH); glVertex2f(x+pixelwidth, y+psy); if(pey-psy > FONTH) { glVertex2f(x, y+psy+FONTH); glVertex2f(x+pixelwidth, y+psy+FONTH); glVertex2f(x+pixelwidth, y+pey); glVertex2f(x, y+pey); } glVertex2f(x, y+pey); glVertex2f(x, y+pey+FONTH); glVertex2f(x+pex, y+pey+FONTH); glVertex2f(x+pex, y+pey); } glEnd(); glEnable(GL_TEXTURE_2D); defaultshader->set(); } } int h = 0; for(int i = scrolly; i < lines.length(); i++) { int width, height; text_bounds(lines[i].text, width, height, maxwidth); if(h + height > pixelheight) break; draw_text(lines[i].text, x, y+h, color>>16, (color>>8)&0xFF, color&0xFF, 0xFF, hit&&(cy==i)?cx:-1, maxwidth); if(linewrap && height > FONTH) // line wrap indicator { notextureshader->set(); glDisable(GL_TEXTURE_2D); glColor3ub(0x80, 0xA0, 0x80); glBegin(GL_TRIANGLE_STRIP); glVertex2f(x, y+h+FONTH); glVertex2f(x, y+h+height); glVertex2f(x-FONTW/2, y+h+FONTH); glVertex2f(x-FONTW/2, y+h+height); glEnd(); glEnable(GL_TEXTURE_2D); defaultshader->set(); } h+=height; } } }; // a 'stack' where the last is the current focused editor static vector editors; static editor *currentfocus() { return editors.length() ? editors.last() : NULL; } static void readyeditors() { loopv(editors) editors[i]->active = (editors[i]->mode==EDITORFOREVER); } static void flusheditors() { loopvrev(editors) if(!editors[i]->active) { editor *e = editors.remove(i); DELETEP(e); } } static editor *useeditor(const char *name, int mode, bool focus, const char *initval = NULL) { loopv(editors) if(strcmp(editors[i]->name, name) == 0) { editor *e = editors[i]; if(focus) { editors.add(e); editors.remove(i); } // re-position as last e->active = true; return e; } editor *e = new editor(name, mode, initval); if(focus) editors.add(e); else editors.insert(0, e); return e; } #ifdef NEWGUI static void focuseditor(editor *e) { editors.removeobj(e); editors.add(e); } static void removeeditor(editor *e) { editors.removeobj(e); DELETEP(e); } #endif #define TEXTCOMMAND(f, s, d, body) ICOMMAND(f, s, d,\ editor *top = currentfocus();\ if(!top) return;\ body\ ) ICOMMAND(textlist, "", (), // @DEBUG return list of all the editors string s = ""; loopv(editors) { if(i > 0) concatstring(s, ", "); concatstring(s, editors[i]->name); } result(s); ); TEXTCOMMAND(textshow, "", (), // @DEBUG return the start of the buffer editline line; line.combinelines(top->lines); result(line.text); line.clear(); ); ICOMMAND(textfocus, "si", (char *name, int *mode), // focus on a (or create a persistent) specific editor, else returns current name if(*name) useeditor(name, *mode<=0 ? EDITORFOREVER : *mode, true); else if(editors.length() > 0) result(editors.last()->name); ); TEXTCOMMAND(textprev, "", (), editors.insert(0, top); editors.pop();); // return to the previous editor TEXTCOMMAND(textmode, "i", (int *m), // (1= keep while focused, 2= keep while used in gui, 3= keep forever (i.e. until mode changes)) topmost editor, return current setting if no args if(*m) top->mode = *m; else { defformatstring(s)("%d", top->mode); result(s); } ); TEXTCOMMAND(textsave, "s", (char *file), // saves the topmost (filename is optional) if(*file) top->setfile(path(file, true)); top->save(); ); TEXTCOMMAND(textload, "s", (char *file), // loads into the topmost editor, returns filename if no args if(*file) { top->setfile(path(file, true)); top->load(); } else if(top->filename) result(top->filename); ); TEXTCOMMAND(textinit, "sss", (char *name, char *file, char *initval), // loads into named editor if no file assigned and editor has been rendered { editor *e = NULL; loopv(editors) if(!strcmp(editors[i]->name, name)) { e = editors[i]; break; } if(e && e->rendered && !e->filename && *file && (e->lines.empty() || (e->lines.length() == 1 && !strcmp(e->lines[0].text, initval)))) { e->setfile(path(file, true)); e->load(); } }); #define PASTEBUFFER "#pastebuffer" TEXTCOMMAND(textcopy, "", (), editor *b = useeditor(PASTEBUFFER, EDITORFOREVER, false); top->copyselectionto(b);); TEXTCOMMAND(textpaste, "", (), editor *b = useeditor(PASTEBUFFER, EDITORFOREVER, false); top->insertallfrom(b);); TEXTCOMMAND(textmark, "i", (int *m), // (1=mark, 2=unmark), return current mark setting if no args if(*m) top->mark(*m==1); else result(top->region() ? "1" : "2"); ); TEXTCOMMAND(textselectall, "", (), top->selectall();); TEXTCOMMAND(textclear, "", (), top->clear();); TEXTCOMMAND(textcurrentline, "", (), result(top->currentline().text);); TEXTCOMMAND(textexec, "i", (int *selected), // execute script commands from the buffer (0=all, 1=selected region only) char *script = *selected ? top->selectiontostring() : top->tostring(); execute(script); delete[] script; ); TEXTCOMMAND(textalias, "is", (int *selected, char* _alias), // save text into alias char *script = *selected ? top->selectiontostring() : top->tostring(); alias(_alias, script); delete[] script; ); sandboxgamemaker-2.7.1+dfsg/src/engine/pvs.cpp0000664000175000017500000012446311615526106021237 0ustar showardshoward#include "engine.h" #include "SDL_thread.h" enum { PVS_HIDE_GEOM = 1<<0, PVS_HIDE_BB = 1<<1 }; struct pvsnode { bvec edges; uchar flags; uint children; }; static vector origpvsnodes; static bool mergepvsnodes(pvsnode &p, pvsnode *children) { loopi(7) if(children[i].flags!=children[7].flags) return false; bvec bbs[4]; loop(x, 2) loop(y, 2) { const bvec &lo = children[octaindex(2, x, y, 0)].edges, &hi = children[octaindex(2, x, y, 1)].edges; if(lo.x!=0xFF && (lo.x&0x11 || lo.y&0x11 || lo.z&0x11)) return false; if(hi.x!=0xFF && (hi.x&0x11 || hi.y&0x11 || hi.z&0x11)) return false; #define MERGEBBS(res, coord, row, col) \ if(lo.coord==0xFF) \ { \ if(hi.coord!=0xFF) \ { \ res.coord = ((hi.coord&~0x11)>>1) + 0x44; \ res.row = hi.row; \ res.col = hi.col; \ } \ } \ else if(hi.coord==0xFF) \ { \ res.coord = (lo.coord&0xEE)>>1; \ res.row = lo.row; \ res.col = lo.col; \ } \ else if(lo.row!=hi.row || lo.col!=hi.col || (lo.coord&0xF0)!=0x80 || (hi.coord&0xF)!=0) return false; \ else \ { \ res.coord = ((lo.coord&~0xF1)>>1) | (((hi.coord&~0x1F)>>1) + 0x40); \ res.row = lo.row; \ res.col = lo.col; \ } bvec &res = bbs[x + 2*y]; MERGEBBS(res, z, x, y); res.x = lo.x; res.y = lo.y; } loop(x, 2) { bvec &lo = bbs[x], &hi = bbs[x+2]; MERGEBBS(lo, y, x, z); } bvec &lo = bbs[0], &hi = bbs[1]; MERGEBBS(p.edges, x, y, z); return true; } static void genpvsnodes(cube *c, int parent = 0, const ivec &co = ivec(0, 0, 0), int size = worldsize/2) { int index = origpvsnodes.length(); loopi(8) { ivec o(i, co.x, co.y, co.z, size); pvsnode &n = origpvsnodes.add(); n.flags = 0; n.children = 0; if(c[i].children || isempty(c[i]) || c[i].material&MAT_ALPHA) memset(n.edges.v, 0xFF, 3); else loopk(3) { uint face = c[i].faces[k]; if(face==F_SOLID) n.edges[k] = 0x80; else { uchar low = max(max(face&0xF, (face>>8)&0xF), max((face>>16)&0xF, (face>>24)&0xF)), high = min(min((face>>4)&0xF, (face>>12)&0xF), min((face>>20)&0xF, (face>>28)&0xF)); if(size<8) { if(low&((8/size)-1)) { low += 8/size - (low&((8/size)-1)); } if(high&((8/size)-1)) high &= ~(8/size-1); } if(low >= high) { memset(n.edges.v, 0xFF, 3); break; } n.edges[k] = low | (high<<4); } } } int branches = 0; loopi(8) if(c[i].children) { ivec o(i, co.x, co.y, co.z, size); genpvsnodes(c[i].children, index+i, o, size>>1); if(origpvsnodes[index+i].children) branches++; } if(!branches && mergepvsnodes(origpvsnodes[parent], &origpvsnodes[index])) origpvsnodes.setsize(index); else origpvsnodes[parent].children = index; } struct shaftplane { float r, c, offset; uchar rnear, cnear, rfar, cfar; }; struct usvec { union { struct { ushort x, y, z; }; ushort v[3]; }; ushort &operator[](int i) { return v[i]; } ushort operator[](int i) const { return v[i]; } ivec toivec() const { return ivec(x, y, z); } }; struct shaftbb { union { ushort v[6]; struct { usvec min, max; }; }; shaftbb() {} shaftbb(const ivec &o, int size) { min.x = o.x; min.y = o.y; min.z = o.z; max.x = o.x + size; max.y = o.y + size; max.z = o.z + size; } shaftbb(const ivec &o, int size, const bvec &edges) { min.x = o.x + (size*(edges.x&0xF))/8; min.y = o.y + (size*(edges.y&0xF))/8; min.z = o.z + (size*(edges.z&0xF))/8; max.x = o.x + (size*(edges.x>>4))/8; max.y = o.y + (size*(edges.y>>4))/8; max.z = o.z + (size*(edges.z>>4))/8; } ushort &operator[](int i) { return v[i]; } ushort operator[](int i) const { return v[i]; } bool contains(const shaftbb &o) const { return min.x<=o.min.x && min.y<=o.min.y && min.z<=o.min.z && max.x>=o.max.x && max.y>=o.max.y && max.z>=o.max.z; } bool outside(const ivec &o, int size) const { return o.x>=max.x || o.y>=max.y || o.z>=max.z || o.x+size<=min.x || o.y+size<=min.y || o.z+size<=min.z; } bool outside(const shaftbb &o) const { return o.min.x>max.x || o.min.y>max.y || o.min.z>max.z || o.max.xmax.x || o.max.y>max.y || o.max.z>max.z; } }; struct shaft { shaftbb bounds; shaftplane planes[8]; int numplanes; shaft(const shaftbb &from, const shaftbb &to) { calcshaft(from, to); } void calcshaft(const shaftbb &from, const shaftbb &to) { uchar match = 0, color = 0; loopi(3) { if(to.min[i] < from.min[i]) { color |= 1< from.min[i]) bounds.min[i] = to.min[i]+1; else { match |= 1< from.max[i]) { color |= 8<>i)^(color>>j))&1) { int r = i%3, c = j%3, d = (r+1)%3; if(d==c) d = (c+1)%3; shaftplane &p = planes[numplanes++]; p.r = from[j] - to[j]; if(i<3 ? p.r >= 0 : p.r < 0) { p.r = -p.r; p.c = from[i] - to[i]; } else p.c = to[i] - from[i]; p.offset = -(from[i]*p.r + from[j]*p.c); p.rnear = p.r >= 0 ? r : 3+r; p.cnear = p.c >= 0 ? c : 3+c; p.rfar = p.r < 0 ? r : 3+r; p.cfar = p.c < 0 ? c : 3+c; } } bool outside(const shaftbb &o) const { if(bounds.outside(o)) return true; for(const shaftplane *p = planes; p < &planes[numplanes]; p++) { if(o[p->rnear]*p->r + o[p->cnear]*p->c + p->offset > 0) return true; } return false; } bool inside(const shaftbb &o) const { if(bounds.notinside(o)) return false; for(const shaftplane *p = planes; p < &planes[numplanes]; p++) { if(o[p->rfar]*p->r + o[p->cfar]*p->c + p->offset > 0) return false; } return true; } }; struct pvsdata { int offset, len; pvsdata() {} pvsdata(int offset, int len) : offset(offset), len(len) {} }; static vector pvsbuf; static inline uint hthash(const pvsdata &k) { uint h = 5381; loopi(k.len) h = ((h<<5)+h)^pvsbuf[k.offset+i]; return h; } static inline bool htcmp(const pvsdata &x, const pvsdata &y) { return x.len==y.len && !memcmp(&pvsbuf[x.offset], &pvsbuf[y.offset], x.len); } static SDL_mutex *pvsmutex = NULL; static hashtable pvscompress; static vector pvs; static SDL_mutex *viewcellmutex = NULL; struct viewcellrequest { int *result; ivec o; int size; }; static vector viewcellrequests; static bool genpvs_canceled = false; static int numviewcells = 0; VAR(maxpvsblocker, 1, 512, 1<<16); VAR(pvsleafsize, 1, 64, 1024); #define MAXWATERPVS 32 static struct { int height; vector matsurfs; } waterplanes[MAXWATERPVS]; static vector waterfalls; uint numwaterplanes = 0; struct pvsworker { pvsworker() : thread(NULL), pvsnodes(new pvsnode[origpvsnodes.length()]) { } ~pvsworker() { delete[] pvsnodes; } SDL_Thread *thread; pvsnode *pvsnodes; shaftbb viewcellbb; pvsnode *levels[32]; int curlevel; ivec origin; void resetlevels() { curlevel = worldscale; levels[curlevel] = &pvsnodes[0]; origin = ivec(0, 0, 0); } int hasvoxel(const ivec &p, int coord, int dir, int ocoord = 0, int odir = 0, int *omin = NULL) { uint diff = (origin.x^p.x)|(origin.y^p.y)|(origin.z^p.z); if(diff >= uint(worldsize)) return 0; diff >>= curlevel; while(diff) { curlevel++; diff >>= 1; } pvsnode *cur = levels[curlevel]; while(cur->children && !(cur->flags&PVS_HIDE_BB)) { cur = &pvsnodes[cur->children]; curlevel--; cur += ((p.z>>(curlevel-2))&4) | ((p.y>>(curlevel-1))&2) | ((p.x>>curlevel)&1); levels[curlevel] = cur; } origin = ivec(p.x&(~0<flags&PVS_HIDE_BB || cur->edges==bvec(0x80, 0x80, 0x80)) { if(omin) { int step = origin[ocoord] + (odir< *omin) *omin = step; } return origin[coord] + (dir<edges.x==0xFF) return 0; ivec bbp(p); bbp.sub(origin); ivec bbmin, bbmax; bbmin.x = ((cur->edges.x&0xF)<edges.x>>4)<= bbmax.x) return 0; bbmin.y = ((cur->edges.y&0xF)<edges.y>>4)<= bbmax.y) return 0; bbmin.z = ((cur->edges.z&0xF)<edges.z>>4)<= bbmax.z) return 0; if(omin) { int step = (odir ? bbmax[ocoord] : bbmin[ocoord]) - bbp[ocoord] + (odir - 1); if(odir ? step < *omin : step > *omin) *omin = step; } return (dir ? bbmax[coord] : bbmin[coord]) - bbp[coord] + (dir - 1); } void hidepvs(pvsnode &p) { if(p.children) { pvsnode *children = &pvsnodes[p.children]; loopi(8) hidepvs(children[i]); p.flags |= PVS_HIDE_BB; return; } p.flags |= PVS_HIDE_BB; if(p.edges.x!=0xFF) p.flags |= PVS_HIDE_GEOM; } void shaftcullpvs(shaft &s, pvsnode &p, const ivec &co = ivec(0, 0, 0), int size = worldsize) { if(p.flags&PVS_HIDE_BB) return; shaftbb bb(co, size); if(s.outside(bb)) return; if(s.inside(bb)) { hidepvs(p); return; } if(p.children) { pvsnode *children = &pvsnodes[p.children]; uchar flags = 0xFF; loopi(8) { ivec o(i, co.x, co.y, co.z, size>>1); shaftcullpvs(s, children[i], o, size>>1); flags &= children[i].flags; } if(flags & PVS_HIDE_BB) p.flags |= PVS_HIDE_BB; return; } if(p.edges.x==0xFF) return; shaftbb geom(co, size, p.edges); if(s.inside(geom)) p.flags |= PVS_HIDE_GEOM; } ringbuf prevblockers; struct cullorder { int index, dist; cullorder() {} cullorder(int index, int dist) : index(index), dist(dist) {} }; void cullpvs(pvsnode &p, const ivec &co = ivec(0, 0, 0), int size = worldsize) { if(p.flags&(PVS_HIDE_BB | PVS_HIDE_GEOM) || genpvs_canceled) return; if(p.children && !(p.flags&PVS_HIDE_BB)) { pvsnode *children = &pvsnodes[p.children]; int csize = size>>1; ivec dmin = ivec(co).add(csize>>1).sub(viewcellbb.min.toivec().add(viewcellbb.max.toivec()).shr(1)), dmax = ivec(dmin).add(csize); dmin.mul(dmin); dmax.mul(dmax); ivec diff = ivec(dmax).sub(dmin); cullorder order[8]; int dir = 0; if(diff.x < 0) { diff.x = -diff.x; dir |= 1; } if(diff.y < 0) { diff.y = -diff.y; dir |= 2; } if(diff.z < 0) { diff.z = -diff.z; dir |= 4; } order[0] = cullorder(0, 0); order[7] = cullorder(7, diff.x + diff.y + diff.z); order[1] = cullorder(1, diff.x); order[2] = cullorder(2, diff.y); order[3] = cullorder(4, diff.z); if(order[2].dist < order[1].dist) swap(order[1], order[2]); if(order[3].dist < order[2].dist) swap(order[2], order[3]); if(order[2].dist < order[1].dist) swap(order[1], order[2]); cullorder dxy(order[1].index|order[2].index, order[1].dist+order[2].dist), dxz(order[1].index|order[3].index, order[1].dist+order[3].dist), dyz(order[2].index|order[3].index, order[2].dist+order[3].dist); int j; for(j = 4; j > 0 && dxy.dist < order[j-1].dist; --j) order[j] = order[j-1]; order[j] = dxy; for(j = 5; j > 0 && dxz.dist < order[j-1].dist; --j) order[j] = order[j-1]; order[j] = dxz; for(j = 6; j > 0 && dyz.dist < order[j-1].dist; --j) order[j] = order[j-1]; order[j] = dyz; loopi(8) { int index = order[i].index^dir; ivec o(index, co.x, co.y, co.z, csize); cullpvs(children[index], o, csize); } if(!(p.flags & PVS_HIDE_BB)) return; } bvec edges = p.children ? bvec(0x80, 0x80, 0x80) : p.edges; if(edges.x==0xFF) return; shaftbb geom(co, size, edges); ivec diff = geom.max.toivec().sub(viewcellbb.min.toivec()).abs(); cullorder order[3] = { cullorder(0, diff.x), cullorder(1, diff.y), cullorder(2, diff.z) }; if(order[1].dist > order[0].dist) swap(order[0], order[1]); if(order[2].dist > order[1].dist) swap(order[1], order[2]); if(order[1].dist > order[0].dist) swap(order[0], order[1]); loopi(6) { int dim = order[i >= 3 ? i-3 : i].index, dc = (i >= 3) != (geom.max[dim] <= viewcellbb.min[dim]) ? 1 : 0, r = R[dim], c = C[dim]; int ccenter = geom.min[c]; if(geom.min[r]==geom.max[r] || geom.min[c]==geom.max[c]) continue; while(ccenter < geom.max[c]) { ivec rmin; rmin[dim] = geom[dim + 3*dc] + (dc ? -1 : 0); rmin[r] = geom.min[r]; rmin[c] = ccenter; ivec rmax = rmin; rmax[r] = geom.max[r] - 1; int rcenter = (rmin[r] + rmax[r])/2; resetlevels(); for(int minstep = -1, maxstep = 1; (minstep || maxstep) && rmax[r] - rmin[r] < maxpvsblocker;) { if(minstep) minstep = hasvoxel(rmin, r, 0); if(maxstep) maxstep = hasvoxel(rmax, r, 1); rmin[r] += minstep; rmax[r] += maxstep; } rmin[r] = rcenter + (rmin[r] - rcenter)/2; rmax[r] = rcenter + (rmax[r] - rcenter)/2; if(rmin[r]>=geom.min[r] && rmax[r]=geom.min[r] && rmax[r]=geom.min[c] && cmax[c]geom.min[r]) emin[r] = geom.min[r]; if(emax[r]= viewcellbb.max[dim] || bb.max[dim] <= viewcellbb.min[dim]) { int ddir = bb.min[dim] >= viewcellbb.max[dim] ? 1 : -1, dval = ddir>0 ? USHRT_MAX-1 : 0, dlimit = maxpvsblocker, numsides = 0; loopj(4) { ivec dmax; int odim = j < 2 ? c : r; if(j&1) { if(bb.max[odim] >= viewcellbb.max[odim]) continue; dmax[odim] = bb.max[odim]-1; } else { if(bb.min[odim] <= viewcellbb.min[odim]) continue; dmax[odim] = bb.min[odim]; } numsides++; dmax[dim] = bb.min[dim]; int stepdim = j < 2 ? r : c, stepstart = bb.min[stepdim], stepend = bb.max[stepdim]; int dstep = ddir; for(; dstep && ddir*(dmax[dim] - (int)bb.min[dim]) < dlimit;) { dmax[dim] += dstep; dstep = ddir > 0 ? INT_MAX : INT_MIN; dmax[stepdim] = stepstart; resetlevels(); for(int step = 1; step && dmax[stepdim] < stepend;) { step = hasvoxel(dmax, stepdim, 1, dim, (ddir+1)/2, &dstep); dmax[stepdim] += step; } if(dmax[stepdim] < stepend) dstep = 0; } dlimit = min(dlimit, ddir*(dmax[dim] - (int)bb.min[dim])); if(!dstep) dmax[dim] -= ddir; if(ddir>0) dval = min(dval, dmax[dim]); else dval = max(dval, dmax[dim]); } if(numsides>0) { if(ddir>0) bb.max[dim] = dval+1; else bb.min[dim] = dval; } //printf("(%d,%d,%d) x %d,%d,%d, side %d, ccenter = %d, origin = (%d,%d,%d), size = %d\n", bb.min.x, bb.min.y, bb.min.z, bb.max.x-bb.min.x, bb.max.y-bb.min.y, bb.max.z-bb.min.z, i, ccenter, co.x, co.y, co.z, size); } bool dup = false; loopvj(prevblockers) { if(prevblockers[j].contains(bb)) { dup = true; break; } } if(!dup) { shaft s(viewcellbb, bb); shaftcullpvs(s, pvsnodes[0]); prevblockers.add(bb); } if(bb.contains(geom)) return; ccenter = cmax[c] + 1; } } } bool compresspvs(pvsnode &p, int size, int threshold) { if(!p.children) return true; if(p.flags&PVS_HIDE_BB) { p.children = 0; return true; } pvsnode *children = &pvsnodes[p.children]; bool canreduce = true; loopi(8) { if(!compresspvs(children[i], size/2, threshold)) canreduce = false; } if(canreduce) { int hide = children[7].flags&PVS_HIDE_BB; loopi(7) if((children[i].flags&PVS_HIDE_BB)!=hide) canreduce = false; if(canreduce) { p.flags = (p.flags & ~PVS_HIDE_BB) | hide; p.children = 0; return true; } } if(size <= threshold) { p.children = 0; return true; } return false; } vector outbuf; bool serializepvs(pvsnode &p, int storage = -1) { if(!p.children) { outbuf.add(0xFF); loopi(8) outbuf.add(p.flags&PVS_HIDE_BB ? 0xFF : 0); return true; } int index = outbuf.length(); pvsnode *children = &pvsnodes[p.children]; int i = 0; uchar leafvalues = 0; if(storage>=0) { for(; i < 8; i++) { pvsnode &child = children[i]; if(child.flags&PVS_HIDE_BB) leafvalues |= 1<255) { outbuf[storage] = 0; return false; } outbuf[storage] = uchar(offset); } outbuf.add(0); loopj(8) outbuf.add(leafvalues&(1< &matsurfs) { if(pvsnodes[0].flags & PVS_HIDE_BB) return true; if(!pvsnodes[0].children) return false; loopv(matsurfs) { materialsurface &m = *matsurfs[i]; ivec bborigin(m.o), bbsize(0, 0, 0); int dim = dimension(m.orient); bbsize[C[dim]] = m.csize; bbsize[R[dim]] = m.rsize; bborigin[dim] -= 2; bbsize[dim] = 2; if(!materialoccluded(pvsnodes[0], vec(0, 0, 0), worldsize/2, bborigin, bbsize)) return false; } return true; } int wateroccluded, waterbytes; void calcpvs(const ivec &co, int size) { loopk(3) { viewcellbb.min[k] = co[k]; viewcellbb.max[k] = co[k]+size; } memcpy(pvsnodes, origpvsnodes.getbuf(), origpvsnodes.length()*sizeof(pvsnode)); prevblockers.clear(); cullpvs(pvsnodes[0]); wateroccluded = 0; loopi(numwaterplanes) { if(waterplanes[i].height < 0) { if(waterfalls.length() && materialoccluded(waterfalls)) wateroccluded |= 1<>(i*8))&0xFF); pvsbuf.put(outbuf.getbuf(), outbuf.length()); int *val = pvscompress.access(key); if(val) pvsbuf.setsize(key.offset); else { val = &pvscompress[key]; *val = pvs.length(); pvs.add(key); } if(pvsmutex) SDL_UnlockMutex(pvsmutex); return *val; } static int run(void *data) { pvsworker *w = (pvsworker *)data; SDL_LockMutex(viewcellmutex); while(viewcellrequests.length()) { viewcellrequest req = viewcellrequests.pop(); SDL_UnlockMutex(viewcellmutex); int result = w->genviewcell(req.o, req.size); SDL_LockMutex(viewcellmutex); *req.result = result; } SDL_UnlockMutex(viewcellmutex); return 0; } }; struct viewcellnode { uchar leafmask; union viewcellchild { int pvs; viewcellnode *node; } children[8]; viewcellnode() : leafmask(0xFF) { loopi(8) children[i].pvs = -1; } ~viewcellnode() { loopi(8) if(!(leafmask&(1< pvsworkers; static volatile bool check_genpvs_progress = false; static Uint32 genpvs_timer(Uint32 interval, void *param) { check_genpvs_progress = true; return interval; } static int totalviewcells = 0; static void show_genpvs_progress(int unique = pvs.length(), int processed = numviewcells) { float bar1 = float(processed) / float(totalviewcells>0 ? totalviewcells : 1); defformatstring(text1)("%.2f%% - %d of %d view cells (%d unique)", bar1 * 100, processed, totalviewcells, unique); renderprogress(bar1, text1); if(interceptkey(SDLK_ESCAPE)) genpvs_canceled = true; check_genpvs_progress = false; } static shaftbb pvsbounds; static void calcpvsbounds() { loopk(3) pvsbounds.min[k] = USHRT_MAX; loopk(3) pvsbounds.max[k] = 0; extern vector valist; loopv(valist) { vtxarray *va = valist[i]; loopk(3) { if(va->geommin[k]>va->geommax[k]) continue; pvsbounds.min[k] = min(pvsbounds.min[k], (ushort)va->geommin[k]); pvsbounds.max[k] = max(pvsbounds.max[k], (ushort)va->geommax[k]); } } } static inline bool isallclip(cube *c) { loopi(8) { cube &h = c[i]; if(h.children ? !isallclip(h.children) : (!isentirelysolid(h) && (h.material&MATF_CLIP)!=MAT_CLIP)) return false; } return true; } static int countviewcells(cube *c, const ivec &co, int size, int threshold) { int count = 0; loopi(8) { ivec o(i, co.x, co.y, co.z, size); if(pvsbounds.outside(o, size)) continue; cube &h = c[i]; if(h.children) { if(size>threshold) { count += countviewcells(h.children, o, size>>1, threshold); continue; } if(isallclip(h.children)) continue; } else if(isentirelysolid(h) || (h.material&MATF_CLIP)==MAT_CLIP) continue; count++; } return count; } static void genviewcells(viewcellnode &p, cube *c, const ivec &co, int size, int threshold) { if(genpvs_canceled) return; loopi(8) { ivec o(i, co.x, co.y, co.z, size); if(pvsbounds.outside(o, size)) continue; cube &h = c[i]; if(h.children) { if(size>threshold) { p.leafmask &= ~(1<>1, threshold); continue; } if(isallclip(h.children)) continue; } else if(isentirelysolid(h) || (h.material&MATF_CLIP)==MAT_CLIP) continue; if(pvsthreads<=1) { if(genpvs_canceled) return; p.children[i].pvs = pvsworkers[0]->genviewcell(o, size); if(check_genpvs_progress) show_genpvs_progress(); } else { viewcellrequest &req = viewcellrequests.add(); req.result = &p.children[i].pvs; req.o = o; req.size = size; } } } static viewcellnode *viewcells = NULL; static int lockedwaterplanes[MAXWATERPVS]; static uchar *curpvs = NULL, *lockedpvs = NULL; static int curwaterpvs = 0, lockedwaterpvs = 0; static inline pvsdata *lookupviewcell(const vec &p) { uint x = uint(floor(p.x)), y = uint(floor(p.y)), z = uint(floor(p.z)); if(!viewcells || (x|y|z)>=uint(worldsize)) return NULL; viewcellnode *vc = viewcells; for(int scale = worldscale-1; scale>=0; scale--) { int i = octastep(x, y, z, scale); if(vc->leafmask&(1<children[i].pvs>=0 ? &pvs[vc->children[i].pvs] : NULL; } vc = vc->children[i].node; } return NULL; } static void lockpvs_(bool lock) { if(lockedpvs) DELETEA(lockedpvs); if(!lock) return; pvsdata *d = lookupviewcell(camera1->o); if(!d) return; int wbytes = d->len%9, len = d->len - wbytes; lockedpvs = new uchar[len]; memcpy(lockedpvs, &pvsbuf[d->offset + wbytes], len); lockedwaterpvs = 0; loopi(wbytes) lockedwaterpvs |= pvsbuf[d->offset + i] << (i*8); loopi(MAXWATERPVS) lockedwaterplanes[i] = waterplanes[i].height; conoutf("locked view cell at %.1f, %.1f, %.1f", camera1->o.x, camera1->o.y, camera1->o.z); } VARF(lockpvs, 0, 0, 1, lockpvs_(lockpvs!=0)); VARN(pvs, usepvs, 0, 1, 1); VARN(waterpvs, usewaterpvs, 0, 1, 1); void setviewcell(const vec &p) { if(!usepvs) curpvs = NULL; else if(lockedpvs) { curpvs = lockedpvs; curwaterpvs = lockedwaterpvs; } else { pvsdata *d = lookupviewcell(p); curpvs = d ? &pvsbuf[d->offset] : NULL; curwaterpvs = 0; if(d) { loopi(d->len%9) curwaterpvs |= *curpvs++ << (i*8); } } if(!usepvs || !usewaterpvs) curwaterpvs = 0; } void clearpvs() { DELETEP(viewcells); pvs.setsize(0); pvsbuf.setsize(0); curpvs = NULL; numwaterplanes = 0; lockpvs = 0; lockpvs_(false); } COMMAND(clearpvs, ""); static void findwaterplanes() { extern vector valist; loopi(MAXWATERPVS) { waterplanes[i].height = -1; waterplanes[i].matsurfs.setsize(0); } waterfalls.setsize(0); numwaterplanes = 0; loopv(valist) { vtxarray *va = valist[i]; loopj(va->matsurfs) { materialsurface &m = va->matbuf[j]; if(m.material!=MAT_WATER || m.orient==O_BOTTOM) continue; if(m.orient!=O_TOP) { waterfalls.add(&m); continue; } loopk(numwaterplanes) if(waterplanes[k].height == m.o.z) { waterplanes[k].matsurfs.add(&m); goto nextmatsurf; } if(numwaterplanes < MAXWATERPVS) { waterplanes[numwaterplanes].height = m.o.z; waterplanes[numwaterplanes].matsurfs.add(&m); numwaterplanes++; } nextmatsurf:; } } if(waterfalls.length() > 0 && numwaterplanes < MAXWATERPVS) numwaterplanes++; } void testpvs(int *vcsize) { lockpvs_(false); uint oldnumwaterplanes = numwaterplanes; int oldwaterplanes[MAXWATERPVS]; loopi(numwaterplanes) oldwaterplanes[i] = waterplanes[i].height; findwaterplanes(); pvsnode &root = origpvsnodes.add(); memset(root.edges.v, 0xFF, 3); root.flags = 0; root.children = 0; genpvsnodes(worldroot); genpvs_canceled = false; check_genpvs_progress = false; int size = *vcsize>0 ? *vcsize : 32; for(int mask = 1; mask < size; mask <<= 1) size &= ~mask; ivec o = camera1->o; o.mask(~(size-1)); pvsworker w; int len; lockedpvs = w.testviewcell(o, size, &lockedwaterpvs, &len); loopi(MAXWATERPVS) lockedwaterplanes[i] = waterplanes[i].height; lockpvs = 1; conoutf("generated test view cell of size %d at %.1f, %.1f, %.1f (%d B)", size, camera1->o.x, camera1->o.y, camera1->o.z, len); origpvsnodes.setsize(0); numwaterplanes = oldnumwaterplanes; loopi(numwaterplanes) waterplanes[i].height = oldwaterplanes[i]; } COMMAND(testpvs, "i"); void genpvs(int *viewcellsize) { if(worldsize > 1<<15) { conoutf(CON_ERROR, "map is too large for PVS"); return; } extern string mname; defformatstring(capt)("Sandbox Engine %s: %s - Generating PVS Data...", version, mname); SDL_WM_SetCaption(capt, NULL); renderbackground("generating PVS (esc to abort)"); genpvs_canceled = false; Uint32 start = SDL_GetTicks(); renderprogress(0, "finding view cells"); clearpvs(); calcpvsbounds(); findwaterplanes(); pvsnode &root = origpvsnodes.add(); memset(root.edges.v, 0xFF, 3); root.flags = 0; root.children = 0; genpvsnodes(worldroot); totalviewcells = countviewcells(worldroot, ivec(0, 0, 0), worldsize>>1, *viewcellsize>0 ? *viewcellsize : 32); numviewcells = 0; genpvs_canceled = false; check_genpvs_progress = false; SDL_TimerID timer = NULL; if(pvsthreads<=1) { pvsworkers.add(new pvsworker); timer = SDL_AddTimer(500, genpvs_timer, NULL); } viewcells = new viewcellnode; genviewcells(*viewcells, worldroot, ivec(0, 0, 0), worldsize>>1, *viewcellsize>0 ? *viewcellsize : 32); if(pvsthreads<=1) { SDL_RemoveTimer(timer); } else { renderprogress(0, "creating threads"); if(!pvsmutex) pvsmutex = SDL_CreateMutex(); if(!viewcellmutex) viewcellmutex = SDL_CreateMutex(); loopi(pvsthreads) { pvsworker *w = pvsworkers.add(new pvsworker); w->thread = SDL_CreateThread(pvsworker::run, w); } show_genpvs_progress(0, 0); while(!genpvs_canceled) { SDL_Delay(500); SDL_LockMutex(viewcellmutex); int unique = pvs.length(), processed = numviewcells, remaining = viewcellrequests.length(); SDL_UnlockMutex(viewcellmutex); show_genpvs_progress(unique, processed); if(!remaining) break; } SDL_LockMutex(viewcellmutex); viewcellrequests.setsize(0); SDL_UnlockMutex(viewcellmutex); loopv(pvsworkers) SDL_WaitThread(pvsworkers[i]->thread, NULL); } pvsworkers.deletecontents(); origpvsnodes.setsize(0); pvscompress.clear(); Uint32 end = SDL_GetTicks(); if(genpvs_canceled) { clearpvs(); conoutf("genpvs aborted"); } else conoutf("generated %d unique view cells totaling %.1f kB and averaging %d B (%.1f seconds)", pvs.length(), pvsbuf.length()/1024.0f, pvsbuf.length()/max(pvs.length(), 1), (end - start) / 1000.0f); game::setwindowcaption(); } COMMAND(genpvs, "i"); void pvsstats() { conoutf("%d unique view cells totaling %.1f kB and averaging %d B", pvs.length(), pvsbuf.length()/1024.0f, pvsbuf.length()/max(pvs.length(), 1)); } COMMAND(pvsstats, ""); static inline bool pvsoccluded(uchar *buf, const ivec &co, int size, const ivec &bborigin, const ivec &bbsize) { uchar leafmask = buf[0]; loopoctabox(co, size, bborigin, bbsize) { ivec o(i, co.x, co.y, co.z, size); if(leafmask&(1<>1, bborigin, bbsize)&~leafvalues)) return false; } else if(!pvsoccluded(buf+9*buf[1+i], o, size>>1, bborigin, bbsize)) return false; } return true; } static inline bool pvsoccluded(uchar *buf, const ivec &bborigin, const ivec &bbsize) { int diff = (bborigin.x^(bborigin.x+bbsize.x)) | (bborigin.y^(bborigin.y+bbsize.y)) | (bborigin.z^(bborigin.z+bbsize.z)); if(diff&~((1<putchar(p.leafmask); loopi(8) { if(p.leafmask&(1<putlil(p.children[i].pvs); else saveviewcells(f, *p.children[i].node); } } void savepvs(stream *f) { uint totallen = pvsbuf.length() | (numwaterplanes>0 ? 0x80000000U : 0); f->putlil(totallen); if(numwaterplanes>0) { f->putlil(numwaterplanes); loopi(numwaterplanes) { f->putlil(waterplanes[i].height); if(waterplanes[i].height < 0) break; } } loopv(pvs) f->putlil(pvs[i].len); f->write(pvsbuf.getbuf(), pvsbuf.length()); saveviewcells(f, *viewcells); } viewcellnode *loadviewcells(stream *f) { viewcellnode *p = new viewcellnode; p->leafmask = f->getchar(); loopi(8) { if(p->leafmask&(1<children[i].pvs = f->getlil(); else p->children[i].node = loadviewcells(f); } return p; } void loadpvs(stream *f, int numpvs) { uint totallen = f->getlil(); if(totallen & 0x80000000U) { totallen &= ~0x80000000U; numwaterplanes = f->getlil(); loopi(numwaterplanes) waterplanes[i].height = f->getlil(); } int offset = 0; loopi(numpvs) { ushort len = f->getlil(); pvs.add(pvsdata(offset, len)); offset += len; } f->read(pvsbuf.reserve(totallen).buf, totallen); pvsbuf.advance(totallen); viewcells = loadviewcells(f); } int getnumviewcells() { return pvs.length(); } sandboxgamemaker-2.7.1+dfsg/src/engine/md3.h0000664000175000017500000001635711460063014020551 0ustar showardshowardstruct md3; struct md3frame { vec bbmin, bbmax, origin; float radius; uchar name[16]; }; struct md3tag { char name[64]; vec pos; float rotation[3][3]; }; struct md3vertex { short vertex[3]; short normal; }; struct md3triangle { int vertexindices[3]; }; struct md3header { char id[4]; int version; char name[64]; int flags; int numframes, numtags, nummeshes, numskins; int ofs_frames, ofs_tags, ofs_meshes, ofs_eof; // offsets }; struct md3meshheader { char id[4]; char name[64]; int flags; int numframes, numshaders, numvertices, numtriangles; int ofs_triangles, ofs_shaders, ofs_uv, ofs_vertices, meshsize; // offsets }; struct md3 : vertmodel, vertloader { md3(const char *name) : vertmodel(name) {} static const char *formatname() { return "md3"; } int type() const { return MDL_MD3; } struct md3meshgroup : vertmeshgroup { bool load(char *path) { stream *f = openfile(path, "rb"); if(!f) return false; md3header header; f->read(&header, sizeof(md3header)); lilswap(&header.version, 1); lilswap(&header.flags, 9); if(strncmp(header.id, "IDP3", 4) != 0 || header.version != 15) // header check { delete f; conoutf("md3: corrupted header"); return false; } name = newstring(path); numframes = header.numframes; int mesh_offset = header.ofs_meshes; loopi(header.nummeshes) { vertmesh &m = *new vertmesh; m.group = this; meshes.add(&m); md3meshheader mheader; f->seek(mesh_offset, SEEK_SET); f->read(&mheader, sizeof(md3meshheader)); lilswap(&mheader.flags, 10); m.name = newstring(mheader.name); m.numtris = mheader.numtriangles; m.tris = new tri[m.numtris]; f->seek(mesh_offset + mheader.ofs_triangles, SEEK_SET); loopj(m.numtris) { md3triangle tri; f->read(&tri, sizeof(md3triangle)); // read the triangles lilswap(tri.vertexindices, 3); loopk(3) m.tris[j].vert[k] = (ushort)tri.vertexindices[k]; } m.numverts = mheader.numvertices; m.tcverts = new tcvert[m.numverts]; f->seek(mesh_offset + mheader.ofs_uv , SEEK_SET); f->read(m.tcverts, m.numverts*2*sizeof(float)); // read the UV data lilswap(&m.tcverts[0].u, 2*m.numverts); m.verts = new vert[numframes*m.numverts]; f->seek(mesh_offset + mheader.ofs_vertices, SEEK_SET); loopj(numframes*m.numverts) { md3vertex v; f->read(&v, sizeof(md3vertex)); // read the vertices lilswap(v.vertex, 4); m.verts[j].pos.x = v.vertex[0]/64.0f; m.verts[j].pos.y = -v.vertex[1]/64.0f; m.verts[j].pos.z = v.vertex[2]/64.0f; float lng = (v.normal&0xFF)*PI2/255.0f; // decode vertex normals float lat = ((v.normal>>8)&0xFF)*PI2/255.0f; m.verts[j].norm.x = cosf(lat)*sinf(lng); m.verts[j].norm.y = -sinf(lat)*sinf(lng); m.verts[j].norm.z = cosf(lng); } mesh_offset += mheader.meshsize; } numtags = header.numtags; if(numtags) { tags = new tag[numframes*numtags]; f->seek(header.ofs_tags, SEEK_SET); md3tag tag; loopi(header.numframes*header.numtags) { f->read(&tag, sizeof(md3tag)); lilswap(&tag.pos.x, 12); if(tag.name[0] && iload(name)) { delete group; return NULL; } return group; } bool loaddefaultparts() { const char *pname = parentdir(loadname); part &mdl = *new part; parts.add(&mdl); mdl.model = this; mdl.index = 0; defformatstring(name1)("packages/models/%s/tris.md3", loadname); mdl.meshes = sharemeshes(path(name1)); if(!mdl.meshes) { defformatstring(name2)("packages/models/%s/tris.md3", pname); // try md3 in parent folder (vert sharing) mdl.meshes = sharemeshes(path(name2)); if(!mdl.meshes) return false; } Texture *tex, *masks; loadskin(loadname, pname, tex, masks); mdl.initskins(tex, masks); if(tex==notexture) conoutf("could not load model skin for %s", name1); return true; } bool load() { if(loaded) return true; formatstring(dir)("packages/models/%s", loadname); defformatstring(cfgname)("packages/models/%s/md3.cfg", loadname); loading = this; identflags &= ~IDF_PERSIST; if(execfile(cfgname, false) && parts.length()) // configured md3, will call the md3* commands below { identflags |= IDF_PERSIST; loading = NULL; loopv(parts) if(!parts[i]->meshes) return false; } else // md3 without configuration, try default tris and skin { identflags |= IDF_PERSIST; loading = NULL; if(!loaddefaultparts()) return false; } scale /= 4; translate.y = -translate.y; parts[0]->translate = translate; loopv(parts) parts[i]->meshes->shared++; preloadshaders(); return loaded = true; } }; vertcommands md3commands; sandboxgamemaker-2.7.1+dfsg/src/engine/scale.h0000664000175000017500000001062011654260372021153 0ustar showardshowardstatic void FUNCNAME(halvetexture)(uchar *src, uint sw, uint sh, uint stride, uchar *dst) { for(uchar *yend = &src[sh*stride]; src < yend;) { for(uchar *xend = &src[stride]; src < xend; src += 2*BPP, dst += BPP) { #define OP(c, n) dst[n] = (uint(src[n]) + uint(src[n+BPP]) + uint(src[stride+n]) + uint(src[stride+n+BPP]))>>2 PIXELOP #undef OP } src += stride; } } static void FUNCNAME(shifttexture)(uchar *src, uint sw, uint sh, uint stride, uchar *dst, uint dw, uint dh) { uint wfrac = sw/dw, hfrac = sh/dh, wshift = 0, hshift = 0; while(dw<>tshift PIXELOP #undef OP } src += (hfrac-1)*stride; } } static void FUNCNAME(scaletexture)(uchar *src, uint sw, uint sh, uint stride, uchar *dst, uint dw, uint dh) { uint wfrac = (sw<<12)/dw, hfrac = (sh<<12)/dh, darea = dw*dh, sarea = sw*sh; int over, under; for(over = 0; (darea>>over) > sarea; over++); for(under = 0; (darea<>12, h = (yn>>12) - yi, ylow = ((yn|(-int(h)>>24))&0xFFFU) + 1 - (y&0xFFFU), yhigh = (yn&0xFFFU) + 1; const uchar *ysrc = &src[yi*stride]; for(uint x = 0; x < dw; x += wfrac, dst += BPP) { const uint xn = x + wfrac - 1, xi = x>>12, w = (xn>>12) - xi, xlow = ((w+0xFFFU)&0x1000U) - (x&0xFFFU), xhigh = (xn&0xFFFU) + 1; const uchar *xsrc = &ysrc[xi*BPP], *xend = &xsrc[w*BPP]; #define OP(c, n) c##t = 0 DEFPIXEL #undef OP for(const uchar *xcur = &xsrc[BPP]; xcur < xend; xcur += BPP) { #define OP(c, n) c##t += xcur[n] PIXELOP #undef OP } #define OP(c, n) c##t = (ylow*(c##t + ((xsrc[n]*xlow + xend[n]*xhigh)>>12)))>>cscale PIXELOP #undef OP if(h) { xsrc += stride; xend += stride; for(uint hcur = h; --hcur; xsrc += stride, xend += stride) { #define OP(c, n) c = 0 DEFPIXEL #undef OP for(const uchar *xcur = &xsrc[BPP]; xcur < xend; xcur += BPP) { #define OP(c, n) c += xcur[n] PIXELOP #undef OP } #define OP(c, n) c##t += ((c<<12) + xsrc[n]*xlow + xend[n]*xhigh)>>cscale; PIXELOP #undef OP } #define OP(c, n) c = 0 DEFPIXEL #undef OP for(const uchar *xcur = &xsrc[BPP]; xcur < xend; xcur += BPP) { #define OP(c, n) c += xcur[n] PIXELOP #undef OP } #define OP(c, n) c##t += (yhigh*(c + ((xsrc[n]*xlow + xend[n]*xhigh)>>12)))>>cscale PIXELOP #undef OP } #define OP(c, n) dst[n] = (c##t * area)>>dscale PIXELOP #undef OP } } } #undef FUNCNAME #undef DEFPIXEL #undef PIXELOP #undef BPP sandboxgamemaker-2.7.1+dfsg/src/engine/normal.cpp0000664000175000017500000002773411642642476021733 0ustar showardshoward#include "engine.h" struct normalgroup { vec pos; int flat, normals, tnormals; normalgroup() : flat(0), normals(-1), tnormals(-1) {} normalgroup(const vec &pos) : pos(pos), flat(0), normals(-1), tnormals(-1) {} }; static inline bool htcmp(const vec &v, const normalgroup &n) { return v == n.pos; } struct normal { int next; vec surface; }; struct tnormal { int next; float offset; int normals[2]; normalgroup *groups[2]; }; hashset normalgroups(1<<16); vector normals; vector tnormals; VARR(lerpangle, 0, 44, 180); static float lerpthreshold = 0; static bool usetnormals = true; static int addnormal(const vec &key, const vec &surface) { normalgroup &g = normalgroups.access(key, key); normal &n = normals.add(); n.next = g.normals; n.surface = surface; return g.normals = normals.length()-1; } static void addtnormal(const vec &key, float offset, int normal1, int normal2, normalgroup *group1, normalgroup *group2) { normalgroup &g = normalgroups.access(key, key); tnormal &n = tnormals.add(); n.next = g.tnormals; n.offset = offset; n.normals[0] = normal1; n.normals[1] = normal2; n.groups[0] = group1; n.groups[1] = group2; g.tnormals = tnormals.length()-1; } static int addnormal(const vec &key, int axis) { normalgroup &g = normalgroups.access(key, key); g.flat += 1<<(4*axis); return axis - 6; } static inline void findnormal(const normalgroup &g, const vec &surface, vec &v) { v = vec(0, 0, 0); int total = 0; if(surface.x >= lerpthreshold) { int n = (g.flat>>4)&0xF; v.x += n; total += n; } else if(surface.x <= -lerpthreshold) { int n = g.flat&0xF; v.x -= n; total += n; } if(surface.y >= lerpthreshold) { int n = (g.flat>>12)&0xF; v.y += n; total += n; } else if(surface.y <= -lerpthreshold) { int n = (g.flat>>8)&0xF; v.y -= n; total += n; } if(surface.z >= lerpthreshold) { int n = (g.flat>>20)&0xF; v.z += n; total += n; } else if(surface.z <= -lerpthreshold) { int n = (g.flat>>16)&0xF; v.z -= n; total += n; } for(int cur = g.normals; cur >= 0;) { normal &o = normals[cur]; if(o.surface.dot(surface) >= lerpthreshold) { v.add(o.surface); total++; } cur = o.next; } if(total > 1) v.normalize(); else if(!total) v = surface; } static inline bool findtnormal(const normalgroup &g, const vec &surface, vec &v) { float bestangle = lerpthreshold; tnormal *bestnorm = NULL; for(int cur = g.tnormals; cur >= 0;) { tnormal &o = tnormals[cur]; static const vec flats[6] = { vec(-1, 0, 0), vec(1, 0, 0), vec(0, -1, 0), vec(0, 1, 0), vec(0, 0, -1), vec(0, 0, 1) }; vec n1 = o.normals[0] < 0 ? flats[o.normals[0]+6] : normals[o.normals[0]].surface, n2 = o.normals[1] < 0 ? flats[o.normals[1]+6] : normals[o.normals[1]].surface, nt; nt.lerp(n1, n2, o.offset).normalize(); float tangle = nt.dot(surface); if(tangle >= bestangle) { bestangle = tangle; bestnorm = &o; } cur = o.next; } if(!bestnorm) return false; vec n1, n2; findnormal(*bestnorm->groups[0], surface, n1); findnormal(*bestnorm->groups[1], surface, n2); v.lerp(n1, n2, bestnorm->offset).normalize(); return true; } void findnormal(const vec &key, const vec &surface, vec &v) { const normalgroup *g = normalgroups.access(key); if(!g) v = surface; else if(g->tnormals < 0 || !findtnormal(*g, surface, v)) findnormal(*g, surface, v); } VARR(lerpsubdiv, 0, 2, 4); VARR(lerpsubdivsize, 4, 4, 128); static uint progress = 0; void show_addnormals_progress() { float bar1 = float(progress) / float(allocnodes); renderprogress(bar1, "computing normals..."); } void addnormals(cube &c, const ivec &o, int size) { CHECK_CALCLIGHT_PROGRESS(return, show_addnormals_progress); if(c.children) { progress++; size >>= 1; loopi(8) addnormals(c.children[i], ivec(i, o.x, o.y, o.z, size), size); return; } else if(isempty(c)) return; vec pos[MAXFACEVERTS]; int norms[MAXFACEVERTS]; int tj = usetnormals && c.ext ? c.ext->tjoints : -1, vis; loopi(6) if((vis = visibletris(c, i, o.x, o.y, o.z, size))) { CHECK_CALCLIGHT_PROGRESS(return, show_addnormals_progress); if(c.texture[i] == DEFAULT_SKY) continue; vec planes[2]; int numverts = c.ext ? c.ext->surfaces[i].numverts&MAXFACEVERTS : 0, convex = 0, numplanes = 0; if(numverts) { vertinfo *verts = c.ext->verts() + c.ext->surfaces[i].verts; vec vo = ivec(o).mask(~0xFFF).tovec(); loopj(numverts) { vertinfo &v = verts[j]; pos[j] = vec(v.x, v.y, v.z).mul(1.0f/8).add(vo); } if(!(c.merged&(1<= 0 && tjoints[tj].edge < i*(MAXFACEVERTS+1)) tj = tjoints[tj].next; while(tj >= 0 && tjoints[tj].edge < (i+1)*(MAXFACEVERTS+1)) { int edge = tjoints[tj].edge, e1 = edge%(MAXFACEVERTS+1), e2 = (e1+1)%numverts; const vec &v1 = pos[e1], &v2 = pos[e2]; ivec d = vec(v2).sub(v1).mul(8); int axis = abs(d.x) > abs(d.y) ? (abs(d.x) > abs(d.z) ? 0 : 2) : (abs(d.y) > abs(d.z) ? 1 : 2); if(d[axis] < 0) d.neg(); reduceslope(d); int origin = int(min(v1[axis], v2[axis])*8)&~0x7FFF, offset1 = (int(v1[axis]*8) - origin) / d[axis], offset2 = (int(v2[axis]*8) - origin) / d[axis]; vec o = vec(v1).sub(d.tovec().mul(offset1/8.0f)), n1, n2; float doffset = 1.0f / (offset2 - offset1); while(tj >= 0) { tjoint &t = tjoints[tj]; if(t.edge != edge) break; float offset = (t.offset - offset1) * doffset; vec tpos = d.tovec().mul(t.offset/8.0f).add(o); addtnormal(tpos, offset, norms[e1], norms[e2], normalgroups.access(v1), normalgroups.access(v2)); tj = t.next; } } } } void calcnormals(bool lerptjoints) { if(!lerpangle) return; usetnormals = lerptjoints; if(usetnormals) findtjoints(); lerpthreshold = cos(lerpangle*RAD) - 1e-5f; progress = 1; loopi(8) addnormals(worldroot[i], ivec(i, 0, 0, 0, worldsize/2), worldsize/2); } void clearnormals() { normalgroups.clear(); normals.setsize(0); tnormals.setsize(0); } void calclerpverts(const vec2 *c, const vec *n, lerpvert *lv, int &numv) { int i = 0; loopj(numv) { if(j) { if(c[j] == c[j-1] && n[j] == n[j-1]) continue; if(j == numv-1 && c[j] == c[0] && n[j] == n[0]) continue; } lv[i].normal = n[j]; lv[i].u = c[j].x; lv[i].v = c[j].y; i++; } numv = i; } void setlerpstep(float v, lerpbounds &bounds) { if(bounds.min->v + 1 > bounds.max->v) { bounds.nstep = vec(0, 0, 0); bounds.normal = bounds.min->normal; if(bounds.min->normal != bounds.max->normal) { bounds.normal.add(bounds.max->normal); bounds.normal.normalize(); } bounds.ustep = 0; bounds.u = bounds.min->u; return; } bounds.nstep = bounds.max->normal; bounds.nstep.sub(bounds.min->normal); bounds.nstep.div(bounds.max->v-bounds.min->v); bounds.normal = bounds.nstep; bounds.normal.mul(v - bounds.min->v); bounds.normal.add(bounds.min->normal); bounds.ustep = (bounds.max->u-bounds.min->u) / (bounds.max->v-bounds.min->v); bounds.u = bounds.ustep * (v-bounds.min->v) + bounds.min->u; } void initlerpbounds(const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end) { const lerpvert *first = &lv[0], *second = NULL; loopi(numv-1) { if(lv[i+1].v < first->v) { second = first; first = &lv[i+1]; } else if(!second || lv[i+1].v < second->v) second = &lv[i+1]; } if(int(first->v) < int(second->v)) { start.min = end.min = first; } else if(first->u > second->u) { start.min = second; end.min = first; } else { start.min = first; end.min = second; } if((lv[1].u - lv->u)*(lv[2].v - lv->v) > (lv[1].v - lv->v)*(lv[2].u - lv->u)) { start.winding = end.winding = 1; start.max = (start.min == lv ? &lv[numv-1] : start.min-1); end.max = (end.min == &lv[numv-1] ? lv : end.min+1); } else { start.winding = end.winding = -1; start.max = (start.min == &lv[numv-1] ? lv : start.min+1); end.max = (end.min == lv ? &lv[numv-1] : end.min-1); } setlerpstep(0, start); setlerpstep(0, end); } void updatelerpbounds(float v, const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end) { if(v >= start.max->v) { const lerpvert *next = start.winding > 0 ? (start.max == lv ? &lv[numv-1] : start.max-1) : (start.max == &lv[numv-1] ? lv : start.max+1); if(next->v > start.max->v) { start.min = start.max; start.max = next; setlerpstep(v, start); } } if(v >= end.max->v) { const lerpvert *next = end.winding > 0 ? (end.max == &lv[numv-1] ? lv : end.max+1) : (end.max == lv ? &lv[numv-1] : end.max-1); if(next->v > end.max->v) { end.min = end.max; end.max = next; setlerpstep(v, end); } } } void lerpnormal(float v, const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end, vec &normal, vec &nstep) { updatelerpbounds(v, lv, numv, start, end); if(start.u + 1 > end.u) { nstep = vec(0, 0, 0); normal = start.normal; normal.add(end.normal); normal.normalize(); } else { vec nstart(start.normal), nend(end.normal); nstart.normalize(); nend.normalize(); nstep = nend; nstep.sub(nstart); nstep.div(end.u-start.u); normal = nstep; normal.mul(-start.u); normal.add(nstart); normal.normalize(); } start.normal.add(start.nstep); start.u += start.ustep; end.normal.add(end.nstep); end.u += end.ustep; } sandboxgamemaker-2.7.1+dfsg/src/engine/octarender.cpp0000664000175000017500000016600011642642476022557 0ustar showardshoward// octarender.cpp: fill vertex arrays with different cube surfaces. #include "engine.h" struct vboinfo { int uses; uchar *data; }; static inline uint hthash(GLuint key) { return key; } static inline bool htcmp(GLuint x, GLuint y) { return x==y; } hashtable vbos; VAR(printvbo, 0, 0, 1); VARFN(vbosize, maxvbosize, 0, 1<<14, 1<<16, allchanged()); enum { VBO_VBUF = 0, VBO_EBUF, VBO_SKYBUF, NUMVBO }; static vector vbodata[NUMVBO]; static vector vbovas[NUMVBO]; static int vbosize[NUMVBO]; void destroyvbo(GLuint vbo) { vboinfo *exists = vbos.access(vbo); if(!exists) return; vboinfo &vbi = *exists; if(vbi.uses <= 0) return; vbi.uses--; if(!vbi.uses) { if(hasVBO) glDeleteBuffers_(1, &vbo); else if(vbi.data) delete[] vbi.data; vbos.remove(vbo); } } void genvbo(int type, void *buf, int len, vtxarray **vas, int numva) { GLuint vbo; uchar *data = NULL; if(hasVBO) { glGenBuffers_(1, &vbo); GLenum target = type==VBO_VBUF ? GL_ARRAY_BUFFER_ARB : GL_ELEMENT_ARRAY_BUFFER_ARB; glBindBuffer_(target, vbo); glBufferData_(target, len, buf, GL_STATIC_DRAW_ARB); glBindBuffer_(target, 0); } else { static GLuint nextvbo = 0; if(!nextvbo) nextvbo++; // just in case it ever wraps around vbo = nextvbo++; data = new uchar[len]; memcpy(data, buf, len); } vboinfo &vbi = vbos[vbo]; vbi.uses = numva; vbi.data = data; if(printvbo) conoutf(CON_DEBUG, "vbo %d: type %d, size %d, %d uses", vbo, type, len, numva); loopi(numva) { vtxarray *va = vas[i]; switch(type) { case VBO_VBUF: va->vbuf = vbo; if(!hasVBO) va->vdata = (vertex *)(data + (size_t)va->vdata); break; case VBO_EBUF: va->ebuf = vbo; if(!hasVBO) va->edata = (ushort *)(data + (size_t)va->edata); break; case VBO_SKYBUF: va->skybuf = vbo; if(!hasVBO) va->skydata = (ushort *)(data + (size_t)va->skydata); break; } } } bool readva(vtxarray *va, ushort *&edata, uchar *&vdata) { if(!va->vbuf || !va->ebuf) return false; edata = new ushort[3*va->tris]; vdata = new uchar[va->verts*VTXSIZE]; if(hasVBO) { glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); glGetBufferSubData_(GL_ELEMENT_ARRAY_BUFFER_ARB, (size_t)va->edata, 3*va->tris*sizeof(ushort), edata); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glGetBufferSubData_(GL_ARRAY_BUFFER_ARB, va->voffset*VTXSIZE, va->verts*VTXSIZE, vdata); glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); return true; } else { memcpy(edata, va->edata, 3*va->tris*sizeof(ushort)); memcpy(vdata, (uchar *)va->vdata + va->voffset*VTXSIZE, va->verts*VTXSIZE); return true; } } void flushvbo(int type = -1) { if(type < 0) { loopi(NUMVBO) flushvbo(i); return; } vector &data = vbodata[type]; if(data.empty()) return; vector &vas = vbovas[type]; genvbo(type, data.getbuf(), data.length(), vas.getbuf(), vas.length()); data.setsize(0); vas.setsize(0); vbosize[type] = 0; } uchar *addvbo(vtxarray *va, int type, int numelems, int elemsize) { vbosize[type] += numelems; vector &data = vbodata[type]; vector &vas = vbovas[type]; vas.add(va); int len = numelems*elemsize; uchar *buf = data.reserve(len).buf; data.advance(len); return buf; } struct verthash { static const int SIZE = 1<<13; int table[SIZE]; vector verts; vector chain; verthash() { clearverts(); } void clearverts() { memset(table, -1, sizeof(table)); chain.setsize(0); verts.setsize(0); } int addvert(const vertex &v) { uint h = hthash(v.pos)&(SIZE-1); for(int i = table[h]; i>=0; i = chain[i]) { const vertex &c = verts[i]; if(c.pos==v.pos && c.u==v.u && c.v==v.v && c.norm==v.norm && c.tangent==v.tangent && c.bitangent==v.bitangent) { if(!v.lmu && !v.lmv) return i; if(c.lmu==v.lmu && c.lmv==v.lmv) return i; } } if(verts.length() >= USHRT_MAX) return -1; verts.add(v); chain.add(table[h]); return table[h] = verts.length()-1; } int addvert(const vec &pos, float u = 0, float v = 0, short lmu = 0, short lmv = 0, const bvec &norm = bvec(128, 128, 128), const bvec &tangent = bvec(128, 128, 128), uchar bitangent = 128) { vertex vtx; vtx.pos = pos; vtx.u = u; vtx.v = v; vtx.lmu = lmu; vtx.lmv = lmv; vtx.norm = norm; vtx.reserved = 0; vtx.tangent = tangent; vtx.bitangent = bitangent; return addvert(vtx); } }; enum { NO_ALPHA = 0, ALPHA_BACK, ALPHA_FRONT }; struct sortkey { ushort tex, lmid, envmap; uchar dim, layer, alpha; sortkey() {} sortkey(ushort tex, ushort lmid, uchar dim, uchar layer = LAYER_TOP, ushort envmap = EMID_NONE, uchar alpha = NO_ALPHA) : tex(tex), lmid(lmid), envmap(envmap), dim(dim), layer(layer), alpha(alpha) {} bool operator==(const sortkey &o) const { return tex==o.tex && lmid==o.lmid && envmap==o.envmap && dim==o.dim && layer==o.layer && alpha==o.alpha; } }; struct sortval { int unlit; vector tris[2]; sortval() : unlit(0) {} }; static inline bool htcmp(const sortkey &x, const sortkey &y) { return x == y; } static inline uint hthash(const sortkey &k) { return k.tex + k.lmid*9741; } struct vacollect : verthash { ivec origin; int size; hashtable indices; vector texs; vector grasstris; vector matsurfs; vector mapmodels; vector skyindices, explicitskyindices; int worldtris, skytris, skyfaces, skyclip, skyarea; void clear() { clearverts(); worldtris = skytris = 0; skyfaces = 0; skyclip = INT_MAX; skyarea = 0; indices.clear(); skyindices.setsize(0); explicitskyindices.setsize(0); matsurfs.setsize(0); mapmodels.setsize(0); grasstris.setsize(0); texs.setsize(0); } void remapunlit(vector &remap) { uint lastlmid[8] = { LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT }, firstlmid[8] = { LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT }; int firstlit[8] = { -1, -1, -1, -1, -1, -1, -1, -1 }; loopv(texs) { sortkey &k = texs[i]; if(k.lmid>=LMID_RESERVED) { LightMapTexture &lmtex = lightmaptexs[k.lmid]; int type = lmtex.type&LM_TYPE; if(k.layer==LAYER_BLEND) type += 2; else if(k.alpha) type = 4 + 2*(k.alpha-1); lastlmid[type] = lmtex.unlitx>=0 ? k.lmid : LMID_AMBIENT; if(firstlmid[type]==LMID_AMBIENT && lastlmid[type]!=LMID_AMBIENT) { firstlit[type] = i; firstlmid[type] = lastlmid[type]; } } else if(k.lmid==LMID_AMBIENT) { Shader *s = lookupvslot(k.tex, false).slot->shader; int type = s->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE; if(k.layer==LAYER_BLEND) type += 2; else if(k.alpha) type = 4 + 2*(k.alpha-1); if(lastlmid[type]!=LMID_AMBIENT) { sortval &t = indices[k]; if(t.unlit<=0) t.unlit = lastlmid[type]; } } } loopj(2) { int offset = 2*j; if(firstlmid[offset]==LMID_AMBIENT && firstlmid[offset+1]==LMID_AMBIENT) continue; loopi(max(firstlit[offset], firstlit[offset+1])) { sortkey &k = texs[i]; if((j ? k.layer!=LAYER_BLEND : k.layer==LAYER_BLEND) || k.alpha) continue; if(k.lmid!=LMID_AMBIENT) continue; Shader *s = lookupvslot(k.tex, false).slot->shader; int type = offset + (s->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE); if(firstlmid[type]==LMID_AMBIENT) continue; indices[k].unlit = firstlmid[type]; } } loopj(2) { int offset = 4 + 2*j; if(firstlmid[offset]==LMID_AMBIENT && firstlmid[offset+1]==LMID_AMBIENT) continue; loopi(max(firstlit[offset], firstlit[offset+1])) { sortkey &k = texs[i]; if(k.alpha != j+1) continue; if(k.lmid!=LMID_AMBIENT) continue; Shader *s = lookupvslot(k.tex, false).slot->shader; int type = offset + (s->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE); if(firstlmid[type]==LMID_AMBIENT) continue; indices[k].unlit = firstlmid[type]; } } loopv(remap) { sortkey &k = remap[i]; sortval &t = indices[k]; if(t.unlit<=0) continue; LightMapTexture &lm = lightmaptexs[t.unlit]; short u = short(ceil((lm.unlitx + 0.5f) * SHRT_MAX/lm.w)), v = short(ceil((lm.unlity + 0.5f) * SHRT_MAX/lm.h)); loopl(2) loopvj(t.tris[l]) { vertex &vtx = verts[t.tris[l][j]]; if(!vtx.lmu && !vtx.lmv) { vtx.lmu = u; vtx.lmv = v; } else if(vtx.lmu != u || vtx.lmv != v) { vertex vtx2 = vtx; vtx2.lmu = u; vtx2.lmv = v; t.tris[l][j] = addvert(vtx2); } } sortval *dst = indices.access(sortkey(k.tex, t.unlit, k.dim, k.layer, k.envmap, k.alpha)); if(dst) loopl(2) loopvj(t.tris[l]) dst->tris[l].add(t.tris[l][j]); } } void optimize() { vector remap; enumeratekt(indices, sortkey, k, sortval, t, loopl(2) if(t.tris[l].length() && t.unlit<=0) { if(k.lmid>=LMID_RESERVED && lightmaptexs[k.lmid].unlitx>=0) { sortkey ukey(k.tex, LMID_AMBIENT, k.dim, k.layer, k.envmap, k.alpha); sortval *uval = indices.access(ukey); if(uval && uval->unlit<=0) { if(uval->unlit<0) texs.removeobj(ukey); else remap.add(ukey); uval->unlit = k.lmid; } } else if(k.lmid==LMID_AMBIENT) { remap.add(k); t.unlit = -1; } texs.add(k); break; } ); texs.sort(texsort); remapunlit(remap); matsurfs.shrink(optimizematsurfs(matsurfs.getbuf(), matsurfs.length())); } static inline bool texsort(const sortkey &x, const sortkey &y) { if(x.alpha < y.alpha) return true; if(x.alpha > y.alpha) return false; if(x.layer < y.layer) return true; if(x.layer > y.layer) return false; if(x.tex == y.tex) { if(x.lmid < y.lmid) return true; if(x.lmid > y.lmid) return false; if(x.envmap < y.envmap) return true; if(x.envmap > y.envmap) return false; if(x.dim < y.dim) return true; if(x.dim > y.dim) return false; return false; } if(renderpath!=R_FIXEDFUNCTION) { VSlot &xs = lookupvslot(x.tex, false), &ys = lookupvslot(y.tex, false); if(xs.slot->shader < ys.slot->shader) return true; if(xs.slot->shader > ys.slot->shader) return false; if(xs.slot->params.length() < ys.slot->params.length()) return true; if(xs.slot->params.length() > ys.slot->params.length()) return false; } if(x.tex < y.tex) return true; else return false; } #define GENVERTS(type, ptr, body) do \ { \ type *f = (type *)ptr; \ loopv(verts) \ { \ const vertex &v = verts[i]; \ body; \ f++; \ } \ } while(0) #define GENVERTSPOSNORMUV(type, ptr, body) GENVERTS(type, ptr, { f->pos = v.pos; f->norm = v.norm; f->norm.flip(); f->reserved = 0; f->u = v.u; f->v = v.v; body; }) void genverts(void *buf) { if(renderpath==R_FIXEDFUNCTION) GENVERTSPOSNORMUV(vertexff, buf, { f->lmu = v.lmu/float(SHRT_MAX); f->lmv = v.lmv/float(SHRT_MAX); }); else GENVERTS(vertex, buf, { *f = v; f->norm.flip(); }); } void setupdata(vtxarray *va) { va->verts = verts.length(); va->tris = worldtris/3; va->vbuf = 0; va->vdata = 0; va->minvert = 0; va->maxvert = va->verts-1; va->voffset = 0; if(va->verts) { if(vbosize[VBO_VBUF] + verts.length() > maxvbosize || vbosize[VBO_EBUF] + worldtris > USHRT_MAX || vbosize[VBO_SKYBUF] + skytris > USHRT_MAX) flushvbo(); va->voffset = vbosize[VBO_VBUF]; uchar *vdata = addvbo(va, VBO_VBUF, va->verts, VTXSIZE); genverts(vdata); va->minvert += va->voffset; va->maxvert += va->voffset; } va->matbuf = NULL; va->matsurfs = matsurfs.length(); if(va->matsurfs) { va->matbuf = new materialsurface[matsurfs.length()]; memcpy(va->matbuf, matsurfs.getbuf(), matsurfs.length()*sizeof(materialsurface)); } va->skybuf = 0; va->skydata = 0; va->sky = skyindices.length(); va->explicitsky = explicitskyindices.length(); if(va->sky + va->explicitsky) { va->skydata += vbosize[VBO_SKYBUF]; ushort *skydata = (ushort *)addvbo(va, VBO_SKYBUF, va->sky+va->explicitsky, sizeof(ushort)); memcpy(skydata, skyindices.getbuf(), va->sky*sizeof(ushort)); memcpy(skydata+va->sky, explicitskyindices.getbuf(), va->explicitsky*sizeof(ushort)); if(va->voffset) loopi(va->sky+va->explicitsky) skydata[i] += va->voffset; } va->eslist = NULL; va->texs = texs.length(); va->blendtris = 0; va->blends = 0; va->alphabacktris = 0; va->alphaback = 0; va->alphafronttris = 0; va->alphafront = 0; va->ebuf = 0; va->edata = 0; if(va->texs) { va->eslist = new elementset[va->texs]; va->edata += vbosize[VBO_EBUF]; ushort *edata = (ushort *)addvbo(va, VBO_EBUF, worldtris, sizeof(ushort)), *curbuf = edata; loopv(texs) { const sortkey &k = texs[i]; const sortval &t = indices[k]; elementset &e = va->eslist[i]; e.texture = k.tex; e.lmid = t.unlit>0 ? t.unlit : k.lmid; e.dim = k.dim; e.layer = k.layer; e.envmap = k.envmap; ushort *startbuf = curbuf; loopl(2) { e.minvert[l] = USHRT_MAX; e.maxvert[l] = 0; if(t.tris[l].length()) { memcpy(curbuf, t.tris[l].getbuf(), t.tris[l].length() * sizeof(ushort)); loopvj(t.tris[l]) { curbuf[j] += va->voffset; e.minvert[l] = min(e.minvert[l], curbuf[j]); e.maxvert[l] = max(e.maxvert[l], curbuf[j]); } curbuf += t.tris[l].length(); } e.length[l] = curbuf-startbuf; } if(k.layer==LAYER_BLEND) { va->texs--; va->tris -= e.length[1]/3; va->blends++; va->blendtris += e.length[1]/3; } else if(k.alpha==ALPHA_BACK) { va->texs--; va->tris -= e.length[1]/3; va->alphaback++; va->alphabacktris += e.length[1]/3; } else if(k.alpha==ALPHA_FRONT) { va->texs--; va->tris -= e.length[1]/3; va->alphafront++; va->alphafronttris += e.length[1]/3; } } } va->texmask = 0; loopi(va->texs+va->blends+va->alphaback+va->alphafront) { Slot &slot = *lookupvslot(va->eslist[i].texture, false).slot; loopvj(slot.sts) va->texmask |= 1<type&SHADER_ENVMAP && (renderpath!=R_FIXEDFUNCTION || (slot.ffenv && hasCM && maxtmus >= 2))) va->texmask |= 1<grasstris.move(grasstris); useshaderbyname("grass"); } if(mapmodels.length()) va->mapmodels.put(mapmodels.getbuf(), mapmodels.length()); } bool emptyva() { return verts.empty() && matsurfs.empty() && skyindices.empty() && explicitskyindices.empty() && grasstris.empty() && mapmodels.empty(); } } vc; int recalcprogress = 0; #define progress(s) if((recalcprogress++&0xFFF)==0) renderprogress(recalcprogress/(float)allocnodes, s); vector tjoints; vec shadowmapmin, shadowmapmax; int calcshadowmask(vec *pos, int numpos) { extern vec shadowdir; int mask = 0, used = 1; vec pe = vec(pos[1]).sub(pos[0]); loopk(numpos-2) { vec e = vec(pos[k+2]).sub(pos[0]); if(vec().cross(pe, e).dot(shadowdir)>0) { mask |= 1< &idxs = key.tex==DEFAULT_SKY ? vc.explicitskyindices : vc.indices[key].tris[(shadowmask>>i)&1]; int left = index[0], mid = index[i+1], right = index[i+2], start = left, i0 = left, i1 = -1; loopk(4) { int i2 = -1, ctj = -1, cedge = -1; switch(k) { case 1: i1 = i2 = mid; cedge = edge+i+1; break; case 2: if(i1 != mid || i0 == left) { i0 = i1; i1 = right; } i2 = right; if(i+1 == numverts-2) cedge = edge+i+2; break; case 3: if(i0 == start) { i0 = i1; i1 = left; } i2 = left; // fall-through default: if(!i) cedge = edge; break; } if(i1 != i2) { if(total + 3 > USHRT_MAX) return; total += 3; idxs.add(i0); idxs.add(i1); idxs.add(i2); i1 = i2; } if(cedge >= 0) { for(ctj = tj;;) { if(ctj < 0) break; if(tjoints[ctj].edge < cedge) { ctj = tjoints[ctj].next; continue; } if(tjoints[ctj].edge != cedge) ctj = -1; break; } } if(ctj >= 0) { int e1 = cedge%(MAXFACEVERTS+1), e2 = (e1+1)%numverts; vertex &v1 = verts[e1], &v2 = verts[e2]; ivec d(vec(v2.pos).sub(v1.pos).mul(8)); int axis = abs(d.x) > abs(d.y) ? (abs(d.x) > abs(d.z) ? 0 : 2) : (abs(d.y) > abs(d.z) ? 1 : 2); if(d[axis] < 0) d.neg(); reduceslope(d); int origin = int(min(v1.pos[axis], v2.pos[axis])*8)&~0x7FFF, offset1 = (int(v1.pos[axis]*8) - origin) / d[axis], offset2 = (int(v2.pos[axis]*8) - origin) / d[axis]; vec o = vec(v1.pos).sub(d.tovec().mul(offset1/8.0f)); float doffset = 1.0f / (offset2 - offset1); if(i1 < 0) for(;;) { tjoint &t = tjoints[ctj]; if(t.next < 0 || tjoints[t.next].edge != cedge) break; ctj = t.next; } while(ctj >= 0) { tjoint &t = tjoints[ctj]; if(t.edge != cedge) break; float offset = (t.offset - offset1) * doffset; vertex vt; vt.pos = d.tovec().mul(t.offset/8.0f).add(o); vt.reserved = 0; vt.u = v1.u + (v2.u-v1.u)*offset; vt.v = v1.v + (v2.v-v1.v)*offset; vt.lmu = short(v1.lmu + (v2.lmu-v1.lmu)*offset), vt.lmv = short(v1.lmv + (v2.lmv-v1.lmv)*offset); vt.norm.lerp(v1.norm, v2.norm, offset); vt.tangent.lerp(v1.tangent, v2.tangent, offset); vt.bitangent = v1.bitangent; int i2 = vc.addvert(vt); if(i2 < 0) return; if(i1 >= 0) { if(total + 3 > USHRT_MAX) return; total += 3; idxs.add(i0); idxs.add(i1); idxs.add(i2); i1 = i2; } else start = i0 = i2; ctj = t.next; } } } } } void addgrasstri(int face, vertex *verts, int numv, ushort texture, ushort lmid) { grasstri &g = vc.grasstris.add(); int i1, i2, i3, i4; if(numv <= 3 && face%2) { i1 = face+1; i2 = face+2; i3 = i4 = 0; } else { i1 = 0; i2 = face+1; i3 = face+2; i4 = numv > 3 ? face+3 : i3; } g.v[0] = verts[i1].pos; g.v[1] = verts[i2].pos; g.v[2] = verts[i3].pos; g.v[3] = verts[i4].pos; g.numv = numv; g.surface.toplane(g.v[0], g.v[1], g.v[2]); if(g.surface.z <= 0) { vc.grasstris.pop(); return; } g.minz = min(min(g.v[0].z, g.v[1].z), min(g.v[2].z, g.v[3].z)); g.maxz = max(max(g.v[0].z, g.v[1].z), max(g.v[2].z, g.v[3].z)); g.center = vec(0, 0, 0); loopk(numv) g.center.add(g.v[k]); g.center.div(numv); g.radius = 0; loopk(numv) g.radius = max(g.radius, g.v[k].dist(g.center)); vec area, bx, by; area.cross(vec(g.v[1]).sub(g.v[0]), vec(g.v[2]).sub(g.v[0])); float scale; int px, py; if(fabs(area.x) >= fabs(area.y) && fabs(area.x) >= fabs(area.z)) scale = 1/area.x, px = 1, py = 2; else if(fabs(area.y) >= fabs(area.x) && fabs(area.y) >= fabs(area.z)) scale = -1/area.y, px = 0, py = 2; else scale = 1/area.z, px = 0, py = 1; bx.x = (g.v[2][py] - g.v[0][py])*scale; bx.y = (g.v[2][px] - g.v[0][px])*scale; bx.z = bx.x*g.v[2][px] - bx.y*g.v[2][py]; by.x = (g.v[2][py] - g.v[1][py])*scale; by.y = (g.v[2][px] - g.v[1][px])*scale; by.z = by.x*g.v[1][px] - by.y*g.v[1][py] - 1; by.sub(bx); float tc1u = verts[i1].lmu/float(SHRT_MAX), tc1v = verts[i1].lmv/float(SHRT_MAX), tc2u = (verts[i2].lmu - verts[i1].lmu)/float(SHRT_MAX), tc2v = (verts[i2].lmv - verts[i1].lmv)/float(SHRT_MAX), tc3u = (verts[i3].lmu - verts[i1].lmu)/float(SHRT_MAX), tc3v = (verts[i3].lmv - verts[i1].lmv)/float(SHRT_MAX); g.tcu = vec4(0, 0, 0, tc1u - (bx.z*tc2u + by.z*tc3u)); g.tcu[px] = bx.x*tc2u + by.x*tc3u; g.tcu[py] = -(bx.y*tc2u + by.y*tc3u); g.tcv = vec4(0, 0, 0, tc1v - (bx.z*tc2v + by.z*tc3v)); g.tcv[px] = bx.x*tc2v + by.x*tc3v; g.tcv[py] = -(bx.y*tc2v + by.y*tc3v); g.texture = texture; g.lmid = lmid; } static inline void calctexgen(VSlot &vslot, int dim, vec4 &sgen, vec4 &tgen) { Texture *tex = vslot.slot->sts.empty() ? notexture : vslot.slot->sts[0].t; float k = TEX_SCALE/vslot.scale, xs = vslot.rotation>=2 && vslot.rotation<=4 ? -tex->xs : tex->xs, ys = (vslot.rotation>=1 && vslot.rotation<=2) || vslot.rotation==5 ? -tex->ys : tex->ys, sk = k/xs, tk = k/ys, soff = -((vslot.rotation&5)==1 ? vslot.yoffset : vslot.xoffset)/xs, toff = -((vslot.rotation&5)==1 ? vslot.xoffset : vslot.yoffset)/ys; static const int si[] = { 1, 0, 0 }, ti[] = { 2, 2, 1 }; int sdim = si[dim], tdim = ti[dim]; sgen = vec4(0, 0, 0, soff); tgen = vec4(0, 0, 0, toff); if((vslot.rotation&5)==1) { sgen[tdim] = (dim <= 1 ? -sk : sk); tgen[sdim] = tk; } else { sgen[sdim] = sk; tgen[tdim] = (dim <= 1 ? -tk : tk); } } ushort encodenormal(const vec &n) { if(n.iszero()) return 0; int yaw = int(-atan2(n.x, n.y)/RAD), pitch = int(asin(n.z)/RAD); return ushort(clamp(pitch + 90, 0, 180)*360 + (yaw < 0 ? yaw%360 + 360 : yaw%360) + 1); } vec decodenormal(ushort norm) { if(!norm) return vec(0, 0, 0); norm--; const vec2 &yaw = sincos360[norm%360], &pitch = sincos360[norm/360+270]; return vec(-yaw.y*pitch.x, yaw.x*pitch.x, pitch.y); } void addcubeverts(VSlot &vslot, int orient, int size, vec *pos, int convex, ushort texture, ushort lmid, vertinfo *vinfo, int numverts, int tj = -1, ushort envmap = EMID_NONE, int grassy = 0, bool alpha = false, int layer = LAYER_TOP) { int dim = dimension(orient); int shadowmask = texture==DEFAULT_SKY || alpha ? 0 : calcshadowmask(pos, numverts); LightMap *lm = NULL; LightMapTexture *lmtex = NULL; if(!nolights && lightmaps.inrange(lmid-LMID_RESERVED)) { lm = &lightmaps[lmid-LMID_RESERVED]; if((lm->type&LM_TYPE)==LM_DIFFUSE || ((lm->type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(lmid+1-LMID_RESERVED) && (lightmaps[lmid+1-LMID_RESERVED].type&LM_TYPE)==LM_BUMPMAP1)) lmtex = &lightmaptexs[lm->tex]; else lm = NULL; } vec4 sgen, tgen; calctexgen(vslot, dim, sgen, tgen); vertex verts[MAXFACEVERTS]; int index[MAXFACEVERTS]; loopk(numverts) { vertex &v = verts[k]; v.pos = pos[k]; v.reserved = 0; v.u = sgen.dot(v.pos); v.v = tgen.dot(v.pos); if(lmtex) { v.lmu = short(ceil((lm->offsetx + vinfo[k].u*(float(LM_PACKW)/float(USHRT_MAX+1)) + 0.5f) * float(SHRT_MAX)/lmtex->w)); v.lmv = short(ceil((lm->offsety + vinfo[k].v*(float(LM_PACKH)/float(USHRT_MAX+1)) + 0.5f) * float(SHRT_MAX)/lmtex->h)); } else v.lmu = v.lmv = 0; if(renderpath!=R_FIXEDFUNCTION && vinfo && vinfo[k].norm) { vec n = decodenormal(vinfo[k].norm), t = orientation_tangent[vslot.rotation][dim]; t.sub(vec(n).mul(n.dot(t))).normalize(); v.norm = bvec(n); v.tangent = bvec(t); v.bitangent = vec().cross(n, t).dot(orientation_binormal[vslot.rotation][dim]) < 0 ? 0 : 255; } else { v.norm = vinfo && vinfo[k].norm && envmap != EMID_NONE ? bvec(decodenormal(vinfo[k].norm)) : bvec(128, 128, 128); v.tangent = bvec(128, 128, 128); v.bitangent = 128; } index[k] = vc.addvert(v); if(index[k] < 0) return; } if(texture == DEFAULT_SKY) { loopk(numverts) vc.skyclip = min(vc.skyclip, int(pos[k].z*8)>>3); vc.skyfaces |= 0x3F&~(1<= LMID_RESERVED) lmid = lm ? lm->tex : LMID_AMBIENT; sortkey key(texture, lmid, vslot.scrollS || vslot.scrollT ? dim : 3, layer == LAYER_BLEND ? LAYER_BLEND : LAYER_TOP, envmap, alpha ? (vslot.alphaback ? ALPHA_BACK : (vslot.alphafront ? ALPHA_FRONT : NO_ALPHA)) : NO_ALPHA); addtris(key, orient, verts, index, numverts, convex, shadowmask, tj); if(grassy) { for(int i = 0; i < numverts-2; i += 2) { int faces = 0; if(index[0]!=index[i+1] && index[i+1]!=index[i+2] && index[i+2]!=index[0]) faces |= 1; if(i+3 < numverts && index[0]!=index[i+2] && index[i+2]!=index[i+3] && index[i+3]!=index[0]) faces |= 2; if(grassy > 1 && faces==3) addgrasstri(i, verts, 4, texture, lmid); else { if(faces&1) addgrasstri(i, verts, 3, texture, lmid); if(faces&2) addgrasstri(i+1, verts, 3, texture, lmid); } } } } struct edgegroup { ivec slope, origin; int axis; }; static uint hthash(const edgegroup &g) { return g.slope.x^g.slope.y^g.slope.z^g.origin.x^g.origin.y^g.origin.z; } static bool htcmp(const edgegroup &x, const edgegroup &y) { return x.slope==y.slope && x.origin==y.origin; } enum { CE_START = 1<<0, CE_END = 1<<1, CE_FLIP = 1<<2, CE_DUP = 1<<3 }; struct cubeedge { cube *c; int next, offset; ushort size; uchar index, flags; }; vector cubeedges; hashtable edgegroups(1<<13); void gencubeedges(cube &c, int x, int y, int z, int size) { ivec pos[MAXFACEVERTS]; int vis; loopi(6) if((vis = visibletris(c, i, x, y, z, size))) { int numverts = c.ext ? c.ext->surfaces[i].numverts&MAXFACEVERTS : 0; if(numverts) { vertinfo *verts = c.ext->verts() + c.ext->surfaces[i].verts; ivec vo = ivec(x, y, z).mask(~0xFFF).shl(3); loopj(numverts) { vertinfo &v = verts[j]; pos[j] = ivec(v.x, v.y, v.z).add(vo); } } else if(c.merged&(1< abs(d.y) ? (abs(d.x) > abs(d.z) ? 0 : 2) : (abs(d.y) > abs(d.z) ? 1 : 2); if(d[axis] < 0) { d.neg(); swap(e1, e2); } reduceslope(d); int t1 = pos[e1][axis]/d[axis], t2 = pos[e2][axis]/d[axis]; edgegroup g; g.origin = ivec(pos[e1]).sub(ivec(d).mul(t1)); g.slope = d; g.axis = axis; cubeedge ce; ce.c = &c; ce.offset = t1; ce.size = t2 - t1; ce.index = i*(MAXFACEVERTS+1)+j; ce.flags = CE_START | CE_END | (e1!=j ? CE_FLIP : 0); ce.next = -1; bool insert = true; int *exists = edgegroups.access(g); if(exists) { int prev = -1, cur = *exists; while(cur >= 0) { cubeedge &p = cubeedges[cur]; if(p.flags&CE_DUP ? ce.offset>=p.offset && ce.offset+ce.size<=p.offset+p.size : ce.offset==p.offset && ce.size==p.size) { p.flags |= CE_DUP; insert = false; break; } else if(ce.offset >= p.offset) { if(ce.offset == p.offset+p.size) ce.flags &= ~CE_START; prev = cur; cur = p.next; } else break; } if(insert) { ce.next = cur; while(cur >= 0) { cubeedge &p = cubeedges[cur]; if(ce.offset+ce.size==p.offset) { ce.flags &= ~CE_END; break; } cur = p.next; } if(prev>=0) cubeedges[prev].next = cubeedges.length(); else *exists = cubeedges.length(); } } else edgegroups[g] = cubeedges.length(); if(insert) cubeedges.add(ce); } } } void gencubeedges(cube *c = worldroot, int x = 0, int y = 0, int z = 0, int size = worldsize>>1) { progress("fixing t-joints..."); neighbourstack[++neighbourdepth] = c; loopi(8) { ivec o(i, x, y, z, size); if(c[i].ext) c[i].ext->tjoints = -1; if(c[i].children) gencubeedges(c[i].children, o.x, o.y, o.z, size>>1); else if(!isempty(c[i])) gencubeedges(c[i], o.x, o.y, o.z, size); } --neighbourdepth; } void gencubeverts(cube &c, int x, int y, int z, int size, int csi) { c.visible = 0; c.collide = 0; int tj = filltjoints && c.ext ? c.ext->tjoints : -1, vis; loopi(6) if((vis = visibletris(c, i, x, y, z, size))) { // this is necessary for physics to work, even if the face is merged if(collideface(c, i)) c.collide |= 1<surfaces[i].numverts&MAXFACEVERTS : 0, convex = 0; if(numverts) { verts = c.ext->verts() + c.ext->surfaces[i].verts; vec vo = ivec(x, y, z).mask(~0xFFF).tovec(); loopj(numverts) pos[j] = verts[j].getxyz().tovec().mul(1.0f/8).add(vo); if(!(c.merged&(1<shader->type&SHADER_ENVMAP ? (vslot.slot->texmask&(1<slot->shader->type&SHADER_ENVMAP ? (layer->slot->texmask&(1<= 0 && tjoints[tj].edge < i*(MAXFACEVERTS+1)) tj = tjoints[tj].next; int hastj = tj >= 0 && tjoints[tj].edge < (i+1)*(MAXFACEVERTS+1) ? tj : -1; int grassy = vslot.slot->autograss && i!=O_BOTTOM ? (vis!=3 || convex ? 1 : 2) : 0; if(!c.ext) addcubeverts(vslot, i, size, pos, convex, c.texture[i], LMID_AMBIENT, NULL, numverts, hastj, envmap, grassy, (c.material&MAT_ALPHA)!=0); else { const surfaceinfo &surf = c.ext->surfaces[i]; if(!surf.numverts || surf.numverts&LAYER_TOP) addcubeverts(vslot, i, size, pos, convex, c.texture[i], surf.lmid[0], verts, numverts, hastj, envmap, grassy, (c.material&MAT_ALPHA)!=0, LAYER_TOP|(surf.numverts&LAYER_BLEND)); if(surf.numverts&LAYER_BOTTOM) addcubeverts(layer ? *layer : vslot, i, size, pos, convex, vslot.layer, surf.lmid[1], surf.numverts&LAYER_DUP ? verts + numverts : verts, numverts, hastj, envmap2); } } else { if(visibleface(c, i, x, y, z, size, MAT_AIR, MAT_NOCLIP, MATF_CLIP) && collideface(c, i)) c.collide |= 1< skyfaces[6]; void minskyface(cube &cu, int orient, const ivec &co, int size, facebounds &orig) { facebounds mincf; mincf.u1 = orig.u2; mincf.u2 = orig.u1; mincf.v1 = orig.v2; mincf.v2 = orig.v1; mincubeface(cu, orient, co, size, orig, mincf, MAT_ALPHA, MAT_ALPHA); orig.u1 = max(mincf.u1, orig.u1); orig.u2 = min(mincf.u2, orig.u2); orig.v1 = max(mincf.v1, orig.v1); orig.v2 = min(mincf.v2, orig.v2); } void genskyfaces(cube &c, const ivec &o, int size) { if(isentirelysolid(c) && !(c.material&MAT_ALPHA)) return; int faces[6], numfaces = hasskyfaces(c, o.x, o.y, o.z, size, faces); if(!numfaces) return; loopi(numfaces) { int orient = faces[i], dim = dimension(orient); facebounds m; m.u1 = (o[C[dim]]&0xFFF)<<3; m.u2 = m.u1 + (size<<3); m.v1 = (o[R[dim]]&0xFFF)<<3; m.v2 = m.v1 + (size<<3); minskyface(c, orient, o, size, m); if(m.u1 >= m.u2 || m.v1 >= m.v2) continue; vc.skyarea += (int(m.u2-m.u1)*int(m.v2-m.v1) + (1<<(2*3))-1)>>(2*3); skyfaces[orient].add(m); } } void addskyverts(const ivec &o, int size) { loopi(6) { int dim = dimension(i), c = C[dim], r = R[dim]; vector &sf = skyfaces[i]; if(sf.empty()) continue; vc.skyfaces |= 0x3F&~(1<>3); } if(vc.skytris + 6 > USHRT_MAX) break; vc.skytris += 6; vc.skyindices.add(index[0]); vc.skyindices.add(index[1]); vc.skyindices.add(index[2]); vc.skyindices.add(index[0]); vc.skyindices.add(index[2]); vc.skyindices.add(index[3]); nextskyface:; } sf.setsize(0); } } ////////// Vertex Arrays ////////////// int allocva = 0; int wtris = 0, wverts = 0, vtris = 0, vverts = 0, glde = 0, gbatches = 0; vector valist, varoot; vtxarray *newva(int x, int y, int z, int size) { vc.optimize(); vtxarray *va = new vtxarray; va->parent = NULL; va->o = ivec(x, y, z); va->size = size; va->skyarea = vc.skyarea; va->skyfaces = vc.skyfaces; va->skyclip = vc.skyclip < INT_MAX ? vc.skyclip : INT_MAX; va->curvfc = VFC_NOT_VISIBLE; va->occluded = OCCLUDE_NOTHING; va->query = NULL; va->bbmin = ivec(-1, -1, -1); va->bbmax = ivec(-1, -1, -1); va->hasmerges = 0; va->mergelevel = -1; vc.setupdata(va); wverts += va->verts; wtris += va->tris + va->blends + va->alphabacktris + va->alphafronttris; allocva++; valist.add(va); return va; } void destroyva(vtxarray *va, bool reparent) { wverts -= va->verts; wtris -= va->tris + va->blends + va->alphabacktris + va->alphafronttris; allocva--; valist.removeobj(va); if(!va->parent) varoot.removeobj(va); if(reparent) { if(va->parent) va->parent->children.removeobj(va); loopv(va->children) { vtxarray *child = va->children[i]; child->parent = va->parent; if(child->parent) child->parent->children.add(child); } } if(va->vbuf) destroyvbo(va->vbuf); if(va->ebuf) destroyvbo(va->ebuf); if(va->skybuf) destroyvbo(va->skybuf); if(va->eslist) delete[] va->eslist; if(va->matbuf) delete[] va->matbuf; delete va; } void clearvas(cube *c) { loopi(8) { if(c[i].ext) { if(c[i].ext->va) destroyva(c[i].ext->va, false); c[i].ext->va = NULL; c[i].ext->tjoints = -1; } if(c[i].children) clearvas(c[i].children); } } void updatevabb(vtxarray *va, bool force) { if(!force && va->bbmin.x >= 0) return; va->bbmin = va->geommin; va->bbmax = va->geommax; va->bbmin.min(va->matmin); va->bbmax.max(va->matmax); loopv(va->children) { vtxarray *child = va->children[i]; updatevabb(child, force); va->bbmin.min(child->bbmin); va->bbmax.max(child->bbmax); } loopv(va->mapmodels) { octaentities *oe = va->mapmodels[i]; va->bbmin.min(oe->bbmin); va->bbmax.max(oe->bbmax); } if(va->skyfaces) { va->skyfaces |= 0x80; if(va->sky) loop(dim, 3) if(va->skyfaces&(3<<(2*dim))) { int r = R[dim], c = C[dim]; if((va->skyfaces&(1<<(2*dim)) && va->o[dim] < va->bbmin[dim]) || (va->skyfaces&(2<<(2*dim)) && va->o[dim]+va->size > va->bbmax[dim]) || va->o[r] < va->bbmin[r] || va->o[r]+va->size > va->bbmax[r] || va->o[c] < va->bbmin[c] || va->o[c]+va->size > va->bbmax[c]) { va->skyfaces &= ~0x80; break; } } } } void updatevabbs(bool force) { loopv(varoot) updatevabb(varoot[i], force); } struct mergedface { uchar orient, mat, lmid, numverts; ushort tex, envmap; vertinfo *verts; int tjoints; }; #define MAXMERGELEVEL 12 static int vahasmerges = 0, vamergemax = 0; static vector vamerges[MAXMERGELEVEL+1]; int genmergedfaces(cube &c, const ivec &co, int size, int minlevel = -1) { if(!c.ext || isempty(c)) return -1; int tj = c.ext->tjoints, maxlevel = -1; if(minlevel < 0) c.escaped &= ~c.merged; loopi(6) { if(!(c.merged&(1<surfaces[i]; int numverts = surf.numverts&MAXFACEVERTS; if(!numverts) { if(minlevel < 0) vahasmerges |= MERGE_PART; continue; } mergedface mf; mf.orient = i; mf.mat = c.material; mf.tex = c.texture[i]; mf.envmap = EMID_NONE; mf.lmid = surf.lmid[0]; mf.numverts = surf.numverts; mf.verts = c.ext->verts() + surf.verts; mf.tjoints = -1; int level = calcmergedsize(i, co, size, mf.verts, mf.numverts&MAXFACEVERTS); if(minlevel < 0 && 1< size) c.escaped |= 1< minlevel) { maxlevel = max(maxlevel, level); while(tj >= 0 && tjoints[tj].edge < i*(MAXFACEVERTS+1)) tj = tjoints[tj].next; if(tj >= 0 && tjoints[tj].edge < (i+1)*(MAXFACEVERTS+1)) mf.tjoints = tj; VSlot &vslot = lookupvslot(mf.tex, true), *layer = vslot.layer && !(c.material&MAT_ALPHA) ? &lookupvslot(vslot.layer, true) : NULL; if(vslot.slot->shader->type&SHADER_ENVMAP) mf.envmap = vslot.slot->texmask&(1<slot->shader->type&SHADER_ENVMAP ? (layer->slot->texmask&(1<= 0) { vamergemax = max(vamergemax, maxlevel); vahasmerges |= MERGE_ORIGIN; } return maxlevel; } int findmergedfaces(cube &c, const ivec &co, int size, int csi, int minlevel) { if(c.ext && c.ext->va && !(c.ext->va->hasmerges&MERGE_ORIGIN)) return c.ext->va->mergelevel; else if(c.children) { int maxlevel = -1; loopi(8) { ivec o(i, co.x, co.y, co.z, size/2); int level = findmergedfaces(c.children[i], o, size/2, csi-1, minlevel); maxlevel = max(maxlevel, level); } return maxlevel; } else if(c.ext && c.merged) return genmergedfaces(c, co, size, minlevel); else return -1; } void addmergedverts(int level, const ivec &o) { vector &mfl = vamerges[level]; if(mfl.empty()) return; vec vo = ivec(o).mask(~0xFFF).tovec(); vec pos[MAXFACEVERTS]; loopv(mfl) { mergedface &mf = mfl[i]; int numverts = mf.numverts&MAXFACEVERTS; loopi(numverts) { vertinfo &v = mf.verts[i]; pos[i] = vec(v.x, v.y, v.z).mul(1.0f/8).add(vo); } VSlot &vslot = lookupvslot(mf.tex, true); int grassy = vslot.slot->autograss && mf.orient!=O_BOTTOM && mf.numverts&LAYER_TOP ? 2 : 0; addcubeverts(vslot, mf.orient, 1<va) { maxlevel = max(maxlevel, c.ext->va->mergelevel); return; // don't re-render } if(c.children) { neighbourstack[++neighbourdepth] = c.children; c.escaped = 0; loopi(8) { ivec o(i, cx, cy, cz, size/2); int level = -1; rendercube(c.children[i], o.x, o.y, o.z, size/2, csi-1, level); if(level >= csi) c.escaped |= 1<ents && c.ext->ents->mapmodels.length()) vc.mapmodels.add(c.ext->ents); } return; } genskyfaces(c, ivec(cx, cy, cz), size); if(!isempty(c)) { gencubeverts(c, cx, cy, cz, size, csi); if(c.merged) maxlevel = max(maxlevel, genmergedfaces(c, ivec(cx, cy, cz), size)); } if(c.material != MAT_AIR) genmatsurfs(c, cx, cy, cz, size, vc.matsurfs); if(c.ext) { if(c.ext->ents && c.ext->ents->mapmodels.length()) vc.mapmodels.add(c.ext->ents); } if(csi <= MAXMERGELEVEL && vamerges[csi].length()) addmergedverts(csi, ivec(cx, cy, cz)); } void calcgeombb(int cx, int cy, int cz, int size, ivec &bbmin, ivec &bbmax) { vec vmin(cx, cy, cz), vmax = vmin; vmin.add(size); loopv(vc.verts) { const vec &v = vc.verts[i].pos; vmin.min(v); vmax.max(v); } bbmin = ivec(vmin.mul(8)).shr(3); bbmax = ivec(vmax.mul(8)).add(7).shr(3); } void calcmatbb(int cx, int cy, int cz, int size, ivec &bbmin, ivec &bbmax) { bbmax = ivec(cx, cy, cz); (bbmin = bbmax).add(size); loopv(vc.matsurfs) { materialsurface &m = vc.matsurfs[i]; switch(m.material) { case MAT_WATER: case MAT_GLASS: case MAT_LAVA: break; default: continue; } int dim = dimension(m.orient), r = R[dim], c = C[dim]; bbmin[dim] = min(bbmin[dim], m.o[dim]); bbmax[dim] = max(bbmax[dim], m.o[dim]); bbmin[r] = min(bbmin[r], m.o[r]); bbmax[r] = max(bbmax[r], m.o[r] + m.rsize); bbmin[c] = min(bbmin[c], m.o[c]); bbmax[c] = max(bbmax[c], m.o[c] + m.csize); } } void setva(cube &c, int cx, int cy, int cz, int size, int csi) { ASSERT(size <= 0x1000); int vamergeoffset[MAXMERGELEVEL+1]; loopi(MAXMERGELEVEL+1) vamergeoffset[i] = vamerges[i].length(); vc.origin = ivec(cx, cy, cz); vc.size = size; shadowmapmin = vec(cx+size, cy+size, cz+size); shadowmapmax = vec(cx, cy, cz); int maxlevel = -1; rendercube(c, cx, cy, cz, size, csi, maxlevel); ivec bbmin, bbmax; calcgeombb(cx, cy, cz, size, bbmin, bbmax); addskyverts(ivec(cx, cy, cz), size); if(!vc.emptyva()) { vtxarray *va = newva(cx, cy, cz, size); ext(c).va = va; va->geommin = bbmin; va->geommax = bbmax; calcmatbb(cx, cy, cz, size, va->matmin, va->matmax); va->shadowmapmin = ivec(shadowmapmin.mul(8)).shr(3); va->shadowmapmax = ivec(shadowmapmax.mul(8)).add(7).shr(3); va->hasmerges = vahasmerges; va->mergelevel = vamergemax; } else { loopi(MAXMERGELEVEL+1) vamerges[i].setsize(vamergeoffset[i]); } vc.clear(); } VARF(vacubemax, 64, 512, 256*256, allchanged()); VARF(vacubesize, 32, 128, 0x1000, allchanged()); VARF(vacubemin, 0, 128, 256*256, allchanged()); int updateva(cube *c, int cx, int cy, int cz, int size, int csi) { progress("recalculating geometry..."); static int faces[6]; int ccount = 0, cmergemax = vamergemax, chasmerges = vahasmerges; neighbourstack[++neighbourdepth] = c; loopi(8) // counting number of semi-solid/solid children cubes { int count = 0, childpos = varoot.length(); ivec o(i, cx, cy, cz, size); vamergemax = 0; vahasmerges = 0; if(c[i].ext && c[i].ext->va) { //count += vacubemax+1; // since must already have more then max cubes varoot.add(c[i].ext->va); if(c[i].ext->va->hasmerges&MERGE_ORIGIN) findmergedfaces(c[i], o, size, csi, csi); } else { if(c[i].children) count += updateva(c[i].children, o.x, o.y, o.z, size/2, csi-1); else if(!isempty(c[i]) || hasskyfaces(c[i], o.x, o.y, o.z, size, faces)) count++; int tcount = count + (csi <= MAXMERGELEVEL ? vamerges[csi].length() : 0); if(tcount > vacubemax || (tcount >= vacubemin && size >= vacubesize) || size == min(0x1000, worldsize/2)) { loadprogress = clamp(recalcprogress/float(allocnodes), 0.0f, 1.0f); setva(c[i], o.x, o.y, o.z, size, csi); if(c[i].ext && c[i].ext->va) { while(varoot.length() > childpos) { vtxarray *child = varoot.pop(); c[i].ext->va->children.add(child); child->parent = c[i].ext->va; } varoot.add(c[i].ext->va); if(vamergemax > size) { cmergemax = max(cmergemax, vamergemax); chasmerges |= vahasmerges&~MERGE_USE; } continue; } else count = 0; } } if(csi+1 <= MAXMERGELEVEL && vamerges[csi].length()) vamerges[csi+1].move(vamerges[csi]); cmergemax = max(cmergemax, vamergemax); chasmerges |= vahasmerges; ccount += count; } --neighbourdepth; vamergemax = cmergemax; vahasmerges = chasmerges; return ccount; } void addtjoint(const edgegroup &g, const cubeedge &e, int offset) { int vcoord = (g.slope[g.axis]*offset + g.origin[g.axis]) & 0x7FFF; tjoint &tj = tjoints.add(); tj.offset = vcoord / g.slope[g.axis]; tj.edge = e.index; int prev = -1, cur = ext(*e.c).tjoints; while(cur >= 0) { tjoint &o = tjoints[cur]; if(tj.edge < o.edge || (tj.edge==o.edge && (e.flags&CE_FLIP ? tj.offset > o.offset : tj.offset < o.offset))) break; prev = cur; cur = o.next; } tj.next = cur; if(prev < 0) e.c->ext->tjoints = tjoints.length()-1; else tjoints[prev].next = tjoints.length()-1; } void findtjoints(int cur, const edgegroup &g) { int active = -1; while(cur >= 0) { cubeedge &e = cubeedges[cur]; int prevactive = -1, curactive = active; while(curactive >= 0) { cubeedge &a = cubeedges[curactive]; if(a.offset+a.size <= e.offset) { if(prevactive >= 0) cubeedges[prevactive].next = a.next; else active = a.next; } else { prevactive = curactive; if(!(a.flags&CE_DUP)) { if(e.flags&CE_START && e.offset > a.offset && e.offset < a.offset+a.size) addtjoint(g, a, e.offset); if(e.flags&CE_END && e.offset+e.size > a.offset && e.offset+e.size < a.offset+a.size) addtjoint(g, a, e.offset+e.size); } if(!(e.flags&CE_DUP)) { if(a.flags&CE_START && a.offset > e.offset && a.offset < e.offset+e.size) addtjoint(g, e, a.offset); if(a.flags&CE_END && a.offset+a.size > e.offset && a.offset+a.size < e.offset+e.size) addtjoint(g, e, a.offset+a.size); } } curactive = a.next; } int next = e.next; e.next = active; active = cur; cur = next; } } void findtjoints() { recalcprogress = 0; gencubeedges(); tjoints.setsize(0); enumeratekt(edgegroups, edgegroup, g, int, e, findtjoints(e, g)); cubeedges.setsize(0); edgegroups.clear(); } void octarender() // creates va s for all leaf cubes that don't already have them { int csi = 0; while(1<explicitsky; skyarea += va->skyarea; } extern vtxarray *visibleva; visibleva = NULL; } void precachetextures() { vector texs; loopv(valist) { vtxarray *va = valist[i]; loopj(va->texs + va->blends) if(texs.find(va->eslist[j].texture) < 0) texs.add(va->eslist[j].texture); } loopv(texs) { loadprogress = float(i+1)/texs.length(); lookupvslot(texs[i]); } loadprogress = 0; } void allchanged(bool load) { renderprogress(0, "clearing vertex arrays..."); clearvas(worldroot); resetqueries(); resetclipplanes(); if(load) initenvmaps(); guessshadowdir(); entitiesinoctanodes(); tjoints.setsize(0); if(filltjoints) findtjoints(); octarender(); if(load) precachetextures(); setupmaterials(); invalidatepostfx(); updatevabbs(true); resetblobs(); if(load) { seedparticles(); genenvmaps(); drawminimap(); } } void recalc() { allchanged(true); } COMMAND(recalc, ""); sandboxgamemaker-2.7.1+dfsg/src/engine/octa.cpp0000664000175000017500000015535611654260372021365 0ustar showardshoward// core world management routines #include "engine.h" cube *worldroot = newcubes(F_SOLID); int allocnodes = 0; cubeext *growcubeext(cubeext *old, int maxverts) { cubeext *ext = (cubeext *)new uchar[sizeof(cubeext) + maxverts*sizeof(vertinfo)]; if(old) { ext->va = old->va; ext->ents = old->ents; ext->tjoints = old->tjoints; } else { ext->va = NULL; ext->ents = NULL; ext->tjoints = -1; } ext->maxverts = maxverts; return ext; } void setcubeext(cube &c, cubeext *ext) { cubeext *old = c.ext; if(old == ext) return; c.ext = ext; if(old) delete[] (uchar *)old; } cubeext *newcubeext(cube &c, int maxverts, bool init) { if(c.ext && c.ext->maxverts >= maxverts) return c.ext; cubeext *ext = growcubeext(c.ext, maxverts); if(init) { if(c.ext) { memcpy(ext->surfaces, c.ext->surfaces, sizeof(ext->surfaces)); memcpy(ext->verts(), c.ext->verts(), c.ext->maxverts*sizeof(vertinfo)); } else memset(ext->surfaces, 0, sizeof(ext->surfaces)); } setcubeext(c, ext); return ext; } cube *newcubes(uint face, int mat) { cube *c = new cube[8]; loopi(8) { c->children = NULL; c->ext = NULL; c->visible = 0; c->collide = 0; c->merged = 0; setfaces(*c, face); loopl(6) c->texture[l] = DEFAULT_GEOM; c->material = mat; c++; } allocnodes++; return c-8; } int familysize(cube &c) { int size = 1; if(c.children) loopi(8) size += familysize(c.children[i]); return size; } void freeocta(cube *c) { if(!c) return; loopi(8) discardchildren(c[i]); delete[] c; allocnodes--; } void freecubeext(cube &c) { if(c.ext) { delete[] (uchar *)c.ext; c.ext = NULL; } } void discardchildren(cube &c, bool fixtex, int depth) { c.visible = 0; c.collide = 0; c.merged = 0; if(c.ext) { if(c.ext->va) destroyva(c.ext->va); c.ext->va = NULL; c.ext->tjoints = -1; freeoctaentities(c); freecubeext(c); } if(c.children) { uint filled = F_EMPTY; loopi(8) { discardchildren(c.children[i], fixtex, depth+1); filled |= c.children[i].faces[0]; } if(fixtex) { loopi(6) c.texture[i] = getmippedtexture(c, i); if(depth > 0 && filled != F_EMPTY) c.faces[0] = F_SOLID; } DELETEA(c.children); allocnodes--; } } void getcubevector(cube &c, int d, int x, int y, int z, ivec &p) { ivec v(d, x, y, z); loopi(3) p[i] = edgeget(cubeedge(c, i, v[R[i]], v[C[i]]), v[D[i]]); } void setcubevector(cube &c, int d, int x, int y, int z, const ivec &p) { ivec v(d, x, y, z); loopi(3) edgeset(cubeedge(c, i, v[R[i]], v[C[i]]), v[D[i]], p[i]); } static inline void getcubevector(cube &c, int i, ivec &p) { p.x = edgeget(cubeedge(c, 0, (i>>R[0])&1, (i>>C[0])&1), (i>>D[0])&1); p.y = edgeget(cubeedge(c, 1, (i>>R[1])&1, (i>>C[1])&1), (i>>D[1])&1); p.z = edgeget(cubeedge(c, 2, (i>>R[2])&1, (i>>C[2])&1), (i>>D[2])&1); } static inline void setcubevector(cube &c, int i, const ivec &p) { edgeset(cubeedge(c, 0, (i>>R[0])&1, (i>>C[0])&1), (i>>D[0])&1, p.x); edgeset(cubeedge(c, 1, (i>>R[1])&1, (i>>C[1])&1), (i>>D[1])&1, p.y); edgeset(cubeedge(c, 2, (i>>R[2])&1, (i>>C[2])&1), (i>>D[2])&1, p.z); } void optiface(uchar *p, cube &c) { uint f = *(uint *)p; if(((f>>4)&0x0F0F0F0FU) == (f&0x0F0F0F0FU)) emptyfaces(c); } void printcube() { cube &c = lookupcube(lu.x, lu.y, lu.z); // assume this is cube being pointed at conoutf(CON_DEBUG, "= %p = (%d, %d, %d) @ %d", &c, lu.x, lu.y, lu.z, lusize); conoutf(CON_DEBUG, " x %.8x", c.faces[0]); conoutf(CON_DEBUG, " y %.8x", c.faces[1]); conoutf(CON_DEBUG, " z %.8x", c.faces[2]); } COMMAND(printcube, ""); bool isvalidcube(cube &c) { clipplanes p; genclipplanes(c, 0, 0, 0, 256, p); loopi(8) // test that cube is convex { vec v; calcvert(c, 0, 0, 0, 256, v, i); if(!pointincube(p, v)) return false; } return true; } void validatec(cube *c, int size) { loopi(8) { if(c[i].children) { if(size<=1) { solidfaces(c[i]); discardchildren(c[i], true); } else validatec(c[i].children, size>>1); } else if(size > 0x1000) { subdividecube(c[i], true, false); validatec(c[i].children, size>>1); } else { loopj(3) { uint f = c[i].faces[j], e0 = f&0x0F0F0F0FU, e1 = (f>>4)&0x0F0F0F0FU; if(e0 == e1 || ((e1+0x07070707U)|(e1-e0))&0xF0F0F0F0U) { emptyfaces(c[i]); break; } } } } } ivec lu; int lusize; cube &lookupcube(int tx, int ty, int tz, int tsize, ivec &ro, int &rsize) { tx = clamp(tx, 0, worldsize-1); ty = clamp(ty, 0, worldsize-1); tz = clamp(tz, 0, worldsize-1); int scale = worldscale-1, csize = abs(tsize); cube *c = &worldroot[octastep(tx, ty, tz, scale)]; if(!(csize>>scale)) do { if(!c->children) { if(tsize > 0) do { subdividecube(*c); scale--; c = &c->children[octastep(tx, ty, tz, scale)]; } while(!(csize>>scale)); break; } scale--; c = &c->children[octastep(tx, ty, tz, scale)]; } while(!(csize>>scale)); ro = ivec(tx, ty, tz).mask(~0<children) { scale--; c = &c->children[octastep(o.x, o.y, o.z, scale)]; } return c->material; } cube *neighbourstack[32]; int neighbourdepth = -1; cube &neighbourcube(cube &c, int orient, int x, int y, int z, int size, ivec &ro, int &rsize) { ivec n(x, y, z); int dim = dimension(orient); uint diff = n[dim]; if(dimcoord(orient)) n[dim] += size; else n[dim] -= size; diff ^= n[dim]; if(diff >= uint(worldsize)) { ro = n; rsize = size; return c; } int scale = worldscale; cube *nc = worldroot; if(neighbourdepth >= 0) { scale -= neighbourdepth + 1; diff >>= scale; do { scale++; diff >>= 1; } while(diff); nc = neighbourstack[worldscale - scale]; } scale--; nc = &nc[octastep(n.x, n.y, n.z, scale)]; if(!(size>>scale) && nc->children) do { scale--; nc = &nc->children[octastep(n.x, n.y, n.z, scale)]; } while(!(size>>scale) && nc->children); ro = n.mask(~0< DEFAULT_SKY) tex[x*2+y] = c[n].texture[orient]; } loopk(4) if(tex[k] > DEFAULT_SKY) return tex[k]; return DEFAULT_GEOM; } void forcemip(cube &c, bool fixtex) { cube *ch = c.children; emptyfaces(c); loopi(8) loopj(8) { int n = i^(j==3 ? 4 : (j==4 ? 3 : j)); if(!isempty(ch[n])) // breadth first search for cube near vert { ivec v; getcubevector(ch[n], i, v); // adjust vert to parent size setcubevector(c, i, ivec(n, v.x, v.y, v.z, 8).shr(1)); break; } } if(fixtex) loopj(6) c.texture[j] = getmippedtexture(c, j); } int midedge(const ivec &a, const ivec &b, int xd, int yd, bool &perfect) { int ax = a[xd], bx = b[xd]; int ay = a[yd], by = b[yd]; if(ay==by) return ay; if(ax==bx) { perfect = false; return ay; } bool crossx = (ax<8 && bx>8) || (ax>8 && bx<8); bool crossy = (ay<8 && by>8) || (ay>8 && by<8); if(crossy && !crossx) { midedge(a,b,yd,xd,perfect); return 8; } // to test perfection if(ax<=8 && bx<=8) return ax>bx ? ay : by; if(ax>=8 && bx>=8) return ax16)) perfect = false; return crossy ? 8 : min(max(y, 0), 16); } bool subdividecube(cube &c, bool fullcheck, bool brighten) { if(c.children) return true; if(c.ext) memset(c.ext->surfaces, 0, sizeof(c.ext->surfaces)); if(isempty(c) || isentirelysolid(c)) { c.children = newcubes(isempty(c) ? F_EMPTY : F_SOLID, c.material); loopi(8) { loopl(6) c.children[i].texture[l] = c.texture[l]; if(brighten && !isempty(c)) brightencube(c.children[i]); } return true; } cube *ch = c.children = newcubes(F_SOLID, c.material); bool perfect = true; ivec v[8]; loopi(8) { getcubevector(c, i, v[i]); v[i].mul(2); } loopj(6) { int d = dimension(j), z = dimcoord(j); const ivec &v00 = v[octaindex(d, 0, 0, z)], &v10 = v[octaindex(d, 1, 0, z)], &v01 = v[octaindex(d, 0, 1, z)], &v11 = v[octaindex(d, 1, 1, z)]; int e[3][3]; // corners e[0][0] = v00[d]; e[0][2] = v01[d]; e[2][0] = v10[d]; e[2][2] = v11[d]; // edges e[0][1] = midedge(v00, v01, C[d], d, perfect); e[1][0] = midedge(v00, v10, R[d], d, perfect); e[1][2] = midedge(v11, v01, R[d], d, perfect); e[2][1] = midedge(v11, v10, C[d], d, perfect); // center bool p1 = perfect, p2 = perfect; int c1 = midedge(v00, v11, R[d], d, p1); int c2 = midedge(v01, v10, R[d], d, p2); if(z ? c1 > c2 : c1 < c2) { e[1][1] = c1; perfect = p1 && (c1 == c2 || v00[C[d]] + v11[C[d]] == 16); } else { e[1][1] = c2; perfect = p2 && (c1 == c2 || v01[C[d]] + v10[C[d]] == 16); } loopi(8) { ch[i].texture[j] = c.texture[j]; int rd = (i>>R[d])&1, cd = (i>>C[d])&1, dd = (i>>D[d])&1; edgeset(cubeedge(ch[i], d, 0, 0), z, clamp(e[rd][cd] - dd*8, 0, 8)); edgeset(cubeedge(ch[i], d, 1, 0), z, clamp(e[1+rd][cd] - dd*8, 0, 8)); edgeset(cubeedge(ch[i], d, 0, 1), z, clamp(e[rd][1+cd] - dd*8, 0, 8)); edgeset(cubeedge(ch[i], d, 1, 1), z, clamp(e[1+rd][1+cd] - dd*8, 0, 8)); } } validatec(ch); if(fullcheck) loopi(8) if(!isvalidcube(ch[i])) // not so good... { emptyfaces(ch[i]); perfect=false; } if(brighten) loopi(8) if(!isempty(ch[i])) brightencube(ch[i]); return perfect; } bool crushededge(uchar e, int dc) { return dc ? e==0 : e==0x88; } int visibleorient(cube &c, int orient) { loopi(2) { int a = faceedgesidx[orient][i*2 + 0]; int b = faceedgesidx[orient][i*2 + 1]; loopj(2) { if(crushededge(c.edges[a],j) && crushededge(c.edges[b],j) && touchingface(c, orient)) return ((a>>2)<<1) + j; } } return orient; } VAR(mipvis, 0, 0, 1); static int remipprogress = 0, remiptotal = 0; bool remip(cube &c, int x, int y, int z, int size) { cube *ch = c.children; if(!ch) { if(size<<1 <= 0x1000) return true; subdividecube(c); ch = c.children; } else if((remipprogress++&0xFFF)==1) renderprogress(float(remipprogress)/remiptotal, "remipping..."); bool perfect = true; loopi(8) { ivec o(i, x, y, z, size); if(!remip(ch[i], o.x, o.y, o.z, size>>1)) perfect = false; } solidfaces(c); // so texmip is more consistent loopj(6) c.texture[j] = getmippedtexture(c, j); // parents get child texs regardless if(!perfect) return false; if(size<<1 > 0x1000) return false; uchar mat = MAT_AIR; loopi(8) { mat = ch[i].material; if((mat&MATF_CLIP) == MAT_NOCLIP || mat&MAT_ALPHA) { if(i > 0) return false; while(++i < 8) if(ch[i].material != mat) return false; break; } else if(!isentirelysolid(ch[i])) { while(++i < 8) { int omat = ch[i].material; if(isentirelysolid(ch[i]) ? (omat&MATF_CLIP) == MAT_NOCLIP || omat&MAT_ALPHA : mat != omat) return false; } break; } } cube n = c; n.ext = NULL; forcemip(n); n.children = NULL; if(!subdividecube(n, false, false)) { freeocta(n.children); return false; } cube *nh = n.children; uchar vis[6] = {0, 0, 0, 0, 0, 0}; loopi(8) { if(ch[i].faces[0] != nh[i].faces[0] || ch[i].faces[1] != nh[i].faces[1] || ch[i].faces[2] != nh[i].faces[2]) { freeocta(nh); return false; } if(isempty(ch[i]) && isempty(nh[i])) continue; ivec o(i, x, y, z, size); loop(orient, 6) if(visibleface(ch[i], orient, o.x, o.y, o.z, size, MAT_AIR, (mat&MAT_ALPHA)^MAT_ALPHA, MAT_ALPHA)) { if(ch[i].texture[orient] != n.texture[orient]) { freeocta(nh); return false; } vis[orient] |= 1<>1); remip(worldroot[i], o.x, o.y, o.z, worldsize>>2); } calcmerges(); if(!local) allchanged(); } void remip_() { mpremip(true); allchanged(); } COMMANDN(remip, remip_, ""); static inline int edgeval(cube &c, const ivec &p, int dim, int coord) { return edgeget(cubeedge(c, dim, p[R[dim]]>>3, p[C[dim]]>>3), coord); } void genvertp(cube &c, ivec &p1, ivec &p2, ivec &p3, plane &pl) { int dim = 0; if(p1.y==p2.y && p2.y==p3.y) dim = 1; else if(p1.z==p2.z && p2.z==p3.z) dim = 2; int coord = p1[dim]; ivec v1(p1), v2(p2), v3(p3); v1[D[dim]] = edgeval(c, p1, dim, coord); v2[D[dim]] = edgeval(c, p2, dim, coord); v3[D[dim]] = edgeval(c, p3, dim, coord); pl.toplane(v1.tovec(), v2.tovec(), v3.tovec()); } bool threeplaneintersect(plane &pl1, plane &pl2, plane &pl3, vec &dest) { vec &t1 = dest, t2, t3, t4; t1.cross(pl1, pl2); t4 = t1; t1.mul(pl3.offset); t2.cross(pl3, pl1); t2.mul(pl2.offset); t3.cross(pl2, pl3); t3.mul(pl1.offset); t1.add(t2); t1.add(t3); t1.mul(-1); float d = t4.dot(pl3); if(d==0) return false; t1.div(d); return true; } void genedgespanvert(ivec &p, cube &c, vec &v) { ivec p1(8-p.x, p.y, p.z); ivec p2(p.x, 8-p.y, p.z); ivec p3(p.x, p.y, 8-p.z); cube s; solidfaces(s); plane plane1, plane2, plane3; genvertp(c, p, p1, p2, plane1); genvertp(c, p, p2, p3, plane2); genvertp(c, p, p3, p1, plane3); if(plane1==plane2) genvertp(s, p, p1, p2, plane1); if(plane1==plane3) genvertp(s, p, p1, p2, plane1); if(plane2==plane3) genvertp(s, p, p2, p3, plane2); ASSERT(threeplaneintersect(plane1, plane2, plane3, v)); //ASSERT(v.x>=0 && v.x<=8); //ASSERT(v.y>=0 && v.y<=8); //ASSERT(v.z>=0 && v.z<=8); v.x = max(0.0f, min(8.0f, v.x)); v.y = max(0.0f, min(8.0f, v.y)); v.z = max(0.0f, min(8.0f, v.z)); } void edgespan2vectorcube(cube &c) { vec v; if(c.children) loopi(8) edgespan2vectorcube(c.children[i]); if(isentirelysolid(c) || isempty(c)) return; cube n = c; loop(x,2) loop(y,2) loop(z,2) { ivec p(8*x, 8*y, 8*z); genedgespanvert(p, c, v); edgeset(cubeedge(n, 0, y, z), x, int(v.x+0.49f)); edgeset(cubeedge(n, 1, z, x), y, int(v.y+0.49f)); edgeset(cubeedge(n, 2, x, y), z, int(v.z+0.49f)); } c = n; } void converttovectorworld() { conoutf(CON_WARN, "WARNING: old map, use savecurrentmap"); loopi(8) edgespan2vectorcube(worldroot[i]); } const ivec cubecoords[8] = // verts of bounding cube { ivec(8, 8, 0), ivec(0, 8, 0), ivec(0, 8, 8), ivec(8, 8, 8), ivec(8, 0, 8), ivec(0, 0, 8), ivec(0, 0, 0), ivec(8, 0, 0), }; template static inline void genfacevert(cube &c, int i, T &v) { #define GENFACEVERT(v, X, Y, Z) { \ v.x = edgeget(cubeedge(c, 0, Y, Z), X); \ v.y = edgeget(cubeedge(c, 1, Z, X), Y); \ v.z = edgeget(cubeedge(c, 2, X, Y), Z); \ } switch(i) { case 0: GENFACEVERT(v, 1, 1, 0); break; case 1: GENFACEVERT(v, 0, 1, 0); break; case 2: GENFACEVERT(v, 0, 1, 1); break; case 3: GENFACEVERT(v, 1, 1, 1); break; case 4: GENFACEVERT(v, 1, 0, 1); break; case 5: GENFACEVERT(v, 0, 0, 1); break; case 6: GENFACEVERT(v, 0, 0, 0); break; case 7: GENFACEVERT(v, 1, 0, 0); break; } } void genfaceverts(cube &c, int orient, ivec v[4]) { #define GENFACEVERTS(X0,Y0,Z0, X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3) { \ GENFACEVERT(v[0], X0, Y0, Z0); \ GENFACEVERT(v[1], X1, Y1, Z1); \ GENFACEVERT(v[2], X2, Y2, Z2); \ GENFACEVERT(v[3], X3, Y3, Z3); \ } switch(orient) { case 0: GENFACEVERTS(0,1,1, 0,1,0, 0,0,0, 0,0,1); break; case 1: GENFACEVERTS(1,1,1, 1,0,1, 1,0,0, 1,1,0); break; case 2: GENFACEVERTS(1,0,1, 0,0,1, 0,0,0, 1,0,0); break; case 3: GENFACEVERTS(0,1,0, 0,1,1, 1,1,1, 1,1,0); break; case 4: GENFACEVERTS(0,0,0, 0,1,0, 1,1,0, 1,0,0); break; case 5: GENFACEVERTS(0,0,1, 1,0,1, 1,1,1, 0,1,1); break; } } const ivec facecoords[6][4] = { { ivec(0,8,8), ivec(0,8,0), ivec(0,0,0), ivec(0,0,8) }, { ivec(8,8,8), ivec(8,0,8), ivec(8,0,0), ivec(8,8,0) }, { ivec(8,0,8), ivec(0,0,8), ivec(0,0,0), ivec(8,0,0) }, { ivec(0,8,0), ivec(0,8,8), ivec(8,8,8), ivec(8,8,0) }, { ivec(0,0,0), ivec(0,8,0), ivec(8,8,0), ivec(8,0,0) }, { ivec(0,0,8), ivec(8,0,8), ivec(8,8,8), ivec(0,8,8) }, }; const uchar fv[6][4] = // indexes for cubecoords, per each vert of a face orientation { { 2, 1, 6, 5 }, { 3, 4, 7, 0 }, { 4, 5, 6, 7 }, { 1, 2, 3, 0 }, { 6, 1, 0, 7 }, { 5, 4, 3, 2 }, }; const uchar fvmasks[64] = // mask of verts used given a mask of visible face orientations { 0x00, 0x66, 0x99, 0xFF, 0xF0, 0xF6, 0xF9, 0xFF, 0x0F, 0x6F, 0x9F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC3, 0xE7, 0xDB, 0xFF, 0xF3, 0xF7, 0xFB, 0xFF, 0xCF, 0xEF, 0xDF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3C, 0x7E, 0xBD, 0xFF, 0xFC, 0xFE, 0xFD, 0xFF, 0x3F, 0x7F, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; const uchar faceedgesidx[6][4] = // ordered edges surrounding each orient {//0..1 = row edges, 2..3 = column edges { 4, 5, 8, 10 }, { 6, 7, 9, 11 }, { 8, 9, 0, 2 }, { 10, 11, 1, 3 }, { 0, 1, 4, 6 }, { 2, 3, 5, 7 }, }; bool flataxisface(cube &c, int orient) { uint face = c.faces[dimension(orient)]; if(dimcoord(orient)) face >>= 4; return (face&0x0F0F0F0F) == 0x01010101*(face&0x0F); } bool collideface(cube &c, int orient) { if(flataxisface(c, orient)) { uchar r1 = c.edges[faceedgesidx[orient][0]], r2 = c.edges[faceedgesidx[orient][1]]; if(uchar((r1>>4)|(r2&0xF0)) == uchar((r1&0x0F)|(r2<<4))) return false; uchar c1 = c.edges[faceedgesidx[orient][2]], c2 = c.edges[faceedgesidx[orient][3]]; if(uchar((c1>>4)|(c2&0xF0)) == uchar((c1&0x0F)|(c2<<4))) return false; } return true; } bool touchingface(cube &c, int orient) { uint face = c.faces[dimension(orient)]; return dimcoord(orient) ? (face&0xF0F0F0F0)==0x80808080 : (face&0x0F0F0F0F)==0; } bool notouchingface(cube &c, int orient) { uint face = c.faces[dimension(orient)]; return dimcoord(orient) ? (face&0x80808080)==0 : ((0x88888888-face)&0x08080808) == 0; } int faceconvexity(ivec v[4]) { ivec n; n.cross(ivec(v[1]).sub(v[0]), ivec(v[2]).sub(v[0])); return ivec(v[0]).sub(v[3]).dot(n); // 1 if convex, -1 if concave, 0 if flat } int faceconvexity(vertinfo *verts, int numverts) { if(numverts < 4) return 0; ivec v[4] = { verts[0].getxyz(), verts[1].getxyz(), verts[2].getxyz(), verts[3].getxyz() }; return faceconvexity(v); } int faceconvexity(ivec v[4], int &vis) { ivec e1, e2, e3, n; n.cross((e1 = v[1]).sub(v[0]), (e2 = v[2]).sub(v[0])); int convex = (e3 = v[0]).sub(v[3]).dot(n); if(!convex) { if(ivec().cross(e3, e2).iszero()) { if(!n.iszero()) vis = 1; } else if(n.iszero()) { vis = 2; } return 0; } return convex; } int faceconvexity(cube &c, int orient) { if(flataxisface(c, orient)) return 0; ivec v[4]; genfaceverts(c, orient, v); return faceconvexity(v); } int faceorder(cube &c, int orient) // gets above 'fv' so that each face is convex { return faceconvexity(c, orient)<0 ? 1 : 0; } static inline void faceedges(const cube &c, int orient, uchar edges[4]) { loopk(4) edges[k] = c.edges[faceedgesidx[orient][k]]; } uint faceedges(cube &c, int orient) { union { uchar edges[4]; uint face; } u; faceedges(c, orient, u.edges); return u.face; } struct facevec { int x, y; facevec() {} facevec(int x, int y) : x(x), y(y) {} bool operator==(const facevec &f) const { return x == f.x && y == f.y; } bool operator!=(const facevec &f) const { return x != f.x || y != f.y; } }; static inline int genfacevecs(cube &cu, int orient, const ivec &pos, int size, bool solid, facevec *fvecs, const ivec *v = NULL) { int dim = dimension(orient), coord = dimcoord(orient), c = C[dim], r = R[dim], winding = coord ? 0 : 3, touching = 0; ivec buf[4]; if(solid) { loopi(4) { const ivec &cc = facecoords[orient][i^winding]; fvecs[i] = facevec(cc[c]*size + (pos[c]<<3), cc[r]*size + (pos[r]<<3)); } return 4; } if(!v) { genfaceverts(cu, orient, buf); v = buf; } facevec prev(INT_MAX, INT_MAX); loopi(4) { const ivec &cc = v[i^winding]; if(cc[dim] == coord*8) { fvecs[touching] = facevec(cc[c]*size + (pos[c]<<3), cc[r]*size + (pos[r]<<3)); if(fvecs[touching] != prev) prev = fvecs[touching++]; } } if(fvecs[0] == prev) touching--; return touching; } static inline int clipfacevecy(const facevec &o, const facevec &dir, int cx, int cy, int size, facevec &r) { if(dir.x >= 0) { if(cx <= o.x || cx >= o.x+dir.x) return 0; } else if(cx <= o.x+dir.x || cx >= o.x) return 0; int t = (o.y-cy) + (cx-o.x)*dir.y/dir.x; if(t <= 0 || t >= size) return 0; r.x = cx; r.y = cy + t; return 1; } static inline int clipfacevecx(const facevec &o, const facevec &dir, int cx, int cy, int size, facevec &r) { if(dir.y >= 0) { if(cy <= o.y || cy >= o.y+dir.y) return 0; } else if(cy <= o.y+dir.y || cy >= o.y) return 0; int t = (o.x-cx) + (cy-o.y)*dir.x/dir.y; if(t <= 0 || t >= size) return 0; r.x = cx + t; r.y = cy; return 1; } static inline int clipfacevec(const facevec &o, const facevec &dir, int cx, int cy, int size, facevec *rvecs) { int r = 0; if(o.x >= cx && o.x <= cx+size && o.y >= cy && o.y <= cy+size && ((o.x != cx && o.x != cx+size) || (o.y != cy && o.y != cy+size))) { rvecs[0].x = o.x; rvecs[0].y = o.y; r++; } r += clipfacevecx(o, dir, cx, cy, size, rvecs[r]); r += clipfacevecx(o, dir, cx, cy+size, size, rvecs[r]); r += clipfacevecy(o, dir, cx, cy, size, rvecs[r]); r += clipfacevecy(o, dir, cx+size, cy, size, rvecs[r]); ASSERT(r <= 2); return r; } static inline bool insideface(const facevec *p, int nump, const facevec *o, int numo) { int bounds = 0; facevec prev = o[numo-1]; loopi(numo) { const facevec &cur = o[i]; facevec dir(cur.x-prev.x, cur.y-prev.y); int offset = dir.x*prev.y - dir.y*prev.x; loopj(nump) if(dir.x*p[j].y - dir.y*p[j].x > offset) return false; bounds++; prev = cur; } return bounds>=3; } static inline int clipfacevecs(const facevec *o, int numo, int cx, int cy, int size, facevec *rvecs) { cx <<= 3; cy <<= 3; size <<= 3; int r = 0; facevec prev = o[numo-1]; loopi(numo) { const facevec &cur = o[i]; r += clipfacevec(prev, facevec(cur.x-prev.x, cur.y-prev.y), cx, cy, size, &rvecs[r]); prev = cur; } facevec corner[4] = {facevec(cx, cy), facevec(cx+size, cy), facevec(cx+size, cy+size), facevec(cx, cy+size)}; loopi(4) if(insideface(&corner[i], 1, o, numo)) rvecs[r++] = corner[i]; ASSERT(r <= 8); return r; } bool collapsedface(cube &c, int orient) { int e0 = c.edges[faceedgesidx[orient][0]], e1 = c.edges[faceedgesidx[orient][1]], e2 = c.edges[faceedgesidx[orient][2]], e3 = c.edges[faceedgesidx[orient][3]], face = dimension(orient)*4, f0 = c.edges[face+0], f1 = c.edges[face+1], f2 = c.edges[face+2], f3 = c.edges[face+3]; if(dimcoord(orient)) { f0 >>= 4; f1 >>= 4; f2 >>= 4; f3 >>= 4; } else { f0 &= 0xF; f1 &= 0xF; f2 &= 0xF; f3 &= 0xF; } ivec v0(e0&0xF, e2&0xF, f0), v1(e0>>4, e3&0xF, f1), v2(e1>>4, e3>>4, f3), v3(e1&0xF, e2>>4, f2); return ivec().cross(v1.sub(v0), v2.sub(v0)).iszero() && ivec().cross(v2, v3.sub(v0)).iszero(); } static inline bool occludesface(cube &c, int orient, const ivec &o, int size, const ivec &vo, int vsize, uchar vmat, uchar nmat, uchar matmask, const facevec *vf, int numv) { int dim = dimension(orient); if(!c.children) { if(nmat != MAT_AIR && (c.material&matmask) == nmat) { facevec nf[8]; return clipfacevecs(vf, numv, o[C[dim]], o[R[dim]], size, nf) < 3; } if(isentirelysolid(c)) return true; if(vmat != MAT_AIR && ((c.material&matmask) == vmat || (isliquid(vmat) && isclipped(c.material&MATF_VOLUME)))) return true; if(touchingface(c, orient) && faceedges(c, orient) == F_SOLID) return true; facevec cf[8]; int numc = clipfacevecs(vf, numv, o[C[dim]], o[R[dim]], size, cf); if(numc < 3) return true; if(isempty(c) || notouchingface(c, orient)) return false; facevec of[4]; int numo = genfacevecs(c, orient, o, size, false, of); return numo >= 3 && insideface(cf, numc, of, numo); } size >>= 1; int coord = dimcoord(orient); loopi(8) if(octacoord(dim, i) == coord) { if(!occludesface(c.children[i], orient, ivec(i, o.x, o.y, o.z, size), size, vo, vsize, vmat, nmat, matmask, vf, numv)) return false; } return true; } bool visibleface(cube &c, int orient, int x, int y, int z, int size, uchar mat, uchar nmat, uchar matmask) { if(mat != MAT_AIR) { if(faceedges(c, orient)==F_SOLID && touchingface(c, orient)) return false; } else { if(collapsedface(c, orient)) return false; if(!touchingface(c, orient)) return true; } ivec no; int nsize; cube &o = neighbourcube(c, orient, x, y, z, size, no, nsize); if(&o==&c) return false; int opp = opposite(orient); if(nsize > size || (nsize == size && !o.children)) { if(nmat != MAT_AIR && (o.material&matmask) == nmat) return true; if(isentirelysolid(o)) return false; if(mat != MAT_AIR && ((o.material&matmask) == mat || (isliquid(mat) && (o.material&MATF_VOLUME) == MAT_GLASS))) return false; if(isempty(o) || notouchingface(o, opp)) return true; if(touchingface(o, opp) && faceedges(o, opp) == F_SOLID) return false; ivec vo(x, y, z); vo.mask(0xFFF); no.mask(0xFFF); facevec cf[4], of[4]; int numc = genfacevecs(c, orient, vo, size, mat != MAT_AIR, cf), numo = genfacevecs(o, opp, no, nsize, false, of); return numo < 3 || !insideface(cf, numc, of, numo); } ivec vo(x, y, z); vo.mask(0xFFF); no.mask(0xFFF); facevec cf[4]; int numc = genfacevecs(c, orient, vo, size, mat != MAT_AIR, cf); return !occludesface(o, opp, no, nsize, vo, size, mat, nmat, matmask, cf, numc); } // more expensive version that checks both triangles of a face independently int visibletris(cube &c, int orient, int x, int y, int z, int size, uchar nmat, uchar matmask) { int vis = 3, touching = 0xF; ivec v[4], e1, e2, e3, n; genfaceverts(c, orient, v); n.cross((e1 = v[1]).sub(v[0]), (e2 = v[2]).sub(v[0])); int convex = (e3 = v[0]).sub(v[3]).dot(n); if(!convex) { if(ivec().cross(e3, e2).iszero()) { if(n.iszero()) return 0; vis = 1; touching = 0xF&~(1<<3); } else if(n.iszero()) { vis = 2; touching = 0xF&~(1<<1); } } int dim = dimension(orient), coord = dimcoord(orient); if(v[0][dim] != coord*8) touching &= ~(1<<0); if(v[1][dim] != coord*8) touching &= ~(1<<1); if(v[2][dim] != coord*8) touching &= ~(1<<2); if(v[3][dim] != coord*8) touching &= ~(1<<3); static const int notouchmasks[2][16] = // mask of triangles not touching { // order 0: flat or convex // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 1, 3, 0 }, // order 1: concave { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 2, 0 }, }; int order = convex < 0 ? 1 : 0, notouch = notouchmasks[order][touching]; if((vis¬ouch)==vis) return vis; ivec no; int nsize; cube &o = neighbourcube(c, orient, x, y, z, size, no, nsize); if(&o==&c) return 0; if(matmask == MAT_AIR) { nmat = c.material&MAT_ALPHA ? MAT_AIR : MAT_ALPHA; matmask = MAT_ALPHA; } ivec vo(x, y, z); vo.mask(0xFFF); no.mask(0xFFF); facevec cf[4], of[4]; int opp = opposite(orient), numo = 0, numc; if(nsize > size || (nsize == size && !o.children)) { if(isempty(c) || notouchingface(o, opp)) return vis; if(nmat != MAT_AIR && (o.material&matmask) == nmat) return vis; if(isentirelysolid(o) || (touchingface(o, opp) && faceedges(o, opp) == F_SOLID)) return vis¬ouch; numc = genfacevecs(c, orient, vo, size, false, cf, v); numo = genfacevecs(o, opp, no, nsize, false, of); if(numo < 3) return vis; if(insideface(cf, numc, of, numo)) return vis¬ouch; } else { numc = genfacevecs(c, orient, vo, size, false, cf, v); if(occludesface(o, opp, no, nsize, vo, size, MAT_AIR, nmat, matmask, cf, numc)) return vis¬ouch; } if(vis != 3 || notouch) return vis; static const int triverts[2][2][2][3] = { // order { // coord { { 1, 2, 3 }, { 0, 1, 3 } }, // verts { { 0, 1, 2 }, { 0, 2, 3 } } }, { // coord { { 0, 1, 2 }, { 3, 0, 2 } }, // verts { { 1, 2, 3 }, { 1, 3, 0 } } } }; do { loopi(2) { const int *verts = triverts[order][coord][i]; facevec tf[3] = { cf[verts[0]], cf[verts[1]], cf[verts[2]] }; if(numo > 0) { if(!insideface(tf, 3, of, numo)) continue; } else if(!occludesface(o, opp, no, nsize, vo, size, MAT_AIR, nmat, matmask, tf, 3)) continue; return vis & ~(1<=8) v.mul(size/8); else v.div(8/size); v.add(ivec(x, y, z).shl(3)); } void calcvert(cube &c, int x, int y, int z, int size, vec &v, int i, bool solid) { if(solid) v = cubecoords[i].tovec(); else genfacevert(c, i, v); v.mul(size/8.0f).add(vec(x, y, z)); } int genclipplane(cube &c, int orient, vec *v, plane *clip) { int planes = 0, convex = faceconvexity(c, orient), order = convex < 0 ? 1 : 0; const vec &v0 = v[fv[orient][order]], &v1 = v[fv[orient][order+1]], &v2 = v[fv[orient][order+2]], &v3 = v[fv[orient][(order+3)&3]]; if(v0==v2) return 0; if(v0!=v1 && v1!=v2) clip[planes++].toplane(v0, v1, v2); if(v0!=v3 && v2!=v3 && (!planes || convex)) clip[planes++].toplane(v0, v2, v3); return planes; } void genclipplanes(cube &c, int x, int y, int z, int size, clipplanes &p) { // generate tight bounding box calcvert(c, x, y, z, size, p.v[0], 0); vec mx = p.v[0], mn = p.v[0]; for(int i = 1; i < 8; i++) { calcvert(c, x, y, z, size, p.v[i], i); mx.max(p.v[i]); mn.min(p.v[i]); } p.r = mx.sub(mn).mul(0.5f); p.o = mn.add(p.r); p.size = 0; p.visible = 0; loopi(6) if(c.collide&(1< y.v2) return false; if(x.u1 < y.u1) return true; if(x.u1 > y.u1) return false; return false; } static int mergefacev(int orient, facebounds *m, int sz, facebounds &n) { for(int i = sz-1; i >= 0; --i) { if(m[i].v2 < n.v1) break; if(m[i].v2 == n.v1 && m[i].u1 == n.u1 && m[i].u2 == n.u2) { n.v1 = m[i].v1; memmove(&m[i], &m[i+1], (sz - (i+1)) * sizeof(facebounds)); return 1; } } return 0; } static int mergefaceu(int orient, facebounds &m, facebounds &n) { if(m.v1 == n.v1 && m.v2 == n.v2 && m.u2 == n.u1) { n.u1 = m.u1; return 1; } return 0; } static int mergeface(int orient, facebounds *m, int sz, facebounds &n) { for(bool merged = false; sz; merged = true) { int vmerged = mergefacev(orient, m, sz, n); sz -= vmerged; if(!vmerged && merged) break; if(!sz) break; int umerged = mergefaceu(orient, m[sz-1], n); sz -= umerged; if(!umerged) break; } m[sz++] = n; return sz; } int mergefaces(int orient, facebounds *m, int sz) { quicksort(m, sz, mergefacecmp); int nsz = 0; loopi(sz) nsz = mergeface(orient, m, nsz, m[i]); return nsz; } struct cfkey { uchar orient, material; ushort tex; ivec n; int offset; }; static inline bool htcmp(const cfkey &x, const cfkey &y) { return x.orient == y.orient && x.tex == y.tex && x.n == y.n && x.offset == y.offset && x.material==y.material; } static inline uint hthash(const cfkey &k) { return hthash(k.n)^k.offset^k.tex^k.orient^k.material; } void mincubeface(cube &cu, int orient, const ivec &o, int size, const facebounds &orig, facebounds &cf, uchar nmat, uchar matmask) { int dim = dimension(orient); if(cu.children) { size >>= 1; int coord = dimcoord(orient); loopi(8) if(octacoord(dim, i) == coord) mincubeface(cu.children[i], orient, ivec(i, o.x, o.y, o.z, size), size, orig, cf, nmat, matmask); return; } int c = C[dim], r = R[dim]; ushort uco = (o[c]&0xFFF)<<3, vco = (o[r]&0xFFF)<<3; ushort uc1 = uco, vc1 = vco, uc2 = ushort(size<<3)+uco, vc2 = ushort(size<<3)+vco; uc1 = max(uc1, orig.u1); uc2 = min(uc2, orig.u2); vc1 = max(vc1, orig.v1); vc2 = min(vc2, orig.v2); if(!isempty(cu) && touchingface(cu, orient) && !(nmat!=MAT_AIR && (cu.material&matmask)==nmat)) { uchar r1 = cu.edges[faceedgesidx[orient][0]], r2 = cu.edges[faceedgesidx[orient][1]], c1 = cu.edges[faceedgesidx[orient][2]], c2 = cu.edges[faceedgesidx[orient][3]]; ushort u1 = max(c1&0xF, c2&0xF)*size+uco, u2 = min(c1>>4, c2>>4)*size+uco, v1 = max(r1&0xF, r2&0xF)*size+vco, v2 = min(r1>>4, r2>>4)*size+vco; u1 = max(u1, orig.u1); u2 = min(u2, orig.u2); v1 = max(v1, orig.v1); v2 = min(v2, orig.v2); if(v2-v1==vc2-vc1) { if(u2-u1==uc2-uc1) return; if(u1==uc1) uc1 = u2; if(u2==uc2) uc2 = u1; } else if(u2-u1==uc2-uc1) { if(v1==vc1) vc1 = v2; if(v2==vc2) vc2 = v1; } } if(uc1==uc2 || vc1==vc2) return; cf.u1 = min(cf.u1, uc1); cf.u2 = max(cf.u2, uc2); cf.v1 = min(cf.v1, vc1); cf.v2 = max(cf.v2, vc2); } bool mincubeface(cube &cu, int orient, const ivec &co, int size, facebounds &orig) { ivec no; int nsize; cube &nc = neighbourcube(cu, orient, co.x, co.y, co.z, size, no, nsize); facebounds mincf; mincf.u1 = orig.u2; mincf.u2 = orig.u1; mincf.v1 = orig.v2; mincf.v2 = orig.v1; mincubeface(nc, opposite(orient), no, nsize, orig, mincf, cu.material&MAT_ALPHA ? MAT_AIR : MAT_ALPHA, MAT_ALPHA); bool smaller = false; if(mincf.u1 > orig.u1) { orig.u1 = mincf.u1; smaller = true; } if(mincf.u2 < orig.u2) { orig.u2 = mincf.u2; smaller = true; } if(mincf.v1 > orig.v1) { orig.v1 = mincf.v1; smaller = true; } if(mincf.v2 < orig.v2) { orig.v2 = mincf.v2; smaller = true; } return smaller; } VAR(maxmerge, 0, 6, 12); VAR(minface, 0, 4, 12); struct pvert { ushort x, y; pvert() {} pvert(ushort x, ushort y) : x(x), y(y) {} bool operator==(const pvert &o) const { return x == o.x && y == o.y; } bool operator!=(const pvert &o) const { return x != o.x || y != o.y; } }; struct pedge { pvert from, to; pedge() {} pedge(const pvert &from, const pvert &to) : from(from), to(to) {} bool operator==(const pedge &o) const { return from == o.from && to == o.to; } bool operator!=(const pedge &o) const { return from != o.from || to != o.to; } }; static inline uint hthash(const pedge &x) { return uint(x.from.x)^(uint(x.from.y)<<8); } static inline bool htcmp(const pedge &x, const pedge &y) { return x == y; } struct poly { cube *c; int numverts; bool merged; pvert verts[MAXFACEVERTS]; }; bool clippoly(poly &p, const facebounds &b) { pvert verts1[MAXFACEVERTS+4], verts2[MAXFACEVERTS+4]; int numverts1 = 0, numverts2 = 0, px = p.verts[p.numverts-1].x, py = p.verts[p.numverts-1].y; loopi(p.numverts) { int x = p.verts[i].x, y = p.verts[i].y; if(x < b.u1) { if(px > b.u2) verts1[numverts1++] = pvert(b.u2, y + ((y - py)*(b.u2 - x))/(x - px)); if(px > b.u1) verts1[numverts1++] = pvert(b.u1, y + ((y - py)*(b.u1 - x))/(x - px)); } else if(x > b.u2) { if(px < b.u1) verts1[numverts1++] = pvert(b.u1, y + ((y - py)*(b.u1 - x))/(x - px)); if(px < b.u2) verts1[numverts1++] = pvert(b.u2, y + ((y - py)*(b.u2 - x))/(x - px)); } else { if(px < b.u1) { if(x > b.u1) verts1[numverts1++] = pvert(b.u1, y + ((y - py)*(b.u1 - x))/(x - px)); } else if(px > b.u2 && x < b.u2) verts1[numverts1++] = pvert(b.u2, y + ((y - py)*(b.u2 - x))/(x - px)); verts1[numverts1++] = pvert(x, y); } px = x; py = y; } if(numverts1 < 3) return false; px = verts1[numverts1-1].x; py = verts1[numverts1-1].y; loopi(numverts1) { int x = verts1[i].x, y = verts1[i].y; if(y < b.v1) { if(py > b.v2) verts2[numverts2++] = pvert(x + ((x - px)*(b.v2 - y))/(y - py), b.v2); if(py > b.v1) verts2[numverts2++] = pvert(x + ((x - px)*(b.v1 - y))/(y - py), b.v1); } else if(y > b.v2) { if(py < b.v1) verts2[numverts2++] = pvert(x + ((x - px)*(b.v1 - y))/(y - py), b.v1); if(py < b.v2) verts2[numverts2++] = pvert(x + ((x - px)*(b.v2 - y))/(y - py), b.v2); } else { if(py < b.v1) { if(y > b.v1) verts2[numverts2++] = pvert(x + ((x - px)*(b.v1 - y))/(y - py), b.v1); } else if(py > b.v2 && y < b.v2) verts2[numverts2++] = pvert(x + ((x - px)*(b.v2 - y))/(y - py), b.v2); verts2[numverts2++] = pvert(x, y); } px = x; py = y; } if(numverts2 < 3) return false; if(numverts2 > MAXFACEVERTS) return false; memcpy(p.verts, verts2, numverts2*sizeof(pvert)); p.numverts = numverts2; return true; } bool genpoly(cube &cu, int orient, const ivec &o, int size, int vis, ivec &n, int &offset, poly &p) { int dim = dimension(orient), coord = dimcoord(orient); ivec v[4]; genfaceverts(cu, orient, v); if(flataxisface(cu, orient)) { n = ivec(0, 0, 0); n[dim] = coord ? 1 : -1; } else { if(faceconvexity(v)) return false; n.cross(ivec(v[1]).sub(v[0]), ivec(v[2]).sub(v[0])); if(n.iszero()) n.cross(ivec(v[2]).sub(v[0]), ivec(v[3]).sub(v[0])); reduceslope(n); } ivec po = ivec(o).mask(0xFFF).shl(3); loopk(4) v[k].mul(size).add(po); offset = -n.dot(v[3]); int r = R[dim], c = C[dim], order = vis&4 ? 1 : 0; p.numverts = 0; if(coord) { const ivec &v0 = v[order]; p.verts[p.numverts++] = pvert(v0[c], v0[r]); if(vis&1) { const ivec &v1 = v[order+1]; p.verts[p.numverts++] = pvert(v1[c], v1[r]); } const ivec &v2 = v[order+2]; p.verts[p.numverts++] = pvert(v2[c], v2[r]); if(vis&2) { const ivec &v3 = v[(order+3)&3]; p.verts[p.numverts++] = pvert(v3[c], v3[r]); } } else { if(vis&2) { const ivec &v3 = v[(order+3)&3]; p.verts[p.numverts++] = pvert(v3[c], v3[r]); } const ivec &v2 = v[order+2]; p.verts[p.numverts++] = pvert(v2[c], v2[r]); if(vis&1) { const ivec &v1 = v[order+1]; p.verts[p.numverts++] = pvert(v1[c], v1[r]); } const ivec &v0 = v[order]; p.verts[p.numverts++] = pvert(v0[c], v0[r]); } if(faceedges(cu, orient)!=F_SOLID) { int px = int(p.verts[p.numverts-2].x) - int(p.verts[p.numverts-3].x), py = int(p.verts[p.numverts-2].y) - int(p.verts[p.numverts-3].y), cx = int(p.verts[p.numverts-1].x) - int(p.verts[p.numverts-2].x), cy = int(p.verts[p.numverts-1].y) - int(p.verts[p.numverts-2].y), dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) { if(p.numverts < 4) return false; p.verts[p.numverts-2] = p.verts[p.numverts-1]; p.numverts--; } px = cx; py = cy; cx = int(p.verts[0].x) - int(p.verts[p.numverts-1].x); cy = int(p.verts[0].y) - int(p.verts[p.numverts-1].y); dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) { if(p.numverts < 4) return false; p.numverts--; } px = cx; py = cy; cx = int(p.verts[1].x) - int(p.verts[0].x); cy = int(p.verts[1].y) - int(p.verts[0].y); dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) { if(p.numverts < 4) return false; p.verts[0] = p.verts[p.numverts-1]; p.numverts--; } px = cx; py = cy; cx = int(p.verts[2].x) - int(p.verts[1].x); cy = int(p.verts[2].y) - int(p.verts[1].y); dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) { if(p.numverts < 4) return false; p.verts[1] = p.verts[2]; p.verts[2] = p.verts[3]; p.numverts--; } } p.c = &cu; p.merged = false; if(minface && size >= 1< &links, vector &queue, int owner, poly &p, poly &q, const pedge &e) { int pe = -1, qe = -1; loopi(p.numverts) if(p.verts[i] == e.from) { pe = i; break; } loopi(q.numverts) if(q.verts[i] == e.to) { qe = i; break; } if(pe < 0 || qe < 0) return false; if(p.verts[(pe+1)%p.numverts] != e.to || q.verts[(qe+1)%q.numverts] != e.from) return false; /* * c----d * | | * F----T * | P | * b----a */ pvert verts[2*MAXFACEVERTS]; int numverts = 0, index = pe+2; // starts at A = T+1, ends at F = T+p.numverts loopi(p.numverts-1) { if(index >= p.numverts) index -= p.numverts; verts[numverts++] = p.verts[index++]; } index = qe+2; // starts at C = T+2 = F+1, ends at T = T+q.numverts int px = int(verts[numverts-1].x) - int(verts[numverts-2].x), py = int(verts[numverts-1].y) - int(verts[numverts-2].y); loopi(q.numverts-1) { if(index >= q.numverts) index -= q.numverts; pvert &src = q.verts[index++]; int cx = int(src.x) - int(verts[numverts-1].x), cy = int(src.y) - int(verts[numverts-1].y), dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) numverts--; verts[numverts++] = src; px = cx; py = cy; } int cx = int(verts[0].x) - int(verts[numverts-1].x), cy = int(verts[0].y) - int(verts[numverts-1].y), dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) numverts--; if(numverts > MAXFACEVERTS) return false; q.merged = true; q.numverts = 0; p.merged = true; p.numverts = numverts; memcpy(p.verts, verts, numverts*sizeof(pvert)); int prev = p.numverts-1; loopj(p.numverts) { pedge e(p.verts[prev], p.verts[j]); int order = e.from.x > e.to.x || (e.from.x == e.to.x && e.from.y > e.to.y) ? 1 : 0; if(order) swap(e.from, e.to); plink &l = links.access(e, e); bool shouldqueue = l.polys[order] < 0 && l.polys[order^1] >= 0; l.polys[order] = owner; if(shouldqueue) queue.add(&l); prev = j; } return true; } void addmerge(cube &cu, int orient, const ivec &co, const ivec &n, int offset, poly &p) { cu.merged |= 1<surfaces[orient] = ambientsurface; return; } surfaceinfo surf = brightsurface; vertinfo verts[MAXFACEVERTS]; surf.numverts |= p.numverts; int dim = dimension(orient), coord = dimcoord(orient), c = C[dim], r = R[dim]; loopk(p.numverts) { pvert &src = p.verts[coord ? k : p.numverts-1-k]; vertinfo &dst = verts[k]; ivec v; v[c] = src.x; v[r] = src.y; v[dim] = -(offset + n[c]*src.x + n[r]*src.y)/n[dim]; dst.set(v); } if(cu.ext) { const surfaceinfo &oldsurf = cu.ext->surfaces[orient]; int numverts = oldsurf.numverts&MAXFACEVERTS; if(numverts == p.numverts) { const vertinfo *oldverts = cu.ext->verts() + oldsurf.verts; loopk(numverts) if(verts[k].getxyz() != oldverts[k].getxyz()) goto nomatch; return; nomatch:; } } setsurface(cu, orient, surf, verts, p.numverts); } static inline void clearmerge(cube &c, int orient) { if(c.merged&(1<surfaces[orient] = brightsurface; } } void addmerges(int orient, const ivec &co, const ivec &n, int offset, vector &polys) { loopv(polys) { poly &p = polys[i]; if(p.merged) addmerge(*p.c, orient, co, n, offset, p); else clearmerge(*p.c, orient); } } void mergepolys(int orient, const ivec &co, const ivec &n, int offset, vector &polys) { if(polys.length() <= 1) { addmerges(orient, co, n, offset, polys); return; } hashset links(polys.length() <= 32 ? 128 : 1024); vector queue; loopv(polys) { poly &p = polys[i]; int prev = p.numverts-1; loopj(p.numverts) { pedge e(p.verts[prev], p.verts[j]); int order = e.from.x > e.to.x || (e.from.x == e.to.x && e.from.y > e.to.y) ? 1 : 0; if(order) swap(e.from, e.to); plink &l = links.access(e, e); l.polys[order] = i; if(l.polys[0] >= 0 && l.polys[1] >= 0) queue.add(&l); prev = j; } } vector nextqueue; while(queue.length()) { loopv(queue) { plink &l = *queue[i]; if(l.polys[0] >= 0 && l.polys[1] >= 0) mergepolys(orient, links, nextqueue, l.polys[0], polys[l.polys[0]], polys[l.polys[1]], l); } queue.setsize(0); queue.move(nextqueue); } addmerges(orient, co, n, offset, polys); } static int genmergeprogress = 0; struct cfpolys { vector polys; }; static hashtable cpolys; void genmerges(cube *c = worldroot, const ivec &o = ivec(0, 0, 0), int size = worldsize>>1) { if((genmergeprogress++&0xFFF)==0) renderprogress(float(genmergeprogress)/allocnodes, "merging faces..."); neighbourstack[++neighbourdepth] = c; loopi(8) { ivec co(i, o.x, o.y, o.z, size); int vis; if(c[i].children) genmerges(c[i].children, co, size>>1); else if(!isempty(c[i])) loopj(6) if((vis = visibletris(c[i], j, co.x, co.y, co.z, size))) { cfkey k; poly p; if(size < 1<= 1<= x2 && mo.y <= y1 && mo.y + (1<= y2 && mo.z <= z1 && mo.z + (1<= z2) break; bits++; } return bits-3; } static void invalidatemerges(cube &c) { if(c.merged) { brightencube(c); c.visible |= c.merged; c.merged = 0; } if(c.ext) { if(c.ext->va) { if(!(c.ext->va->hasmerges&(MERGE_PART | MERGE_ORIGIN))) return; destroyva(c.ext->va); c.ext->va = NULL; } if(c.ext->tjoints >= 0) c.ext->tjoints = -1; } if(c.children) loopi(8) invalidatemerges(c.children[i]); } static int invalidatedmerges = 0; void invalidatemerges(cube &c, const ivec &co, int size, bool msg) { if(msg && invalidatedmerges!=totalmillis) { renderprogress(0, "invalidating merged surfaces..."); invalidatedmerges = totalmillis; } invalidatemerges(c); } void calcmerges() { genmergeprogress = 0; genmerges(); } sandboxgamemaker-2.7.1+dfsg/src/engine/ui.cpp0000664000175000017500000021451311660231276021041 0ustar showardshoward#ifdef NEWGUI #include "engine.h" #include "textedit.h" namespace UI { struct Object; Object *selected = NULL, *hovering = NULL, *focused = NULL; float hoverx = 0, hovery = 0, selectx = 0, selecty = 0; static inline bool isselected(const Object *o) { return o==selected; } static inline bool ishovering(const Object *o) { return o==hovering; } static inline bool isfocused(const Object *o) { return o==focused; } static void setfocus(Object *o) { focused = o; } static inline void clearfocus(const Object *o) { if(o==selected) selected = NULL; if(o==hovering) hovering = NULL; if(o==focused) focused = NULL; } static void quad(float x, float y, float w, float h, float tx = 0, float ty = 0, float tw = 1, float th = 1) { glTexCoord2f(tx, ty); glVertex2f(x, y); glTexCoord2f(tx + tw, ty); glVertex2f(x + w, y); glTexCoord2f(tx + tw, ty + th); glVertex2f(x + w, y + h); glTexCoord2f(tx, ty + th); glVertex2f(x, y + h); } struct ClipArea { float x1, y1, x2, y2; ClipArea(float x, float y, float w, float h) : x1(x), y1(y), x2(x+w), y2(y+h) {} void intersect(const ClipArea &c) { x1 = max(x1, c.x1); y1 = max(y1, c.y1); x2 = max(x1, min(x2, c.x2)); y2 = max(y1, min(y2, c.y2)); } bool isfullyclipped(float x, float y, float w, float h) { return x1 == x2 || y1 == y2 || x >= x2 || y >= y2 || x+w <= x1 || y+h <= y1; } void scissor() { float margin = max((float(screen->w)/screen->h - 1)/2, 0.0f); int sx1 = clamp(int(floor((x1+margin)/(1 + 2*margin)*screen->w)), 0, screen->w), sy1 = clamp(int(floor(y1*screen->h)), 0, screen->h), sx2 = clamp(int(ceil((x2+margin)/(1 + 2*margin)*screen->w)), 0, screen->w), sy2 = clamp(int(ceil(y2*screen->h)), 0, screen->h); glScissor(sx1, screen->h - sy2, sx2-sx1, sy2-sy1); } }; static vector clipstack; static void pushclip(float x, float y, float w, float h) { if(clipstack.empty()) glEnable(GL_SCISSOR_TEST); ClipArea &c = clipstack.add(ClipArea(x, y, w, h)); if(clipstack.length() >= 2) c.intersect(clipstack[clipstack.length()-2]); c.scissor(); } static void popclip() { clipstack.pop(); if(clipstack.empty()) glDisable(GL_SCISSOR_TEST); else clipstack.last().scissor(); } static bool isfullyclipped(float x, float y, float w, float h) { if(clipstack.empty()) return false; return clipstack.last().isfullyclipped(x, y, w, h); } enum { ALIGN_MASK = 0xF, ALIGN_HMASK = 0x3, ALIGN_HSHIFT = 0, ALIGN_HNONE = 0, ALIGN_LEFT = 1, ALIGN_HCENTER = 2, ALIGN_RIGHT = 3, ALIGN_VMASK = 0xC, ALIGN_VSHIFT = 2, ALIGN_VNONE = 0<<2, ALIGN_BOTTOM = 1<<2, ALIGN_VCENTER = 2<<2, ALIGN_TOP = 3<<2, CLAMP_MASK = 0xF0, CLAMP_LEFT = 0x10, CLAMP_RIGHT = 0x20, CLAMP_BOTTOM = 0x40, CLAMP_TOP = 0x80, NO_ADJUST = ALIGN_HNONE | ALIGN_VNONE, }; enum { TYPE_MISC = 0, TYPE_SCROLLER, TYPE_SCROLLBAR, TYPE_SCROLLBUTTON, TYPE_SLIDER, TYPE_SLIDERBUTTON, TYPE_IMAGE, TYPE_TAG, TYPE_WINDOW, TYPE_TEXTEDITOR }; static vector executelater; struct Object { Object *parent; float x, y, w, h; uchar adjust; vector children; Object() : parent(NULL), x(0), y(0), w(0), h(0), adjust(ALIGN_HCENTER | ALIGN_VCENTER) {} virtual ~Object() { clearfocus(this); children.deletecontents(); } virtual int forks() const { return 0; } virtual int choosefork() const { return -1; } #define loopchildren(o, body) do { \ int numforks = forks(); \ if(numforks > 0) \ { \ int i = choosefork(); \ if(children.inrange(i)) \ { \ Object *o = children[i]; \ body; \ } \ } \ for(int i = numforks; i < children.length(); i++) \ { \ Object *o = children[i]; \ body; \ } \ } while(0) #define loopchildrenrev(o, body) do { \ int numforks = forks(); \ for(int i = children.length()-1; i >= numforks; i--) \ { \ Object *o = children[i]; \ body; \ } \ if(numforks > 0) \ { \ int i = choosefork(); \ if(children.inrange(i)) \ { \ Object *o = children[i]; \ body; \ } \ } \ } while(0) #define loopinchildren(o, cx, cy, body) \ loopchildren(o, \ { \ float o##x = cx - o->x; \ float o##y = cy - o->y; \ if(o##x >= 0 && o##x < o->w && o##y >= 0 && o##y < o->h) \ { \ body; \ } \ }) #define loopinchildrenrev(o, cx, cy, body) \ loopchildrenrev(o, \ { \ float o##x = cx - o->x; \ float o##y = cy - o->y; \ if(o##x >= 0 && o##x < o->w && o##y >= 0 && o##y < o->h) \ { \ body; \ } \ }) virtual void layout() { w = h = 0; loopchildren(o, { o->x = o->y = 0; o->layout(); w = max(w, o->x + o->w); h = max(h, o->y + o->h); }); } void adjustchildrento(float px, float py, float pw, float ph) { loopchildren(o, o->adjustlayout(px, py, pw, ph)); } virtual void adjustchildren() { adjustchildrento(0, 0, w, h); } void adjustlayout(float px, float py, float pw, float ph) { switch(adjust&ALIGN_HMASK) { case ALIGN_LEFT: x = px; break; case ALIGN_HCENTER: x = px + (pw - w) / 2; break; case ALIGN_RIGHT: x = px + pw - w; break; } switch(adjust&ALIGN_VMASK) { case ALIGN_BOTTOM: y = py; break; case ALIGN_VCENTER: y = py + (ph - h) / 2; break; case ALIGN_TOP: y = py + ph - h; break; } if(adjust&CLAMP_MASK) { if(adjust&CLAMP_LEFT) x = px; if(adjust&CLAMP_RIGHT) w = px + pw - x; if(adjust&CLAMP_BOTTOM) y = py; if(adjust&CLAMP_TOP) h = py + ph - y; } adjustchildren(); } virtual Object *target(float cx, float cy) { loopinchildrenrev(o, cx, cy, { Object *c = o->target(ox, oy); if(c) return c; }); return NULL; } virtual bool key(int code, bool isdown, int cooked) { loopchildrenrev(o, { if(o->key(code, isdown, cooked)) return true; }); return false; } virtual void draw(float sx, float sy) { loopchildren(o, { if(!isfullyclipped(sx + o->x, sy + o->y, o->w, o->h)) o->draw(sx + o->x, sy + o->y); }); } void draw() { draw(x, y); } virtual Object *hover(float cx, float cy) { loopinchildrenrev(o, cx, cy, { Object *c = o->hover(ox, oy); if(c == o) { hoverx = ox; hovery = oy; } if(c) return c; }); return NULL; } virtual void hovering(float cx, float cy) { } virtual Object *select(float cx, float cy) { loopinchildrenrev(o, cx, cy, { Object *c = o->select(ox, oy); if(c == o) { selectx = ox; selecty = oy; } if(c) return c; }); return NULL; } virtual bool allowselect(Object *o) { return false; } virtual void selected(float cx, float cy) { } virtual const char *getname() const { return ""; } virtual const int gettype() const { return TYPE_MISC; } bool isnamed(const char *name) const { return !strcmp(name, getname()); } Object *findname(int type, const char *name, bool recurse = true, const Object *exclude = NULL) const { loopchildren(o, { if(o != exclude && o->gettype() == type && (!name || o->isnamed(name)) ) return o; }); if(recurse) loopchildren(o, { if(o != exclude) { Object *found = o->findname(type, name); if(found) return found; } }); return NULL; } Object *findsibling(int type, const char *name) const { for(const Object *prev = this, *cur = parent; cur; prev = cur, cur = cur->parent) { Object *o = cur->findname(type, name, true, prev); if(o) return o; } return NULL; } void remove(Object *o) { children.removeobj(o); delete o; } }; struct HorizontalList : Object { float space; HorizontalList(float space = 0) : space(space) {} void layout() { w = h = 0; loopchildren(o, { o->x = w; o->y = 0; o->layout(); w += o->w; h = max(h, o->y + o->h); }); w += space*max(children.length() - 1, 0); } void adjustchildren() { if(children.empty()) return; float offset = 0; loopchildren(o, { o->x = offset; offset += o->w; o->adjustlayout(o->x, 0, offset - o->x, h); offset += space; }); } }; struct VerticalList : Object { float space; VerticalList(float space = 0) : space(space) {} void layout() { w = h = 0; loopchildren(o, { o->x = 0; o->y = h; o->layout(); h += o->h; w = max(w, o->x + o->w); }); h += space*max(children.length() - 1, 0); } void adjustchildren() { if(children.empty()) return; float offset = 0; loopchildren(o, { o->y = offset; offset += o->h; o->adjustlayout(0, o->y, w, offset - o->y); offset += space; }); } }; struct Table : Object { int columns; float space; vector widths, heights; Table(int columns, float space = 0) : columns(columns), space(space) {} void layout() { widths.setsize(0); heights.setsize(0); int column = 0, row = 0; loopchildren(o, { o->layout(); if(!widths.inrange(column)) widths.add(o->w); else if(o->w > widths[column]) widths[column] = o->w; if(!heights.inrange(row)) heights.add(o->h); else if(o->h > heights[row]) heights[row] = o->h; column = (column + 1) % columns; if(!column) row++; }); w = h = 0; column = row = 0; float offset = 0; loopchildren(o, { o->x = offset; o->y = h; o->adjustlayout(o->x, o->y, widths[column], heights[row]); offset += widths[column]; w = max(w, offset); column = (column + 1) % columns; if(!column) { offset = 0; h += heights[row]; row++; } }); if(column) h += heights[row]; w += space*max(widths.length() - 1, 0); h += space*max(heights.length() - 1, 0); } void adjustchildren() { if(children.empty()) return; float cspace = w, rspace = h; loopv(widths) cspace -= widths[i]; loopv(heights) rspace -= heights[i]; cspace /= max(widths.length() - 1, 1); rspace /= max(heights.length() - 1, 1); int column = 0, row = 0; float offsetx = 0, offsety = 0, nexty = heights[0] + rspace; loopchildren(o, { o->x = offsetx; o->y = offsety; offsetx += widths[column]; if(column < widths.length()) offsetx += cspace; o->adjustlayout(o->x, o->y, offsetx - o->x, nexty - o->y); column = (column + 1) % columns; if(!column) { offsetx = 0; offsety = nexty; row++; if(row < heights.length()) { nexty += heights[row]; if(row < heights.length()) nexty += rspace; } } }); } }; struct Spacer : Object { float spacew, spaceh; Spacer(float spacew, float spaceh) : spacew(spacew), spaceh(spaceh) {} void layout() { w = spacew; h = spaceh; loopchildren(o, { o->x = spacew; o->y = spaceh; o->layout(); w = max(w, o->x + o->w); h = max(h, o->y + o->h); }); w += spacew; h += spaceh; } void adjustchildren() { adjustchildrento(spacew, spaceh, w - 2*spacew, h - 2*spaceh); } }; struct Filler : Object { float minw, minh; Filler(float minw, float minh) : minw(minw), minh(minh) {} void layout() { Object::layout(); w = max(w, minw); h = max(h, minh); } }; struct Offsetter : Object { float offsetx, offsety; Offsetter(float offsetx, float offsety) : offsetx(offsetx), offsety(offsety) {} void layout() { Object::layout(); loopchildren(o, { o->x += offsetx; o->y += offsety; }); w += offsetx; h += offsety; } void adjustchildren() { adjustchildrento(offsetx, offsety, w - offsetx, h - offsety); } }; struct Clipper : Object { float clipw, cliph, virtw, virth; Clipper(float clipw = 0, float cliph = 0) : clipw(clipw), cliph(cliph), virtw(0), virth(0) {} void layout() { Object::layout(); virtw = w; virth = h; if(clipw) w = min(w, clipw); if(cliph) h = min(h, cliph); } void adjustchildren() { adjustchildrento(0, 0, virtw, virth); } void draw(float sx, float sy) { if((clipw && virtw > clipw) || (cliph && virth > cliph)) { pushclip(sx, sy, w, h); Object::draw(sx, sy); popclip(); } else Object::draw(sx, sy); } }; struct Conditional : Object { char *cond; Conditional(const char *cond) : cond(newstring(cond)) {} ~Conditional() { delete[] cond; } int forks() const { return 2; } int choosefork() const { return execute(cond) ? 0 : 1; } }; struct Button : Object { char *onselect; Button(const char *onselect) : onselect(newstring(onselect)) {} ~Button() { delete[] onselect; } int forks() const { return 3; } int choosefork() const { return isselected(this) ? 2 : (ishovering(this) ? 1 : 0); } Object *hover(float cx, float cy) { return target(cx, cy) ? this : NULL; } Object *select(float cx, float cy) { return target(cx, cy) ? this : NULL; } void selected(float cx, float cy) { executelater.add(newstring(onselect)); } }; struct ConditionalButton : Button { char *cond; ConditionalButton(const char *cond, const char *onselect) : Button(onselect), cond(newstring(cond)) {} ~ConditionalButton() { delete[] cond; } int forks() const { return 4; } int choosefork() const { return execute(cond) ? 1 + Button::choosefork() : 0; } void selected(float cx, float cy) { if(execute(cond)) Button::selected(cx, cy); } }; VAR(uitogglehside, 1, 0, 0); VAR(uitogglevside, 1, 0, 0); struct Toggle : Button { char *cond; float split; Toggle(const char *cond, const char *onselect, float split = 0) : Button(onselect), cond(newstring(cond)), split(split) {} ~Toggle() { delete[] cond; } int forks() const { return 4; } int choosefork() const { return (execute(cond) ? 2 : 0) + (ishovering(this) ? 1 : 0); } Object *hover(float cx, float cy) { return target(cx, cy) ? this : NULL; } Object *select(float cx, float cy) { if(target(cx, cy)) { uitogglehside = cx < w*split ? 0 : 1; uitogglevside = cy < h*split ? 0 : 1; return this; } return NULL; } }; struct Scroller : Clipper { float offsetx, offsety; Scroller(float clipw = 0, float cliph = 0) : Clipper(clipw, cliph), offsetx(0), offsety(0) {} Object *target(float cx, float cy) { if(cx + offsetx >= virtw || cy + offsety >= virth) return NULL; return Object::target(cx + offsetx, cy + offsety); } Object *hover(float cx, float cy) { if(cx + offsetx >= virtw || cy + offsety >= virth) return NULL; return Object::hover(cx + offsetx, cy + offsety); } Object *select(float cx, float cy) { if(cx + offsetx >= virtw || cy + offsety >= virth) return NULL; return Object::select(cx + offsetx, cy + offsety); } void draw(float sx, float sy) { if((clipw && virtw > clipw) || (cliph && virth > cliph)) { pushclip(sx, sy, w, h); Object::draw(sx - offsetx, sy - offsety); popclip(); } else Object::draw(sx, sy); } float hlimit() const { return max(virtw - w, 0.0f); } float vlimit() const { return max(virth - h, 0.0f); } float hoffset() const { return offsetx / max(virtw, w); } float voffset() const { return offsety / max(virth, h); } float hscale() const { return w / max(virtw, w); } float vscale() const { return h / max(virth, h); } void addhscroll(float hscroll) { sethscroll(offsetx + hscroll); } void addvscroll(float vscroll) { setvscroll(offsety + vscroll); } void sethscroll(float hscroll) { offsetx = clamp(hscroll, 0.0f, hlimit()); } void setvscroll(float vscroll) { offsety = clamp(vscroll, 0.0f, vlimit()); } const int gettype() const { return TYPE_SCROLLER; } }; struct ScrollBar : Object { float arrowsize, arrowspeed; int arrowdir; ScrollBar(float arrowsize = 0, float arrowspeed = 0) : arrowsize(arrowsize), arrowspeed(arrowspeed), arrowdir(0) {} int forks() const { return 5; } int choosefork() const { switch(arrowdir) { case -1: return isselected(this) ? 2 : (ishovering(this) ? 1 : 0); case 1: return isselected(this) ? 4 : (ishovering(this) ? 3 : 0); } return 0; } virtual int choosedir(float cx, float cy) const { return 0; } Object *hover(float cx, float cy) { Object *o = Object::hover(cx, cy); if(o) return o; return target(cx, cy) ? this : NULL; } Object *select(float cx, float cy) { Object *o = Object::select(cx, cy); if(o) return o; return target(cx, cy) ? this : NULL; } const int gettype() const { return TYPE_SCROLLBAR; } virtual void scrollto(float cx, float cy) { } void selected(float cx, float cy) { arrowdir = choosedir(cx, cy); if(!arrowdir) scrollto(cx, cy); else hovering(cx, cy); } virtual void arrowscroll() { } void hovering(float cx, float cy) { if(isselected(this)) { if(arrowdir) arrowscroll(); } else { Object *button = findname(TYPE_SCROLLBUTTON, NULL, false); if(button && isselected(button)) { arrowdir = 0; button->hovering(cx - button->x, cy - button->y); } else arrowdir = choosedir(cx, cy); } } bool allowselect(Object *o) { return children.find(o) >= 0; } virtual void movebutton(Object *o, float fromx, float fromy, float tox, float toy) = 0; }; struct ScrollButton : Object { float offsetx, offsety; ScrollButton() : offsetx(0), offsety(0) {} int forks() const { return 3; } int choosefork() const { return isselected(this) ? 2 : (ishovering(this) ? 1 : 0); } Object *hover(float cx, float cy) { return target(cx, cy) ? this : NULL; } Object *select(float cx, float cy) { return target(cx, cy) ? this : NULL; } void hovering(float cx, float cy) { if(isselected(this)) { if(!parent || parent->gettype() != TYPE_SCROLLBAR) return; ScrollBar *scrollbar = (ScrollBar *) parent; scrollbar->movebutton(this, offsetx, offsety, cx, cy); } } void selected(float cx, float cy) { offsetx = cx; offsety = cy; } const int gettype() const { return TYPE_SCROLLBUTTON; } }; struct HorizontalScrollBar : ScrollBar { HorizontalScrollBar(float arrowsize = 0, float arrowspeed = 0) : ScrollBar(arrowsize, arrowspeed) {} int choosedir(float cx, float cy) const { if(cx < arrowsize) return -1; else if(cx >= w - arrowsize) return 1; return 0; } void arrowscroll() { Scroller *scroller = (Scroller *) findsibling(TYPE_SCROLLER, NULL); if(!scroller) return; scroller->addhscroll(arrowdir*arrowspeed*curtime/1000.0f); } void scrollto(float cx, float cy) { Scroller *scroller = (Scroller *) findsibling(TYPE_SCROLLER, NULL); if(!scroller) return; ScrollButton *button = (ScrollButton *) findname(TYPE_SCROLLBUTTON, NULL, false); if(!button) return; float bscale = (max(w - 2*arrowsize, 0.0f) - button->w) / (1 - scroller->hscale()), offset = bscale > 1e-3f ? (cx - arrowsize)/bscale : 0; scroller->sethscroll(offset*scroller->virtw); } void adjustchildren() { Scroller *scroller = (Scroller *) findsibling(TYPE_SCROLLER, NULL); if(!scroller) return; ScrollButton *button = (ScrollButton *) findname(TYPE_SCROLLBUTTON, NULL, false); if(!button) return; float bw = max(w - 2*arrowsize, 0.0f)*scroller->hscale(); button->w = max(button->w, bw); float bscale = scroller->hscale() < 1 ? (max(w - 2*arrowsize, 0.0f) - button->w) / (1 - scroller->hscale()) : 1; button->x = arrowsize + scroller->hoffset()*bscale; button->adjust &= ~ALIGN_HMASK; ScrollBar::adjustchildren(); } void movebutton(Object *o, float fromx, float fromy, float tox, float toy) { scrollto(o->x + tox - fromx, o->y + toy); } }; struct VerticalScrollBar : ScrollBar { VerticalScrollBar(float arrowsize = 0, float arrowspeed = 0) : ScrollBar(arrowsize, arrowspeed) {} int choosedir(float cx, float cy) const { if(cy < arrowsize) return -1; else if(cy >= h - arrowsize) return 1; return 0; } void arrowscroll() { Scroller *scroller = (Scroller *) findsibling(TYPE_SCROLLER, NULL); if(!scroller) return; scroller->addvscroll(arrowdir*arrowspeed*curtime/1000.0f); } void scrollto(float cx, float cy) { Scroller *scroller = (Scroller *) findsibling(TYPE_SCROLLER, NULL); if(!scroller) return; ScrollButton *button = (ScrollButton *) findname(TYPE_SCROLLBUTTON, NULL, false); if(!button) return; float bscale = (max(h - 2*arrowsize, 0.0f) - button->h) / (1 - scroller->vscale()), offset = bscale > 1e-3f ? (cy - arrowsize)/bscale : 0; scroller->setvscroll(offset*scroller->virth); } void adjustchildren() { Scroller *scroller = (Scroller *) findsibling(TYPE_SCROLLER, NULL); if(!scroller) return; ScrollButton *button = (ScrollButton *) findname(TYPE_SCROLLBUTTON, NULL, false); if(!button) return; float bh = max(h - 2*arrowsize, 0.0f)*scroller->vscale(); button->h = max(button->h, bh); float bscale = scroller->vscale() < 1 ? (max(h - 2*arrowsize, 0.0f) - button->h) / (1 - scroller->vscale()) : 1; button->y = arrowsize + scroller->voffset()*bscale; button->adjust &= ~ALIGN_VMASK; ScrollBar::adjustchildren(); } void movebutton(Object *o, float fromx, float fromy, float tox, float toy) { scrollto(o->x + tox, o->y + toy - fromy); } }; static float getfval(ident *id) { switch(id->type) { case ID_VAR: return *id->storage.i; case ID_FVAR: return *id->storage.f; case ID_SVAR: return parsefloat(*id->storage.s); case ID_ALIAS: return id->getfloat(); default: return 0; } } struct Slider : Object { ident *var; float vmin, vmax; float arrowsize, arrowspeed; int arrowdir; Slider(char *varname, float min = 0, float max = 0, float arrowsize = 0, float arrowspeed = 0) : vmin(min), vmax(max), arrowsize(arrowsize), arrowspeed(arrowspeed), arrowdir(0) { var = getident(varname); if(!var) { alias(varname, "0"); var = getident(varname); } if(vmin == 0 && vmax == 0) { if(var->type == ID_VAR) { vmin = var->minval; vmax = var->maxval; } else if(var->type == ID_FVAR) { vmin = var->minvalf; vmax = var->maxvalf; } } } int forks() const { return 5; } int choosefork() const { switch(arrowdir) { case -1: return isselected(this) ? 2 : (ishovering(this) ? 1 : 0); case 1: return isselected(this) ? 4 : (ishovering(this) ? 3 : 0); } return 0; } virtual int choosedir(float cx, float cy) const { return 0; } Object *hover(float cx, float cy) { Object *o = Object::hover(cx, cy); if(o) return o; return target(cx, cy) ? this : NULL; } Object *select(float cx, float cy) { Object *o = Object::select(cx, cy); if(o) return o; return target(cx, cy) ? this : NULL; } const int gettype() const { return TYPE_SLIDER; } virtual void scrollto(float cx, float cy) { } void selected(float cx, float cy) { arrowdir = choosedir(cx, cy); if(!arrowdir) scrollto(cx, cy); else hovering(cx, cy); } void arrowscroll() { float pos = (getfval(var) - vmin) / (vmax - vmin); pos += clamp(1 - pos, -pos, arrowdir * arrowspeed * curtime / fabs(vmax - vmin)); float val = vmin + pos * (vmax - vmin); setval(val); } void setval(float val) { string cmd = ""; switch(var->type) { case ID_VAR: case ID_FVAR: case ID_SVAR: formatstring(cmd)("%s %g", var->name, val); break; case ID_ALIAS: formatstring(cmd)("alias %s %g", var->name, val); break; } executelater.add(newstring(cmd)); } void hovering(float cx, float cy) { if(isselected(this)) { if(arrowdir) arrowscroll(); } else { Object *button = findname(TYPE_SLIDERBUTTON, NULL, false); if(button && isselected(button)) { arrowdir = 0; button->hovering(cx - button->x, cy - button->y); } else arrowdir = choosedir(cx, cy); } } bool allowselect(Object *o) { return children.find(o) >= 0; } virtual void movebutton(Object *o, float fromx, float fromy, float tox, float toy) = 0; }; struct SliderButton : Object { float offsetx, offsety; SliderButton() : offsetx(0), offsety(0) {} int forks() const { return 3; } int choosefork() const { return isselected(this) ? 2 : (ishovering(this) ? 1 : 0); } Object *hover(float cx, float cy) { return target(cx, cy) ? this : NULL; } Object *select(float cx, float cy) { return target(cx, cy) ? this : NULL; } void hovering(float cx, float cy) { if(isselected(this)) { if(!parent || parent->gettype() != TYPE_SLIDER) return; Slider *slider = (Slider *) parent; slider->movebutton(this, offsetx, offsety, cx, cy); } } void selected(float cx, float cy) { offsetx = cx; offsety = cy; } const int gettype() const { return TYPE_SLIDERBUTTON; } }; struct HorizontalSlider : Slider { HorizontalSlider(char *varname, float vmin = 0, float vmax = 0, float arrowsize = 0, float arrowspeed = 0) : Slider(varname, vmin, vmax, arrowsize, arrowspeed) {} int choosedir(float cx, float cy) const { if(cx < arrowsize) return -1; else if(cx >= w - arrowsize) return 1; return 0; } void scrollto(float cx, float cy) { SliderButton *button = (SliderButton *) findname(TYPE_SLIDERBUTTON, NULL, false); if(!button) return; float pos = clamp(1.0f, 0.0f, (cx - arrowsize) / (w - 2 * arrowsize - button->w)); float val = vmin + pos * (vmax - vmin); setval(val); } void adjustchildren() { SliderButton *button = (SliderButton *) findname(TYPE_SLIDERBUTTON, NULL, false); if(!button) return; float bw = max(w - 2 * arrowsize, 0.0f) / fabs(vmax - vmin); button->w = max(button->w, bw); float bscale = fabs(vmax - vmin) > 0 ? (max(w - 2 * arrowsize, 0.0f) - button->w) / fabs(vmax - vmin) : 1; button->x = arrowsize + (getfval(var) - vmin) * bscale; button->adjust &= ~ALIGN_HMASK; Slider::adjustchildren(); } void movebutton(Object *o, float fromx, float fromy, float tox, float toy) { scrollto(o->x + tox - fromx, o->y + toy); } }; struct VerticalSlider : Slider { VerticalSlider(char *varname, float vmin = 0, float vmax = 0, float arrowsize = 0, float arrowspeed = 0) : Slider(varname, vmin, vmax, arrowsize, arrowspeed) {} int choosedir(float cx, float cy) const { if(cy < arrowsize) return -1; else if(cy >= h - arrowsize) return 1; return 0; } void scrollto(float cx, float cy) { SliderButton *button = (SliderButton *) findname(TYPE_SLIDERBUTTON, NULL, false); if(!button) return; float pos = clamp(1.0f, 0.0f, (cy - arrowsize) / (h - 2 * arrowsize - button->h)); float val = vmin + pos * (vmax - vmin); setval(val); } void adjustchildren() { SliderButton *button = (SliderButton *) findname(TYPE_SLIDERBUTTON, NULL, false); if(!button) return; float bh = max(h - 2 * arrowsize, 0.0f) / fabs(vmax - vmin); button->h = max(button->h, bh); float bscale = fabs(vmax - vmin) > 0 ? (max(h - 2 * arrowsize, 0.0f) - button->h) / fabs(vmax - vmin) : 1; button->y = arrowsize + (getfval(var) - vmin) * bscale; button->adjust &= ~ALIGN_HMASK; Slider::adjustchildren(); } void movebutton(Object *o, float fromx, float fromy, float tox, float toy) { scrollto(o->x + tox, o->y + toy - fromy); } }; static bool checkalphamask(Texture *tex, float x, float y) { if(!tex->alphamask) { loadalphamask(tex); if(!tex->alphamask) return true; } int tx = clamp(int(floor(x*tex->xs)), 0, tex->xs-1), ty = clamp(int(floor(y*tex->ys)), 0, tex->ys-1); if(tex->alphamask[ty*((tex->xs+7)/8) + tx/8] & (1<<(tx%8))) return true; return false; } struct Rectangle : Filler { enum { SOLID = 0, MODULATE }; int type; vec4 color; Rectangle(int type, float r, float g, float b, float a, float minw = 0, float minh = 0) : Filler(minw, minh), type(type), color(r, g, b, a) {} Object *target(float cx, float cy) { Object *o = Object::target(cx, cy); return o ? o : this; } void draw(float sx, float sy) { if(type==MODULATE) glBlendFunc(GL_ZERO, GL_SRC_COLOR); glDisable(GL_TEXTURE_2D); notextureshader->set(); glColor4fv(color.v); glBegin(GL_QUADS); glVertex2f(sx, sy); glVertex2f(sx + w, sy); glVertex2f(sx + w, sy + h); glVertex2f(sx, sy + h); glEnd(); glColor3f(1, 1, 1); glEnable(GL_TEXTURE_2D); defaultshader->set(); if(type==MODULATE) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Object::draw(sx, sy); } }; struct Image : Filler { Texture *tex; Image(Texture *tex, float minw = 0, float minh = 0) : Filler(minw, minh), tex(tex) {} Object *target(float cx, float cy) { Object *o = Object::target(cx, cy); if(o) return o; if(tex->bpp < 32) return this; return checkalphamask(tex, cx/w, cy/h) ? this : NULL; } void draw(float sx, float sy) { glBindTexture(GL_TEXTURE_2D, tex->id); glBegin(GL_QUADS); quad(sx, sy, w, h); glEnd(); Object::draw(sx, sy); } const int gettype() const { return TYPE_IMAGE; } }; VAR(thumbtime, 0, 25, 1000); static int lastthumbnail = 0; struct SlotViewer : Filler { int slotnum; SlotViewer(int slotnum, float minw = 0, float minh = 0) : Filler(minw, minh), slotnum(slotnum) {} Object *target(float cx, float cy) { Object *o = Object::target(cx, cy); if(o || !texmru.inrange(slotnum)) return o; VSlot &vslot = lookupvslot(texmru[slotnum], false); if(vslot.slot->sts.length() && (vslot.slot->loaded || vslot.slot->thumbnail)) return this; return NULL; } void drawslot(Slot &slot, VSlot &vslot, float sx, float sy) { Texture *tex = notexture, *glowtex = NULL, *layertex = NULL; VSlot *layer = NULL; if(slot.loaded) { tex = slot.sts[0].t; if(slot.texmask&(1<slot->sts.empty()) layertex = layer->slot->sts[0].t; } } else if(slot.thumbnail) tex = slot.thumbnail; float xt, yt; xt = min(1.0f, tex->xs/(float)tex->ys), yt = min(1.0f, tex->ys/(float)tex->xs); static Shader *rgbonlyshader = NULL; if(!rgbonlyshader) rgbonlyshader = lookupshaderbyname("rgbonly"); rgbonlyshader->set(); float tc[4][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; int xoff = vslot.xoffset, yoff = vslot.yoffset; if(vslot.rotation) { if((vslot.rotation&5) == 1) { swap(xoff, yoff); loopk(4) swap(tc[k][0], tc[k][1]); } if(vslot.rotation >= 2 && vslot.rotation <= 4) { xoff *= -1; loopk(4) tc[k][0] *= -1; } if(vslot.rotation <= 2 || vslot.rotation == 5) { yoff *= -1; loopk(4) tc[k][1] *= -1; } } loopk(4) { tc[k][0] = tc[k][0]/xt - float(xoff)/tex->xs; tc[k][1] = tc[k][1]/yt - float(yoff)/tex->ys; } if(slot.loaded) glColor3fv(vslot.colorscale.v); glBindTexture(GL_TEXTURE_2D, tex->id); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(sx, sy); glTexCoord2fv(tc[1]); glVertex2f(sx+w, sy); glTexCoord2fv(tc[3]); glVertex2f(sx, sy+h); glTexCoord2fv(tc[2]); glVertex2f(sx+w, sy+h); glEnd(); if(glowtex) { glBlendFunc(GL_SRC_ALPHA, GL_ONE); glBindTexture(GL_TEXTURE_2D, glowtex->id); glColor3fv(vslot.glowcolor.v); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(sx, sy); glTexCoord2fv(tc[1]); glVertex2f(sx+w, sy); glTexCoord2fv(tc[3]); glVertex2f(sx, sy+h); glTexCoord2fv(tc[2]); glVertex2f(sx+w, sy+h); glEnd(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } if(layertex) { glBindTexture(GL_TEXTURE_2D, layertex->id); glColor3fv(layer->colorscale.v); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(sx+w/2, sy+h/2); glTexCoord2fv(tc[1]); glVertex2f(sx+w, sy+h/2); glTexCoord2fv(tc[3]); glVertex2f(sx+w/2, sy+h); glTexCoord2fv(tc[2]); glVertex2f(sx+w, sy+h); glEnd(); } glColor3f(1, 1, 1); defaultshader->set(); } void draw(float sx, float sy) { if(texmru.inrange(slotnum)) { VSlot &vslot = lookupvslot(texmru[slotnum], false); Slot &slot = *vslot.slot; if(slot.sts.length()) { if(slot.loaded || slot.thumbnail) drawslot(slot, vslot, sx, sy); else if(totalmillis-lastthumbnail >= thumbtime) { loadthumbnail(slot); lastthumbnail = totalmillis; } } } Object::draw(sx, sy); } }; struct CroppedImage : Image { float cropx, cropy, cropw, croph; CroppedImage(Texture *tex, float minw = 0, float minh = 0, float cropx = 0, float cropy = 0, float cropw = 1, float croph = 1) : Image(tex, minw, minh), cropx(cropx), cropy(cropy), cropw(cropw), croph(croph) {} Object *target(float cx, float cy) { Object *o = Object::target(cx, cy); if(o) return o; if(tex->bpp < 32) return this; return checkalphamask(tex, cropx + cx/w*cropw, cropy + cy/h*croph) ? this : NULL; } void draw(float sx, float sy) { glBindTexture(GL_TEXTURE_2D, tex->id); glBegin(GL_QUADS); quad(sx, sy, w, h, cropx, cropy, cropw, croph); glEnd(); Object::draw(sx, sy); } }; struct StretchedImage : Image { StretchedImage(Texture *tex, float minw = 0, float minh = 0) : Image(tex, minw, minh) {} Object *target(float cx, float cy) { Object *o = Object::target(cx, cy); if(o) return o; if(tex->bpp < 32) return this; float mx, my; if(w <= minw) mx = cx/w; else if(cx < minw/2) mx = cx/minw; else if(cx >= w - minw/2) mx = 1 - (w - cx) / minw; else mx = 0.5f; if(h <= minh) my = cy/h; else if(cy < minh/2) my = cy/minh; else if(cy >= h - minh/2) my = 1 - (h - cy) / minh; else my = 0.5f; return checkalphamask(tex, mx, my) ? this : NULL; } void draw(float sx, float sy) { glBindTexture(GL_TEXTURE_2D, tex->id); glBegin(GL_QUADS); float splitw = (minw ? min(minw, w) : w) / 2, splith = (minh ? min(minh, h) : h) / 2, vy = sy, ty = 0; loopi(3) { float vh = 0, th = 0; switch(i) { case 0: if(splith < h - splith) { vh = splith; th = 0.5f; } else { vh = h; th = 1; } break; case 1: vh = h - 2*splith; th = 0; break; case 2: vh = splith; th = 0.5f; break; } float vx = sx, tx = 0; loopj(3) { float vw = 0, tw = 0; switch(j) { case 0: if(splitw < w - splitw) { vw = splitw; tw = 0.5f; } else { vw = w; tw = 1; } break; case 1: vw = w - 2*splitw; tw = 0; break; case 2: vw = splitw; tw = 0.5f; break; } quad(vx, vy, vw, vh, tx, ty, tw, th); vx += vw; tx += tw; if(tx >= 1) break; } vy += vh; ty += th; if(ty >= 1) break; } glEnd(); Object::draw(sx, sy); } }; struct BorderedImage : Image { float texborder, screenborder; BorderedImage(Texture *tex, float texborder, float screenborder) : Image(tex), texborder(texborder), screenborder(screenborder) {} void layout() { Object::layout(); w = max(w, 2*screenborder); h = max(h, 2*screenborder); } Object *target(float cx, float cy) { Object *o = Object::target(cx, cy); if(o) return o; if(tex->bpp < 32) return this; float mx, my; if(cx < screenborder) mx = cx/screenborder*texborder; else if(cx >= w - screenborder) mx = 1-texborder + (cx - (w - screenborder))/screenborder*texborder; else mx = texborder + (cx - screenborder)/(w - 2*screenborder)*(1 - 2*texborder); if(cy < screenborder) my = cy/screenborder*texborder; else if(cy >= h - screenborder) my = 1-texborder + (cy - (h - screenborder))/screenborder*texborder; else my = texborder + (cy - screenborder)/(h - 2*screenborder)*(1 - 2*texborder); return checkalphamask(tex, mx, my) ? this : NULL; } void draw(float sx, float sy) { glBindTexture(GL_TEXTURE_2D, tex->id); glBegin(GL_QUADS); float vy = sy, ty = 0; loopi(3) { float vh = 0, th = 0; switch(i) { case 0: vh = screenborder; th = texborder; break; case 1: vh = h - 2*screenborder; th = 1 - 2*texborder; break; case 2: vh = screenborder; th = texborder; break; } float vx = sx, tx = 0; loopj(3) { float vw = 0, tw = 0; switch(j) { case 0: vw = screenborder; tw = texborder; break; case 1: vw = w - 2*screenborder; tw = 1 - 2*texborder; break; case 2: vw = screenborder; tw = texborder; break; } quad(vx, vy, vw, vh, tx, ty, tw, th); vx += vw; tx += tw; } vy += vh; ty += th; } glEnd(); Object::draw(sx, sy); } }; // default size of text in terms of rows per screenful VARP(uitextrows, 1, 40, 200); struct Text : Object { char *str; float scale; vec color; Text(const char *str, float scale = 1, float r = 1, float g = 1, float b = 1) : str(newstring(str)), scale(scale), color(r, g, b) {} ~Text() { delete[] str; } Object *target(float cx, float cy) { Object *o = Object::target(cx, cy); return o ? o : this; } float drawscale() const { return scale / (FONTH * uitextrows); } void draw(float sx, float sy) { float k = drawscale(); glPushMatrix(); glScalef(k, k, 1); draw_text(str, int(sx/k), int(sy/k), color.x * 255, color.y * 255, color.z * 255, 255); glColor3f(1, 1, 1); glPopMatrix(); Object::draw(sx, sy); } void layout() { Object::layout(); int tw, th; text_bounds(str, tw, th); float k = drawscale(); w = max(w, tw*k); h = max(h, th*k); } }; static const char *getsval(ident *id) { switch(id->type) { case ID_VAR: return intstr(*id->storage.i); case ID_FVAR: return floatstr(*id->storage.f); case ID_SVAR: return *id->storage.s; case ID_ALIAS: return id->getstr(); default: return ""; } } struct VarText : Object { ident *id; float scale; vec color; VarText(const char *var, float scale = 1, float r = 1, float g = 1, float b = 1) : scale(scale), color(r, g, b) { id = getident(var); if(!id) { alias(var, "0"); id = getident(var); } } float drawscale() const { return scale / (FONTH * uitextrows); } void draw(float sx, float sy) { float k = drawscale(); glPushMatrix(); glScalef(k, k, 1); draw_text(getsval(id), int(sx/k), int(sy/k), color.x * 255, color.y * 255, color.z * 255, 255); glColor3f(1, 1, 1); glPopMatrix(); Object::draw(sx, sy); } void layout() { Object::layout(); int tw, th; text_bounds(getsval(id), tw, th); float k = drawscale(); w = max(w, tw*k); h = max(h, th*k); } }; struct TextEditor : Object { float scale, offsetx, offsety; editor *edit; char *keyfilter; TextEditor(const char *name, int length, int height, float scale = 1, const char *initval = NULL, int mode = EDITORUSED, const char *keyfilter = NULL) : scale(scale), offsetx(0), offsety(0), keyfilter(keyfilter ? newstring(keyfilter) : NULL) { edit = useeditor(name, mode, initval); edit->linewrap = length<0; edit->maxx = edit->linewrap ? -1 : length; edit->maxy = height <= 0 ? 1 : -1; edit->pixelwidth = abs(length)*FONTH; if(edit->linewrap && edit->maxy==1) { int temp; text_bounds(edit->lines[0].text, temp, edit->pixelheight, edit->pixelwidth); //only single line editors can have variable height } else edit->pixelheight = FONTH*max(height, 1); } ~TextEditor() { DELETEA(keyfilter); if(edit->mode!=EDITORFOREVER) removeeditor(edit); } Object *target(float cx, float cy) { Object *o = Object::target(cx, cy); return o ? o : this; } Object *hover(float cx, float cy) { return target(cx, cy) ? this : NULL; } Object *select(float cx, float cy) { return target(cx, cy) ? this : NULL; } void hovering(float cx, float cy) { if(isselected(this) && isfocused(this)) { bool dragged = max(fabs(cx - offsetx), fabs(cy - offsety)) > (FONTH/8.0f)*scale/float(FONTH*uitextrows); edit->hit(int(floor(cx*(FONTH*uitextrows)/scale - FONTW/2)), int(floor(cy*(FONTH*uitextrows)/scale)), dragged); } } void selected(float cx, float cy) { focuseditor(edit); setfocus(this); edit->mark(false); offsetx = cx; offsety = cy; } bool key(int code, bool isdown, int cooked) { if(Object::key(code, isdown, cooked)) return true; if(!isfocused(this)) return false; switch(code) { case SDLK_RETURN: case SDLK_TAB: if(cooked && edit->maxy != 1) break; case SDLK_ESCAPE: if(cooked) setfocus(NULL); return true; case SDLK_KP_ENTER: if(cooked && edit->maxy == 1) setfocus(NULL); return true; case SDLK_HOME: case SDLK_END: case SDLK_PAGEUP: case SDLK_PAGEDOWN: case SDLK_DELETE: case SDLK_BACKSPACE: case SDLK_UP: case SDLK_DOWN: case SDLK_LEFT: case SDLK_RIGHT: case -4: case -5: break; default: if(!cooked || code<32) return false; if(keyfilter && !strchr(keyfilter, cooked)) return true; break; } if(isdown) edit->key(code, cooked); return true; } void layout() { Object::layout(); if(edit->linewrap && edit->maxy==1) { int temp; text_bounds(edit->lines[0].text, temp, edit->pixelheight, edit->pixelwidth); //only single line editors can have variable height } w = max(w, (edit->pixelwidth + FONTW)*scale/float(FONTH*uitextrows)); h = max(h, edit->pixelheight*scale/float(FONTH*uitextrows)); } void draw(float sx, float sy) { glPushMatrix(); glTranslatef(sx, sy, 0); glScalef(scale/(FONTH*uitextrows), scale/(FONTH*uitextrows), 1); edit->draw(FONTW/2, 0, 0, isfocused(this)); glColor3f(1, 1, 1); glPopMatrix(); Object::draw(sx, sy); } const int gettype() const { return TYPE_TEXTEDITOR; } }; struct NamedObject : Object { char *name; NamedObject(const char *name) : name(newstring(name)) {} ~NamedObject() { delete[] name; } const char *getname() const { return name; } }; struct Tag : NamedObject { Tag(const char *name) : NamedObject(name) {} const int gettype() const { return TYPE_TAG; } }; struct World : Object { void layout() { Object::layout(); float margin = max((float(screen->w)/screen->h - 1)/2, 0.0f); x = -margin; y = 0; w = 1 + 2*margin; h = 1; adjustchildren(); } }; struct Window : NamedObject { char *onhide; Window(const char *name, const char *onhide = NULL) : NamedObject(name), onhide(onhide && onhide[0] ? newstring(onhide) : NULL) {} ~Window() { DELETEA(onhide); } void hidden() { if(onhide) execute(onhide); } const int gettype() const { return TYPE_WINDOW; } }; World *world = NULL; vector build; Window *buildwindow(const char *name, const char *contents, const char *onhide = NULL) { Window *window = new Window(name, onhide); build.add(window); execute(contents); build.pop(); return window; } ICOMMAND(showui, "sss", (char *name, char *contents, char *onhide), { if(build.length()) { intret(0); return; } Window *oldwindow = (Window *) world->findname(TYPE_WINDOW, name, false); if(oldwindow) { oldwindow->hidden(); world->remove(oldwindow); } Window *window = buildwindow(name, contents, onhide); world->children.add(window); window->parent = world; intret(1); }); bool hideui(const char *name) { Window *window = (Window *) world->findname(TYPE_WINDOW, name, false); if(window) { window->hidden(); world->remove(window); } return window!=NULL; } ICOMMAND(hideui, "s", (char *name), intret(hideui(name) ? 1 : 0)); ICOMMAND(replaceui, "sss", (char *wname, char *tname, char *contents), { if(build.length()) { intret(0); return; } Window *window = (Window *) world->findname(TYPE_WINDOW, wname, false); if(!window) { intret(0); return; } Tag *tag = (Tag *) window->findname(TYPE_TAG, tname); if(!tag) { intret(0); return; } tag->children.deletecontents(); build.add(tag); execute(contents); build.pop(); intret(1); }); void addui(Object *o, const char *children) { if(build.length()) { o->parent = build.last(); build.last()->children.add(o); } if(children[0]) { build.add(o); execute(children); build.pop(); } } ICOMMAND(uialign, "ii", (int *xalign, int *yalign), { if(build.length()) build.last()->adjust = (build.last()->adjust & ~ALIGN_MASK) | ((clamp(*xalign, -1, 1)+2)<adjust = (build.last()->adjust & ~CLAMP_MASK) | (*left ? CLAMP_LEFT : 0) | (*right ? CLAMP_RIGHT : 0) | (*bottom ? CLAMP_BOTTOM : 0) | (*top ? CLAMP_TOP : 0); }); ICOMMAND(uitag, "ss", (char *name, char *children), addui(new Tag(name), children)); ICOMMAND(uihlist, "fs", (float *space, char *children), addui(new HorizontalList(*space), children)); ICOMMAND(uivlist, "fs", (float *space, char *children), addui(new VerticalList(*space), children)); ICOMMAND(uitable, "ifs", (int *columns, float *space, char *children), addui(new Table(*columns, *space), children)); ICOMMAND(uispace, "ffs", (float *spacew, float *spaceh, char *children), addui(new Spacer(*spacew, *spaceh), children)); ICOMMAND(uifill, "ffs", (float *minw, float *minh, char *children), addui(new Filler(*minw, *minh), children)); ICOMMAND(uiclip, "ffs", (float *clipw, float *cliph, char *children), addui(new Clipper(*clipw, *cliph), children)); ICOMMAND(uiscroll, "ffs", (float *clipw, float *cliph, char *children), addui(new Scroller(*clipw, *cliph), children)); ICOMMAND(uihscrollbar, "ffs", (float *arrowsize, float *arrowspeed, char *children), addui(new HorizontalScrollBar(*arrowsize, *arrowspeed), children)); ICOMMAND(uivscrollbar, "ffs", (float *arrowsize, float *arrowspeed, char *children), addui(new VerticalScrollBar(*arrowsize, *arrowspeed), children)); ICOMMAND(uiscrollbutton, "s", (char *children), addui(new ScrollButton, children)); ICOMMAND(uihslider, "sffffs", (char *var, float *vmin, float *vmax, float *arrowsize, float *arrowspeed, char *children), addui(new HorizontalSlider(var, *vmin, *vmax, *arrowsize, *arrowspeed), children)); ICOMMAND(uivslider, "sffffs", (char *var, float *vmin, float *vmax, float *arrowsize, float *arrowspeed, char *children), addui(new VerticalSlider(var, *vmin, *vmax, *arrowsize, *arrowspeed), children)); ICOMMAND(uisliderbutton, "s", (char *children), addui(new SliderButton, children)); ICOMMAND(uioffset, "ffs", (float *offsetx, float *offsety, char *children), addui(new Offsetter(*offsetx, *offsety), children)); ICOMMAND(uibutton, "ss", (char *onselect, char *children), addui(new Button(onselect), children)); ICOMMAND(uicond, "ss", (char *cond, char *children), addui(new Conditional(cond), children)); ICOMMAND(uicondbutton, "sss", (char *cond, char *onselect, char *children), addui(new ConditionalButton(cond, onselect), children)); ICOMMAND(uitoggle, "ssfs", (char *cond, char *onselect, float *split, char *children), addui(new Toggle(cond, onselect, *split), children)); ICOMMAND(uiimage, "sffs", (char *texname, float *minw, float *minh, char *children), addui(new Image(textureload(texname, 3, true, false), *minw, *minh), children)); ICOMMAND(uislotview, "iffs", (int *slotnum, float *minw, float *minh, char *children), addui(new SlotViewer(*slotnum, *minw, *minh), children)); ICOMMAND(uialtimage, "s", (char *texname), { if(build.empty() || build.last()->gettype() != TYPE_IMAGE) return; Image *image = (Image *) build.last(); if(image && image->tex==notexture) image->tex = textureload(texname, 3, true, false); }); ICOMMAND(uicolor, "ffffffs", (float *r, float *g, float *b, float *a, float *minw, float *minh, char *children), addui(new Rectangle(Rectangle::SOLID, *r, *g, *b, *a, *minw, *minh), children)); ICOMMAND(uimodcolor, "fffffs", (float *r, float *g, float *b, float *minw, float *minh, char *children), addui(new Rectangle(Rectangle::MODULATE, *r, *g, *b, 1, *minw, *minh), children)); ICOMMAND(uistretchedimage, "sffs", (char *texname, float *minw, float *minh, char *children), addui(new StretchedImage(textureload(texname, 3, true, false), *minw, *minh), children)); ICOMMAND(uicroppedimage, "sffsssss", (char *texname, float *minw, float *minh, char *cropx, char *cropy, char *cropw, char *croph, char *children), Texture *tex = textureload(texname, 3, true, false); addui(new CroppedImage(tex, *minw, *minh, strchr(cropx, 'p') ? atof(cropx) / tex->xs : atof(cropx), strchr(cropy, 'p') ? atof(cropy) / tex->ys : atof(cropy), strchr(cropw, 'p') ? atof(cropw) / tex->xs : atof(cropw), strchr(croph, 'p') ? atof(croph) / tex->ys : atof(croph)), children)); ICOMMAND(uiborderedimage, "ssfs", (char *texname, char *texborder, float *screenborder, char *children), Texture *tex = textureload(texname, 3, true, false); addui(new BorderedImage(tex, strchr(texborder, 'p') ? atof(texborder) / tex->xs : atof(texborder), *screenborder), children)); ICOMMAND(uicolortext, "sffffs", (char *text, float *scale, float *r, float *g, float *b, char *children), addui(new Text(text, *scale <= 0 ? 1 : *scale, *r, *g, *b), children)); ICOMMAND(uitext, "sfs", (char *text, float *scale, char *children), addui(new Text(text, *scale <= 0 ? 1 : *scale), children)); ICOMMAND(uicolorvartext, "sffffs", (char *var, float *scale, float *r, float *g, float *b, char *children), addui(new VarText(var, *scale <= 0 ? 1 : *scale, *r, *g, *b), children)); ICOMMAND(uivartext, "sfs", (char *var, float *scale, char *children), addui(new VarText(var, *scale <= 0 ? 1 : *scale), children)); ICOMMAND(uitexteditor, "siifsiss", (char *name, int *length, int *height, float *scale, char *initval, int *keep, char *filter, char *children), addui(new TextEditor(name, *length, *height, *scale, initval, *keep ? EDITORFOREVER : EDITORUSED, filter[0] ? filter : NULL), children)); FVAR(cursorsensitivity, 1e-3f, 1, 1000); float cursorx = 0.5f, cursory = 0.5f; void resetcursor() { if(editmode || world->children.empty()) cursorx = cursory = 0.5f; } bool movecursor(int &dx, int &dy) { if(editmode || world->children.length()) { float scale = 500.0f / cursorsensitivity; cursorx = clamp(cursorx+dx*(screen->h/(screen->w*scale)), 0.0f, 1.0f); cursory = clamp(cursory+dy/scale, 0.0f, 1.0f); if(editmode) { if(cursorx != 1 && cursorx != 0) dx = 0; if(cursory != 1 && cursory != 0) dy = 0; return false; } return true; } return false; } bool hascursor() { if(world->children.length()) { if(mainmenu) return true; if(world && world->target(cursorx*world->w, cursory*world->h)) return true; } return false; } void getcursorpos(float &x, float &y) { if(editmode || world->children.length()) { x = cursorx; y = cursory; } else x = y = .5f; } bool keypress(int code, bool isdown, int cooked) { if(!hascursor()) return false; switch(code) { case -1: { if(isdown) { selected = world->select(cursorx*world->w, cursory*world->h); if(selected) selected->selected(selectx, selecty); } else selected = NULL; return true; } default: return world->key(code, isdown, cooked); } } VAR(mainmenu, 1, 1, 0); void clearmainmenu() { if(mainmenu && (isconnected() || haslocalclients())) { hideui("main"); mainmenu = 0; } } void setup() { world = new World; } TextEditor *textediting = NULL; int showchanges = 0; void update() { loopv(executelater) execute(executelater[i]); executelater.deletearrays(); if(showchanges && !world->findname(TYPE_WINDOW, NULL, false)) { if(identexists("showchanges")) execute("showchanges"); } if(mainmenu && !isconnected(true) && !world->children.length() && identexists("showmain")) { execute("showmain"); } world->layout(); if(hascursor()) { hovering = world->hover(cursorx*world->w, cursory*world->h); if(hovering) hovering->hovering(hoverx, hovery); } else hovering = selected = NULL; world->layout(); bool wastextediting = textediting!=NULL; if(!focused || focused->gettype() != TYPE_TEXTEDITOR) textediting = NULL; else textediting = (TextEditor *) focused; if((textediting!=NULL) != wastextediting) { SDL_EnableUNICODE(textediting!=NULL); keyrepeat(textediting!=NULL || editmode); } } void render() { if(world->children.empty()) return; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(world->x, world->x + world->w, world->y + world->h, world->y, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glColor3f(1, 1, 1); world->draw(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glEnable(GL_BLEND); } } struct change { int type; const char *desc; change() {} change(int type, const char *desc) : type(type), desc(desc) {} }; static vector needsapply; VARP(applydialog, 0, 1, 1); void addchange(const char *desc, int type) { if(!applydialog) return; loopv(needsapply) if(!strcmp(needsapply[i].desc, desc)) return; needsapply.add(change(type, desc)); UI::showchanges = 1; } void clearchanges(int type) { loopv(needsapply) { if(needsapply[i].type&type) { needsapply[i].type &= ~type; if(!needsapply[i].type) needsapply.remove(i--); } } if(needsapply.empty()) { UI::showchanges = 0; UI::hideui("changes"); } } void applychanges() { int changetypes = 0; loopv(needsapply) changetypes |= needsapply[i].type; if(changetypes&CHANGE_GFX) UI::executelater.add(newstring("resetgl")); if(changetypes&CHANGE_SOUND) UI::executelater.add(newstring("resetsound")); } ICOMMAND(pendingchanges, "", (), intret(needsapply.length())); ICOMMAND(clearchanges, "", (), clearchanges(CHANGE_GFX|CHANGE_SOUND)); COMMAND(applychanges, ""); ICOMMAND(loopchanges, "ss", (char *var, char *body), { loopv(needsapply) { alias(var, needsapply[i].desc); execute(body); } }); HVARP(fullconcolor, 0, 0x4F4F4F, 0xFFFFFF); FVARP(fullconblend, 0, .8, 1); void consolebox(int x1, int y1, int x2, int y2) { glPushMatrix(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_TEXTURE_2D); notextureshader->set(); glTranslatef(x1, y1, 0); float r = ((fullconcolor >> 16) & 0xFF) / 255.f, g = ((fullconcolor >> 8) & 0xFF) / 255.f, b = (fullconcolor & 0xFF) / 255.f; glColor4f(r, g, b, fullconblend); glBegin(GL_TRIANGLE_STRIP); glVertex2i(x1, y1); glVertex2i(x2, y1); glVertex2i(x1, y2); glVertex2i(x2, y2); glEnd(); glEnable(GL_TEXTURE_2D); defaultshader->set(); glPopMatrix(); } #endif sandboxgamemaker-2.7.1+dfsg/src/engine/texture.cpp0000664000175000017500000031626511654260372022135 0ustar showardshoward// texture.cpp: texture slot management #include "engine.h" #define FUNCNAME(name) name##1 #define DEFPIXEL uint OP(r, 0); #define PIXELOP OP(r, 0); #define BPP 1 #include "scale.h" #define FUNCNAME(name) name##2 #define DEFPIXEL uint OP(r, 0), OP(g, 1); #define PIXELOP OP(r, 0); OP(g, 1); #define BPP 2 #include "scale.h" #define FUNCNAME(name) name##3 #define DEFPIXEL uint OP(r, 0), OP(g, 1), OP(b, 2); #define PIXELOP OP(r, 0); OP(g, 1); OP(b, 2); #define BPP 3 #include "scale.h" #define FUNCNAME(name) name##4 #define DEFPIXEL uint OP(r, 0), OP(g, 1), OP(b, 2), OP(a, 3); #define PIXELOP OP(r, 0); OP(g, 1); OP(b, 2); OP(a, 3); #define BPP 4 #include "scale.h" static void scaletexture(uchar *src, uint sw, uint sh, uint bpp, uint pitch, uchar *dst, uint dw, uint dh) { if(sw == dw*2 && sh == dh*2) { switch(bpp) { case 1: return halvetexture1(src, sw, sh, pitch, dst); case 2: return halvetexture2(src, sw, sh, pitch, dst); case 3: return halvetexture3(src, sw, sh, pitch, dst); case 4: return halvetexture4(src, sw, sh, pitch, dst); } } else if(sw < dw || sh < dh || sw&(sw-1) || sh&(sh-1)) { switch(bpp) { case 1: return scaletexture1(src, sw, sh, pitch, dst, dw, dh); case 2: return scaletexture2(src, sw, sh, pitch, dst, dw, dh); case 3: return scaletexture3(src, sw, sh, pitch, dst, dw, dh); case 4: return scaletexture4(src, sw, sh, pitch, dst, dw, dh); } } else { switch(bpp) { case 1: return shifttexture1(src, sw, sh, pitch, dst, dw, dh); case 2: return shifttexture2(src, sw, sh, pitch, dst, dw, dh); case 3: return shifttexture3(src, sw, sh, pitch, dst, dw, dh); case 4: return shifttexture4(src, sw, sh, pitch, dst, dw, dh); } } } static inline void reorienttexture(uchar *src, int sw, int sh, int bpp, int stride, uchar *dst, bool flipx, bool flipy, bool swapxy, bool normals = false) { int stridex = bpp, stridey = bpp; if(swapxy) stridex *= sh; else stridey *= sw; if(flipx) { dst += (sw-1)*stridex; stridex = -stridex; } if(flipy) { dst += (sh-1)*stridey; stridey = -stridey; } uchar *srcrow = src; loopi(sh) { for(uchar *curdst = dst, *src = srcrow, *end = &srcrow[sw*bpp]; src < end;) { loopk(bpp) curdst[k] = *src++; if(normals) { if(flipx) curdst[0] = 255-curdst[0]; if(flipy) curdst[1] = 255-curdst[1]; if(swapxy) swap(curdst[0], curdst[1]); } curdst += stridex; } srcrow += stride; dst += stridey; } } static void reorients3tc(GLenum format, int blocksize, int w, int h, uchar *src, uchar *dst, bool flipx, bool flipy, bool swapxy, bool normals = false) { int bx1 = 0, by1 = 0, bx2 = min(w, 4), by2 = min(h, 4), bw = (w+3)/4, bh = (h+3)/4, stridex = blocksize, stridey = blocksize; if(swapxy) stridex *= bw; else stridey *= bh; if(flipx) { dst += (bw-1)*stridex; stridex = -stridex; bx1 += 4-bx2; bx2 = 4; } if(flipy) { dst += (bh-1)*stridey; stridey = -stridey; by1 += 4-by2; by2 = 4; } loopi(bh) { for(uchar *curdst = dst, *end = &src[bw*blocksize]; src < end; src += blocksize, curdst += stridex) { if(format == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT) { ullong salpha = lilswap(*(ullong *)src), dalpha = 0; uint xmask = flipx ? 15 : 0, ymask = flipy ? 15 : 0, xshift = 2, yshift = 4; if(swapxy) swap(xshift, yshift); for(int y = by1; y < by2; y++) for(int x = bx1; x < bx2; x++) { dalpha |= ((salpha&15) << (((xmask^x)<>= 4; } *(ullong *)curdst = lilswap(dalpha); src += 8; curdst += 8; } else if(format == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT) { uchar alpha1 = src[0], alpha2 = src[1]; ullong salpha = lilswap(*(ushort *)&src[2]) + ((ullong)lilswap(*(ushort *)&src[4])<<16) + ((ullong)lilswap(*(ushort *)&src[6])<<32), dalpha = 0; uint xmask = flipx ? 7 : 0, ymask = flipy ? 7 : 0, xshift = 0, yshift = 2; if(swapxy) swap(xshift, yshift); for(int y = by1; y < by2; y++) for(int x = bx1; x < bx2; x++) { dalpha |= ((salpha&7) << (3*((xmask^x)<>= 3; } curdst[0] = alpha1; curdst[1] = alpha2; *(ushort *)&curdst[2] = lilswap(ushort(dalpha)); *(ushort *)&curdst[4] = lilswap(ushort(dalpha>>16)); *(ushort *)&curdst[6] = lilswap(ushort(dalpha>>32)); src += 8; curdst += 8; } ushort color1 = lilswap(*(ushort *)src), color2 = lilswap(*(ushort *)&src[2]); uint sbits = lilswap(*(uint *)&src[4]); if(normals) { ushort ncolor1 = color1, ncolor2 = color2; if(flipx) { ncolor1 = (ncolor1 & ~0xF800) | (0xF800 - (ncolor1 & 0xF800)); ncolor2 = (ncolor2 & ~0xF800) | (0xF800 - (ncolor2 & 0xF800)); } if(flipy) { ncolor1 = (ncolor1 & ~0x7E0) | (0x7E0 - (ncolor1 & 0x7E0)); ncolor2 = (ncolor2 & ~0x7E0) | (0x7E0 - (ncolor2 & 0x7E0)); } if(swapxy) { ncolor1 = (ncolor1 & 0x1F) | (((((ncolor1 >> 11) & 0x1F) * 0x3F) / 0x1F) << 5) | (((((ncolor1 >> 5) & 0x3F) * 0x1F) / 0x3F) << 11); ncolor2 = (ncolor2 & 0x1F) | (((((ncolor2 >> 11) & 0x1F) * 0x3F) / 0x1F) << 5) | (((((ncolor2 >> 5) & 0x3F) * 0x1F) / 0x3F) << 11); } if(color1 <= color2 && ncolor1 > ncolor2) { color1 = ncolor2; color2 = ncolor1; } else { color1 = ncolor1; color2 = ncolor2; } } uint dbits = 0, xmask = flipx ? 3 : 0, ymask = flipy ? 3 : 0, xshift = 1, yshift = 3; if(swapxy) swap(xshift, yshift); for(int y = by1; y < by2; y++) for(int x = bx1; x < bx2; x++) { dbits |= ((sbits&3) << (((xmask^x)<>= 2; } *(ushort *)curdst = lilswap(color1); *(ushort *)&curdst[2] = lilswap(color2); *(uint *)&curdst[4] = lilswap(dbits); if(blocksize > 8) { src -= 8; curdst -= 8; } } dst += stridey; } } #define writetex(t, body) \ { \ uchar *dstrow = t.data; \ loop(y, t.h) \ { \ for(uchar *dst = dstrow, *end = &dstrow[t.w*t.bpp]; dst < end; dst += t.bpp) \ { \ body; \ } \ dstrow += t.pitch; \ } \ } #define readwritetex(t, s, body) \ { \ uchar *dstrow = t.data, *srcrow = s.data; \ loop(y, t.h) \ { \ for(uchar *dst = dstrow, *src = srcrow, *end = &srcrow[s.w*s.bpp]; src < end; dst += t.bpp, src += s.bpp) \ { \ body; \ } \ dstrow += t.pitch; \ srcrow += s.pitch; \ } \ } #define read2writetex(t, s1, src1, s2, src2, body) \ { \ uchar *dstrow = t.data, *src1row = s1.data, *src2row = s2.data; \ loop(y, t.h) \ { \ for(uchar *dst = dstrow, *end = &dstrow[t.w*t.bpp], *src1 = src1row, *src2 = src2row; dst < end; dst += t.bpp, src1 += s1.bpp, src2 += s2.bpp) \ { \ body; \ } \ dstrow += t.pitch; \ src1row += s1.pitch; \ src2row += s2.pitch; \ } \ } void texreorient(ImageData &s, bool flipx, bool flipy, bool swapxy, int type = TEX_DIFFUSE) { ImageData d(swapxy ? s.h : s.w, swapxy ? s.w : s.h, s.bpp, s.levels, s.align, s.compressed); switch(s.compressed) { case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: { uchar *dst = d.data, *src = s.data; loopi(s.levels) { reorients3tc(s.compressed, s.bpp, max(s.w>>i, 1), max(s.h>>i, 1), src, dst, flipx, flipy, swapxy, type==TEX_NORMAL); src += s.calclevelsize(i); dst += d.calclevelsize(i); } break; } default: reorienttexture(s.data, s.w, s.h, s.bpp, s.pitch, d.data, flipx, flipy, swapxy, type==TEX_NORMAL); break; } s.replace(d); } void texrotate(ImageData &s, int numrots, int type = TEX_DIFFUSE) { // 1..3 rotate through 90..270 degrees, 4 flips X, 5 flips Y if(numrots>=1 && numrots<=5) texreorient(s, numrots>=2 && numrots<=4, // flip X on 180/270 degrees numrots<=2 || numrots==5, // flip Y on 90/180 degrees (numrots&5)==1, // swap X/Y on 90/270 degrees type); } void texoffset(ImageData &s, int xoffset, int yoffset) { xoffset = max(xoffset, 0); xoffset %= s.w; yoffset = max(yoffset, 0); yoffset %= s.h; if(!xoffset && !yoffset) return; ImageData d(s.w, s.h, s.bpp); uchar *src = s.data; loop(y, s.h) { uchar *dst = (uchar *)d.data+((y+yoffset)%d.h)*d.pitch; memcpy(dst+xoffset*s.bpp, src, (s.w-xoffset)*s.bpp); memcpy(dst, src+(s.w-xoffset)*s.bpp, xoffset*s.bpp); src += s.pitch; } s.replace(d); } void texmad(ImageData &s, const vec &mul, const vec &add) { int maxk = min(int(s.bpp), 3); writetex(s, loopk(maxk) dst[k] = uchar(clamp(dst[k]*mul[k] + 255*add[k], 0.0f, 255.0f)); ); } void texcolorify(ImageData &s, const vec &color, vec weights) { if(s.bpp < 3) return; if(weights.iszero()) weights = vec(0.21f, 0.72f, 0.07f); writetex(s, float lum = dst[0]*weights.x + dst[1]*weights.y + dst[2]*weights.z; loopk(3) dst[k] = uchar(clamp(lum*color[k], 0.0f, 255.0f)); ); } void texffmask(ImageData &s, float glowscale, float envscale) { if(renderpath!=R_FIXEDFUNCTION) return; if(nomasks || s.bpp<3) { s.cleanup(); return; } const int minval = 0x18; bool glow = false, envmap = true; writetex(s, if(dst[1]>minval) glow = true; if(dst[2]>minval) { glow = envmap = true; goto needmask; } ); if(!glow && !envmap) { s.cleanup(); return; } needmask: ImageData m(s.w, s.h, envmap ? 2 : 1); readwritetex(m, s, dst[0] = uchar(src[1]*glowscale); if(envmap) dst[1] = uchar(src[2]*envscale); ); s.replace(m); } void texdup(ImageData &s, int srcchan, int dstchan) { if(srcchan==dstchan || max(srcchan, dstchan) >= s.bpp) return; writetex(s, dst[dstchan] = dst[srcchan]); } void texdecal(ImageData &s) { if(renderpath!=R_FIXEDFUNCTION || hasTE) return; ImageData m(s.w, s.w, 2); readwritetex(m, s, dst[0] = src[0]; dst[1] = 255 - src[0]; ); s.replace(m); } void texmix(ImageData &s, int c1, int c2, int c3, int c4) { int numchans = c1 < 0 ? 0 : (c2 < 0 ? 1 : (c3 < 0 ? 2 : (c4 < 0 ? 3 : 4))); if(numchans <= 0) return; ImageData d(s.w, s.h, numchans); readwritetex(d, s, switch(numchans) { case 4: dst[3] = src[c4]; case 3: dst[2] = src[c3]; case 2: dst[1] = src[c2]; case 1: dst[0] = src[c1]; } ); s.replace(d); } void texgrey(ImageData &s) { if(s.bpp <= 2) return; ImageData d(s.w, s.h, s.bpp >= 4 ? 2 : 1); if(s.bpp >= 4) { readwritetex(d, s, dst[0] = src[0]; dst[1] = src[3]; ); } else { readwritetex(d, s, dst[0] = src[0]); } s.replace(d); } void texpremul(ImageData &s) { switch(s.bpp) { case 2: writetex(s, dst[0] = uchar((uint(dst[0])*uint(dst[1]))/255); ); break; case 4: writetex(s, uint alpha = dst[3]; dst[0] = uchar((uint(dst[0])*alpha)/255); dst[1] = uchar((uint(dst[1])*alpha)/255); dst[2] = uchar((uint(dst[2])*alpha)/255); ); break; } } void texagrad(ImageData &s, float x2, float y2, float x1, float y1) { if(s.bpp != 2 && s.bpp != 4) return; y1 = 1 - y1; y2 = 1 - y2; float minx = 1, miny = 1, maxx = 1, maxy = 1; if(x1 != x2) { minx = (0 - x1) / (x2 - x1); maxx = (1 - x1) / (x2 - x1); } if(y1 != y2) { miny = (0 - y1) / (y2 - y1); maxy = (1 - y1) / (y2 - y1); } float dx = (maxx - minx)/max(s.w-1, 1), dy = (maxy - miny)/max(s.h-1, 1), cury = miny; for(uchar *dstrow = s.data + s.bpp - 1, *endrow = dstrow + s.h*s.pitch; dstrow < endrow; dstrow += s.pitch) { float curx = minx; for(uchar *dst = dstrow, *end = &dstrow[s.w*s.bpp]; dst < end; dst += s.bpp) { dst[0] = uchar(dst[0]*clamp(curx, 0.0f, 1.0f)*clamp(cury, 0.0f, 1.0f)); curx += dx; } cury += dy; } } VAR(hwtexsize, 1, 0, 0); VAR(hwcubetexsize, 1, 0, 0); VAR(hwmaxaniso, 1, 0, 0); VARFP(maxtexsize, 0, 0, 1<<12, initwarning("texture quality", INIT_LOAD)); VARFP(reducefilter, 0, 1, 1, initwarning("texture quality", INIT_LOAD)); VARFP(texreduce, 0, 0, 12, initwarning("texture quality", INIT_LOAD)); VARFP(texcompress, 0, 1<<10, 1<<12, initwarning("texture quality", INIT_LOAD)); VARFP(texcompressquality, -1, -1, 1, setuptexcompress()); VARFP(trilinear, 0, 1, 1, initwarning("texture filtering", INIT_LOAD)); VARFP(bilinear, 0, 1, 1, initwarning("texture filtering", INIT_LOAD)); VARFP(aniso, 0, 0, 16, initwarning("texture filtering", INIT_LOAD)); void setuptexcompress() { if(!hasTC) return; GLenum hint = GL_DONT_CARE; switch(texcompressquality) { case 1: hint = GL_NICEST; break; case 0: hint = GL_FASTEST; break; } glHint(GL_TEXTURE_COMPRESSION_HINT_ARB, hint); } GLenum compressedformat(GLenum format, int w, int h, int force = 0) { if(hasTC && texcompress && force >= 0 && (force || max(w, h) >= texcompress)) switch(format) { case GL_RGB5: case GL_RGB8: #ifdef __APPLE__ case GL_LUMINANCE: case GL_RGB: return GL_COMPRESSED_RGB_ARB; case GL_LUMINANCE_ALPHA: case GL_RGBA: return GL_COMPRESSED_RGBA_ARB; #else case GL_LUMINANCE: case GL_RGB: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; case GL_LUMINANCE_ALPHA: case GL_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; #endif } return format; } int formatsize(GLenum format) { switch(format) { case GL_LUMINANCE: case GL_ALPHA: return 1; case GL_LUMINANCE_ALPHA: return 2; case GL_RGB: return 3; case GL_RGBA: return 4; default: return 4; } } VARFP(hwmipmap, 0, 0, 1, initwarning("texture filtering", INIT_LOAD)); VARFP(usenp2, 0, 0, 1, initwarning("texture quality", INIT_LOAD)); void resizetexture(int w, int h, bool mipmap, bool canreduce, GLenum target, int compress, int &tw, int &th) { int hwlimit = target==GL_TEXTURE_CUBE_MAP_ARB ? hwcubetexsize : hwtexsize, sizelimit = mipmap && maxtexsize ? min(maxtexsize, hwlimit) : hwlimit; if(compress > 0 && !hasTC) { w = max(w/compress, 1); h = max(h/compress, 1); } if(canreduce && texreduce) { w = max(w>>texreduce, 1); h = max(h>>texreduce, 1); } w = min(w, sizelimit); h = min(h, sizelimit); if((!hasNP2 || !usenp2) && target!=GL_TEXTURE_RECTANGLE_ARB && (w&(w-1) || h&(h-1))) { tw = th = 1; while(tw < w) tw *= 2; while(th < h) th *= 2; if(w < tw - tw/4) tw /= 2; if(h < th - th/4) th /= 2; } else { tw = w; th = h; } } void uploadtexture(GLenum target, GLenum internal, int tw, int th, GLenum format, GLenum type, void *pixels, int pw, int ph, int pitch, bool mipmap) { int bpp = formatsize(format), row = 0, rowalign = 0; if(!pitch) pitch = pw*bpp; uchar *buf = NULL; if(pw!=tw || ph!=th) { buf = new uchar[tw*th*bpp]; scaletexture((uchar *)pixels, pw, ph, bpp, pitch, buf, tw, th); } else if(tw*bpp != pitch) { row = pitch/bpp; rowalign = texalign(pixels, pitch, 1); while(rowalign > 0 && ((row*bpp + rowalign - 1)/rowalign)*rowalign != pitch) rowalign >>= 1; if(!rowalign) { row = 0; buf = new uchar[tw*th*bpp]; loopi(th) memcpy(&buf[i*tw*bpp], &((uchar *)pixels)[i*pitch], tw*bpp); } } for(int level = 0, align = 0;; level++) { uchar *src = buf ? buf : (uchar *)pixels; if(buf) pitch = tw*bpp; int srcalign = row > 0 ? rowalign : texalign(src, pitch, 1); if(align != srcalign) glPixelStorei(GL_UNPACK_ALIGNMENT, align = srcalign); if(row > 0) glPixelStorei(GL_UNPACK_ROW_LENGTH, row); if(target==GL_TEXTURE_1D) glTexImage1D(target, level, internal, tw, 0, format, type, src); else glTexImage2D(target, level, internal, tw, th, 0, format, type, src); if(row > 0) glPixelStorei(GL_UNPACK_ROW_LENGTH, row = 0); if(!mipmap || (hasGM && hwmipmap) || max(tw, th) <= 1) break; int srcw = tw, srch = th; if(tw > 1) tw /= 2; if(th > 1) th /= 2; if(!buf) buf = new uchar[tw*th*bpp]; scaletexture(src, srcw, srch, bpp, pitch, buf, tw, th); } if(buf) delete[] buf; } void uploadcompressedtexture(GLenum target, GLenum subtarget, GLenum format, int w, int h, uchar *data, int align, int blocksize, int levels, bool mipmap) { int hwlimit = target==GL_TEXTURE_CUBE_MAP_ARB ? hwcubetexsize : hwtexsize, sizelimit = levels > 1 && maxtexsize ? min(maxtexsize, hwlimit) : hwlimit; int level = 0; loopi(levels) { int size = ((w + align-1)/align) * ((h + align-1)/align) * blocksize; if(w <= sizelimit && h <= sizelimit) { if(target==GL_TEXTURE_1D) glCompressedTexImage1D_(subtarget, level, format, w, 0, size, data); else glCompressedTexImage2D_(subtarget, level, format, w, h, 0, size, data); level++; if(!mipmap) break; } if(max(w, h) <= 1) break; if(w > 1) w /= 2; if(h > 1) h /= 2; data += size; } } GLenum textarget(GLenum subtarget) { switch(subtarget) { case GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB: case GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB: case GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB: case GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB: return GL_TEXTURE_CUBE_MAP_ARB; } return subtarget; } GLenum uncompressedformat(GLenum format) { switch(format) { case GL_COMPRESSED_RGB_ARB: case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: return GL_RGB; case GL_COMPRESSED_RGBA_ARB: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: return GL_RGBA; } return GL_FALSE; } void setuptexparameters(int tnum, void *pixels, int clamp, int filter, GLenum format, GLenum target) { glBindTexture(target, tnum); glTexParameteri(target, GL_TEXTURE_WRAP_S, clamp&1 ? GL_CLAMP_TO_EDGE : GL_REPEAT); if(target!=GL_TEXTURE_1D) glTexParameteri(target, GL_TEXTURE_WRAP_T, clamp&2 ? GL_CLAMP_TO_EDGE : GL_REPEAT); if(target==GL_TEXTURE_2D && hasAF && min(aniso, hwmaxaniso) > 0 && filter > 1) glTexParameteri(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, min(aniso, hwmaxaniso)); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filter && bilinear ? GL_LINEAR : GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filter > 1 ? (trilinear ? (bilinear ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_LINEAR) : (bilinear ? GL_LINEAR_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_NEAREST)) : (filter && bilinear ? GL_LINEAR : GL_NEAREST)); if(hasGM && filter > 1 && pixels && hwmipmap && !uncompressedformat(format)) glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); } void createtexture(int tnum, int w, int h, void *pixels, int clamp, int filter, GLenum component, GLenum subtarget, int pw, int ph, int pitch, bool resize, GLenum format) { GLenum target = textarget(subtarget), type = GL_UNSIGNED_BYTE; switch(component) { case GL_FLOAT_RG16_NV: case GL_FLOAT_R32_NV: case GL_RGB16F_ARB: case GL_RGB32F_ARB: if(!format) format = GL_RGB; type = GL_FLOAT; break; case GL_RGBA16F_ARB: case GL_RGBA32F_ARB: if(!format) format = GL_RGBA; type = GL_FLOAT; break; case GL_DEPTH_COMPONENT16: case GL_DEPTH_COMPONENT24: case GL_DEPTH_COMPONENT32: if(!format) format = GL_DEPTH_COMPONENT; break; case GL_RGB5: case GL_RGB8: case GL_RGB16: case GL_COMPRESSED_RGB_ARB: case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: if(!format) format = GL_RGB; break; case GL_RGBA8: case GL_RGBA16: case GL_COMPRESSED_RGBA_ARB: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: if(!format) format = GL_RGBA; break; } if(!format) format = component; if(tnum) setuptexparameters(tnum, pixels, clamp, filter, format, target); if(!pw) pw = w; if(!ph) ph = h; int tw = w, th = h; bool mipmap = filter > 1 && pixels; if(resize && pixels) { resizetexture(w, h, mipmap, false, target, 0, tw, th); if(mipmap) component = compressedformat(component, tw, th); } uploadtexture(subtarget, component, tw, th, format, type, pixels, pw, ph, pitch, mipmap); } void createcompressedtexture(int tnum, int w, int h, uchar *data, int align, int blocksize, int levels, int clamp, int filter, GLenum format, GLenum subtarget) { GLenum target = textarget(subtarget); if(tnum) setuptexparameters(tnum, data, clamp, filter, format, target); uploadcompressedtexture(target, subtarget, format, w, h, data, align, blocksize, levels, filter > 1); } hashtable textures; Texture *notexture = NULL; // used as default, ensured to be loaded static GLenum texformat(int bpp) { switch(bpp) { case 1: return GL_LUMINANCE; case 2: return GL_LUMINANCE_ALPHA; case 3: return GL_RGB; case 4: return GL_RGBA; default: return 0; } } int texalign(void *data, int w, int bpp) { size_t address = size_t(data) | (w*bpp); if(address&1) return 1; if(address&2) return 2; if(address&4) return 4; return 8; } static Texture *newtexture(Texture *t, const char *rname, ImageData &s, int clamp = 0, bool mipit = true, bool canreduce = false, bool transient = false, int compress = 0) { if(!t) { char *key = newstring(rname); t = &textures[key]; t->name = key; } t->clamp = clamp; t->mipmap = mipit; t->type = Texture::IMAGE; if(transient) t->type |= Texture::TRANSIENT; if(!s.data) { t->type |= Texture::STUB; t->w = t->h = t->xs = t->ys = t->bpp = 0; return t; } if(s.compressed) t->type |= Texture::COMPRESSED; t->bpp = s.compressed ? formatsize(uncompressedformat(s.compressed)) : s.bpp; t->w = t->xs = s.w; t->h = t->ys = s.h; int filter = !canreduce || reducefilter ? (mipit ? 2 : 1) : 0; glGenTextures(1, &t->id); if(s.compressed) { uchar *data = s.data; int levels = s.levels, level = 0; if(canreduce && texreduce) loopi(min(texreduce, s.levels-1)) { data += s.calclevelsize(level++); levels--; if(t->w > 1) t->w /= 2; if(t->h > 1) t->h /= 2; } int sizelimit = mipit && maxtexsize ? min(maxtexsize, hwtexsize) : hwtexsize; while(t->w > sizelimit || t->h > sizelimit) { data += s.calclevelsize(level++); levels--; if(t->w > 1) t->w /= 2; if(t->h > 1) t->h /= 2; } createcompressedtexture(t->id, t->w, t->h, data, s.align, s.bpp, levels, clamp, filter, s.compressed, GL_TEXTURE_2D); } else { resizetexture(t->w, t->h, mipit, canreduce, GL_TEXTURE_2D, compress, t->w, t->h); GLenum format = texformat(t->bpp), component = compressedformat(format, t->w, t->h, compress); createtexture(t->id, t->w, t->h, s.data, clamp, filter, component, GL_TEXTURE_2D, t->xs, t->ys, s.pitch, false, format); } return t; } #if SDL_BYTEORDER == SDL_BIG_ENDIAN #define RGBAMASKS 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff #define RGBMASKS 0xff0000, 0x00ff00, 0x0000ff, 0 #else #define RGBAMASKS 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 #define RGBMASKS 0x0000ff, 0x00ff00, 0xff0000, 0 #endif SDL_Surface *wrapsurface(void *data, int width, int height, int bpp) { switch(bpp) { case 3: return SDL_CreateRGBSurfaceFrom(data, width, height, 8*bpp, bpp*width, RGBMASKS); case 4: return SDL_CreateRGBSurfaceFrom(data, width, height, 8*bpp, bpp*width, RGBAMASKS); } return NULL; } SDL_Surface *creatergbsurface(SDL_Surface *os) { SDL_Surface *ns = SDL_CreateRGBSurface(SDL_SWSURFACE, os->w, os->h, 24, RGBMASKS); if(ns) SDL_BlitSurface(os, NULL, ns, NULL); SDL_FreeSurface(os); return ns; } SDL_Surface *creatergbasurface(SDL_Surface *os) { SDL_Surface *ns = SDL_CreateRGBSurface(SDL_SWSURFACE, os->w, os->h, 32, RGBAMASKS); if(ns) { SDL_SetAlpha(os, 0, 0); SDL_BlitSurface(os, NULL, ns, NULL); } SDL_FreeSurface(os); return ns; } bool checkgrayscale(SDL_Surface *s) { // gray scale images have 256 levels, no colorkey, and the palette is a ramp if(s->format->palette) { if(s->format->palette->ncolors != 256 || s->format->colorkey) return false; const SDL_Color *colors = s->format->palette->colors; loopi(256) if(colors[i].r != i || colors[i].g != i || colors[i].b != i) return false; } return true; } SDL_Surface *fixsurfaceformat(SDL_Surface *s) { if(!s) return NULL; if(!s->pixels || min(s->w, s->h) <= 0 || s->format->BytesPerPixel <= 0) { SDL_FreeSurface(s); return NULL; } static const uint rgbmasks[] = { RGBMASKS }, rgbamasks[] = { RGBAMASKS }; switch(s->format->BytesPerPixel) { case 1: if(!checkgrayscale(s)) return s->format->colorkey ? creatergbasurface(s) : creatergbsurface(s); break; case 3: if(s->format->Rmask != rgbmasks[0] || s->format->Gmask != rgbmasks[1] || s->format->Bmask != rgbmasks[2]) return creatergbsurface(s); break; case 4: if(s->format->Rmask != rgbamasks[0] || s->format->Gmask != rgbamasks[1] || s->format->Bmask != rgbamasks[2] || s->format->Amask != rgbamasks[3]) return s->format->Amask ? creatergbasurface(s) : creatergbsurface(s); break; } return s; } void texflip(ImageData &s) { ImageData d(s.w, s.h, s.bpp); uchar *dst = d.data, *src = &s.data[s.pitch*s.h]; loopi(s.h) { src -= s.pitch; memcpy(dst, src, s.bpp*s.w); dst += d.pitch; } s.replace(d); } void texnormal(ImageData &s, int emphasis) { ImageData d(s.w, s.h, 3); uchar *src = s.data, *dst = d.data; loop(y, s.h) loop(x, s.w) { vec normal(0.0f, 0.0f, 255.0f/emphasis); normal.x += src[y*s.pitch + ((x+s.w-1)%s.w)*s.bpp]; normal.x -= src[y*s.pitch + ((x+1)%s.w)*s.bpp]; normal.y += src[((y+s.h-1)%s.h)*s.pitch + x*s.bpp]; normal.y -= src[((y+1)%s.h)*s.pitch + x*s.bpp]; normal.normalize(); *dst++ = uchar(127.5f + normal.x*127.5f); *dst++ = uchar(127.5f + normal.y*127.5f); *dst++ = uchar(127.5f + normal.z*127.5f); } s.replace(d); } template static void blurtexture(int w, int h, uchar *dst, const uchar *src) { static const int matrix3x3[9] = { 0x10, 0x20, 0x10, 0x20, 0x40, 0x20, 0x10, 0x20, 0x10 }; static const int matrix5x5[25] = { 0x05, 0x05, 0x09, 0x05, 0x05, 0x05, 0x0A, 0x14, 0x0A, 0x05, 0x09, 0x14, 0x28, 0x14, 0x09, 0x05, 0x0A, 0x14, 0x0A, 0x05, 0x05, 0x05, 0x09, 0x05, 0x05 }; const int *mat = n > 1 ? matrix5x5 : matrix3x3; int mstride = 2*n + 1, mstartoffset = n*(mstride + 1), stride = bpp*w, startoffset = n*bpp, nextoffset1 = stride + mstride*bpp, nextoffset2 = stride - mstride*bpp; loop(y, h) loop(x, w) { loopk(3) { int val = 0; const uchar *p = src - startoffset; const int *m = mat + mstartoffset; for(int t = y; t >= y-n; t--, p -= nextoffset1, m -= mstride) { if(t < 0) p += stride; int a = 0; if(n > 1) { a += m[-2]; if(x >= 2) { val += *p * a; a = 0; } p += bpp; } a += m[-1]; if(x >= 1) { val += *p * a; a = 0; } p += bpp; int c = *p; val += c * (a + m[0]); p += bpp; if(x+1 < w) c = *p; val += c * m[1]; p += bpp; if(n > 1) { if(x+2 < w) c = *p; val += c * m[2]; p += bpp; } } p = src - startoffset + stride; m = mat + mstartoffset + mstride; for(int t = y+1; t <= y+n; t++, p += nextoffset2, m += mstride) { if(t >= h) p -= stride; int a = 0; if(n > 1) { a += m[-2]; if(x >= 2) { val += *p * a; a = 0; } p += bpp; } a += m[-1]; if(x >= 1) { val += *p * a; a = 0; } p += bpp; int c = *p; val += c * (a + m[0]); p += bpp; if(x+1 < w) c = *p; val += c * m[1]; p += bpp; if(n > 1) { if(x+2 < w) c = *p; val += c * m[2]; p += bpp; } } *dst++ = val>>8; src++; } if(bpp > 3) *dst++ = *src++; } } void blurtexture(int n, int bpp, int w, int h, uchar *dst, const uchar *src) { switch((clamp(n, 1, 2)<<4) | bpp) { case 0x13: blurtexture<1, 3>(w, h, dst, src); break; case 0x23: blurtexture<2, 3>(w, h, dst, src); break; case 0x14: blurtexture<1, 4>(w, h, dst, src); break; case 0x24: blurtexture<2, 4>(w, h, dst, src); break; } } void texblur(ImageData &s, int n, int r) { if(s.bpp < 3) return; loopi(r) { ImageData d(s.w, s.h, s.bpp); blurtexture(n, s.bpp, s.w, s.h, d.data, s.data); s.replace(d); } } void scaleimage(ImageData &s, int w, int h) { ImageData d(w, h, s.bpp); scaletexture(s.data, s.w, s.h, s.bpp, s.pitch, d.data, w, h); s.replace(d); } #define readwritergbtex(t, s, body) \ { \ if(t.bpp >= 3) { readwritetex(t, s, body); } \ else \ { \ ImageData rgb(t.w, t.h, 3); \ read2writetex(rgb, t, orig, s, src, \ { \ switch(t.bpp) \ { \ case 1: dst[0] = orig[0]; dst[1] = orig[0]; dst[2] = orig[0]; break; \ case 2: dst[0] = orig[0]; dst[1] = orig[1]; dst[2] = orig[1]; break; \ } \ body; \ }); \ t.replace(rgb); \ } \ } void forcergbimage(ImageData &s) { if(s.bpp >= 3) return; ImageData d(s.w, s.h, 3); readwritetex(d, s, switch(s.bpp) { case 1: dst[0] = src[0]; dst[1] = src[0]; dst[2] = src[0]; break; case 2: dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[1]; break; } ); s.replace(d); } #define readwritergbatex(t, s, body) \ { \ if(t.bpp >= 4) { readwritetex(t, s, body); } \ else \ { \ ImageData rgba(t.w, t.h, 4); \ read2writetex(rgba, t, orig, s, src, \ { \ switch(t.bpp) \ { \ case 1: dst[0] = orig[0]; dst[1] = orig[0]; dst[2] = orig[0]; break; \ case 2: dst[0] = orig[0]; dst[1] = orig[1]; dst[2] = orig[1]; break; \ case 3: dst[0] = orig[0]; dst[1] = orig[1]; dst[2] = orig[2]; break; \ } \ body; \ }); \ t.replace(rgba); \ } \ } void forcergbaimage(ImageData &s) { if(s.bpp >= 4) return; ImageData d(s.w, s.h, 4); readwritetex(d, s, switch(s.bpp) { case 1: dst[0] = src[0]; dst[1] = src[0]; dst[2] = src[0]; break; case 2: dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[1]; break; case 3: dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; break; } ); s.replace(d); } bool canloadsurface(const char *name) { stream *f = openfile(name, "rb"); if(!f) return false; delete f; return true; } SDL_Surface *loadsurface(const char *name) { const char *exts[] = {"", ".png", ".jpg", ".tga", ".bmp"}; SDL_Surface *s = NULL; loopi(sizeof(exts)/sizeof(exts[0])) { defformatstring(newname)("%s%s", name, exts[i]); stream *z = openzipfile(newname, "rb"); if(z) { SDL_RWops *rw = z->rwops(); if(rw) { s = IMG_Load_RW(rw, 0); SDL_FreeRW(rw); } delete z; } if(!s) s = IMG_Load(findfile(newname, "rb")); if(s) break; } return fixsurfaceformat(s); } static vec parsevec(const char *arg) { vec v(0, 0, 0); int i = 0; for(; arg[0] && (!i || arg[0]=='/') && i<3; arg += strcspn(arg, "/,><"), i++) { if(i) arg++; v[i] = atof(arg); } if(i==1) v.y = v.z = v.x; return v; } VAR(usedds, 0, 1, 1); VAR(dbgdds, 0, 0, 1); static bool texturedata(ImageData &d, const char *tname, Slot::Tex *tex = NULL, bool msg = true, int *compress = NULL) { const char *cmds = NULL, *file = tname; if(!tname) { if(!tex) return false; if(tex->name[0]=='<') { cmds = tex->name; file = strrchr(tex->name, '>'); if(!file) { if(msg) conoutf(CON_ERROR, "could not load texture packages/%s", tex->name); return false; } file++; } else file = tex->name; static string pname; formatstring(pname)("packages/%s", file); file = path(pname); } else if(tname[0]=='<') { cmds = tname; file = strrchr(tname, '>'); if(!file) { if(msg) conoutf(CON_ERROR, "could not load texture %s", tname); return NULL; } file++; } bool raw = !usedds || !compress, dds = false; for(const char *pcmds = cmds; pcmds;) { #define PARSETEXCOMMANDS(cmds) \ const char *cmd = NULL, *end = NULL, *arg[4] = { NULL, NULL, NULL, NULL }; \ cmd = &cmds[1]; \ end = strchr(cmd, '>'); \ if(!end) break; \ cmds = strchr(cmd, '<'); \ size_t len = strcspn(cmd, ":,><"); \ loopi(4) \ { \ arg[i] = strchr(i ? arg[i-1] : cmd, i ? ',' : ':'); \ if(!arg[i] || arg[i] >= end) arg[i] = ""; \ else arg[i]++; \ } PARSETEXCOMMANDS(pcmds); if(!strncmp(cmd, "noff", len)) { if(renderpath==R_FIXEDFUNCTION) return true; } else if(!strncmp(cmd, "ffmask", len) || !strncmp(cmd, "ffskip", len)) { if(renderpath==R_FIXEDFUNCTION) raw = true; } else if(!strncmp(cmd, "decal", len)) { if(renderpath==R_FIXEDFUNCTION && !hasTE) raw = true; } else if(!strncmp(cmd, "dds", len)) dds = true; else if(!strncmp(cmd, "thumbnail", len)) raw = true; else if(!strncmp(cmd, "stub", len)) return canloadsurface(file); } if(msg) renderprogress(loadprogress, file); int flen = strlen(file); if(flen >= 4 && (!strcasecmp(file + flen - 4, ".dds") || dds)) { string dfile; copystring(dfile, file); memcpy(dfile + flen - 4, ".dds", 4); if(!raw && hasTC && loaddds(dfile, d)) return true; if(!dds || dbgdds) { if(msg) conoutf(CON_ERROR, "could not load texture %s", dfile); return false; } } SDL_Surface *s = loadsurface(file); if(!s) { if(msg) conoutf(CON_ERROR, "could not load texture %s", file); return false; } int bpp = s->format->BitsPerPixel; if(bpp%8 || !texformat(bpp/8)) { SDL_FreeSurface(s); conoutf(CON_ERROR, "texture must be 8, 16, 24, or 32 bpp: %s", file); return false; } if(max(s->w, s->h) > (1<<12)) { SDL_FreeSurface(s); conoutf(CON_ERROR, "texture size exceeded %dx%d pixels: %s", 1<<12, 1<<12, file); return false; } d.wrap(s); while(cmds) { PARSETEXCOMMANDS(cmds); if(!strncmp(cmd, "mad", len)) texmad(d, parsevec(arg[0]), parsevec(arg[1])); else if(!strncmp(cmd, "colorify", len)) texcolorify(d, parsevec(arg[0]), parsevec(arg[1])); else if(!strncmp(cmd, "scale", len) || !strncmp(cmd, "thumbnail", len)) { int w = atoi(arg[0]), h = atoi(arg[1]); if(w <= 0 || w > (1<<12)) w = 64; if(h <= 0 || h > (1<<12)) h = w; if(d.w > w || d.h > h) scaleimage(d, w, h); } else if(!strncmp(cmd, "ffmask", len)) { texffmask(d, atof(arg[0]), atof(arg[1])); if(!d.data) break; } else if(!strncmp(cmd, "normal", len)) { int emphasis = atoi(arg[0]); texnormal(d, emphasis > 0 ? emphasis : 3); } else if(!strncmp(cmd, "dup", len)) texdup(d, atoi(arg[0]), atoi(arg[1])); else if(!strncmp(cmd, "decal", len)) texdecal(d); else if(!strncmp(cmd, "offset", len)) texoffset(d, atoi(arg[0]), atoi(arg[1])); else if(!strncmp(cmd, "rotate", len)) texrotate(d, atoi(arg[0]), tex ? tex->type : 0); else if(!strncmp(cmd, "reorient", len)) texreorient(d, atoi(arg[0])>0, atoi(arg[1])>0, atoi(arg[2])>0, tex ? tex->type : TEX_DIFFUSE); else if(!strncmp(cmd, "mix", len)) texmix(d, *arg[0] ? atoi(arg[0]) : -1, *arg[1] ? atoi(arg[1]) : -1, *arg[2] ? atoi(arg[2]) : -1, *arg[3] ? atoi(arg[3]) : -1); else if(!strncmp(cmd, "grey", len)) texgrey(d); else if(!strncmp(cmd, "blur", len)) { int emphasis = atoi(arg[0]), repeat = atoi(arg[1]); texblur(d, emphasis > 0 ? clamp(emphasis, 1, 2) : 1, repeat > 0 ? repeat : 1); } else if(!strncmp(cmd, "premul", len)) texpremul(d); else if(!strncmp(cmd, "agrad", len)) texagrad(d, atof(arg[0]), atof(arg[1]), atof(arg[2]), atof(arg[3])); else if(!strncmp(cmd, "compress", len) || !strncmp(cmd, "dds", len)) { int scale = atoi(arg[0]); if(scale <= 0) scale = 2; if(compress) *compress = scale; } else if(!strncmp(cmd, "nocompress", len)) { if(compress) *compress = -1; } else if(!strncmp(cmd, "ffskip", len)) { if(renderpath==R_FIXEDFUNCTION) break; } } return true; } void loadalphamask(Texture *t) { if(t->alphamask || t->bpp!=4 || t->type&Texture::COMPRESSED) return; ImageData s; if(!texturedata(s, t->name, NULL, false) || !s.data || s.bpp!=4 || s.compressed) return; t->alphamask = new uchar[s.h * ((s.w+7)/8)]; uchar *srcrow = s.data, *dst = t->alphamask-1; loop(y, s.h) { uchar *src = srcrow+s.bpp-1; loop(x, s.w) { int offset = x%8; if(!offset) *++dst = 0; if(*src) *dst |= 1<id); return t != notexture; } bool settexture(Texture *&tex) { if(!tex) tex = notexture; glBindTexture(GL_TEXTURE_2D, tex->id); return tex != notexture; } const char *textypename(int i) { switch(i) { case TEX_DIFFUSE: return "0"; case TEX_DECAL: return "d"; case TEX_NORMAL: return "n"; case TEX_GLOW: return "g"; case TEX_SPEC: return "s"; case TEX_DEPTH: return "z"; case TEX_ENVMAP: return "e"; case TEX_UNKNOWN: default: return "1"; } } vector vslots; vector slots; MSlot materialslots[MATF_VOLUME+1]; Slot dummyslot; VSlot dummyvslot(&dummyslot); vector texanim; void updatetexanims() { loopv(texanim) { TexAnim &anim = *texanim[i]; if(anim.frames.length() && anim.on && anim.delay >= 0 && lastmillis-anim.lastupdate >= anim.delay) { int updates = (lastmillis - anim.lastupdate) / anim.delay; anim.lastupdate += updates * anim.delay; anim.pos+= updates; anim.pos %= anim.frames.length(); slots[anim.frames[0].slot]->sts[0].t->id = anim.frames[anim.pos].num; } //if off, just pause, keep at current frame } } void texaniminit(int *n) { loopv(texanim) { if(texanim[i]->frames[0].slot == *n) {conoutf("slot %i already initiated for animation", *n); return;} } if(!slots.inrange(*n)) { conoutf("undefiend slot %i", *n); return; } Slot &tmp = lookupslot(*n, true); //load the texture, prevents crashes due to NULL textures in the slot[i].sts vector texanim.add(new TexAnim(*n, tmp.sts[0].t->id)); } void texanimadd(int *d, int *s) { int anim = -1, tex = -1; loopv(texanim) { if(texanim[i]->frames[0].slot == *d) anim = i; if(texanim[i]->frames[0].slot == *s) tex = i; //ie, the replacement slot is animated } if(anim >= 0 && slots.inrange(*d) && slots.inrange(*s)) { if(tex >= 0) texanim[anim]->frames.add(texanim[tex]->frames[0]); //add the original frame, not the current one, if animated else { Slot &tmp = lookupslot(*s, true); //load the texture, prevents crashes due to NULL textures in the slot[i].sts vector texanim[anim]->frames.add(frame(*s, tmp.sts[0].t->id)); } } else { if(anim < 0) conoutf("slot %i not initiated for animation", *d); if(!slots.inrange(*d)) conoutf("slot %i not defined", *d); if(!slots.inrange(*s)) conoutf("replacement slot %i not defined, ignoring frame", *s); } } void texanimstart(int *n) { loopv(texanim) { if(texanim[i]->frames[0].slot == *n) { if(texanim[i]->pausemillis) { texanim[i]->lastupdate = lastmillis - (texanim[i]->pausemillis - texanim[i]->lastupdate); //ie, resume texanim[i]->pausemillis = 0; } else texanim[i]->lastupdate = lastmillis; texanim[i]->on = true; return; } } conoutf("slot %i not initiated for animation", *n); } void texanimdelay(int *n, int *d) { loopv(texanim) { if(texanim[i]->frames[0].slot == *n) { if(*d <= 0) { conoutf("invalid delay time (%i) for slot %i", *d, *n); return; } texanim[i]->delay = *d; return; } } conoutf("slot %i not initiated for animation", *n); } void texanimstop(int *n) { loopv(texanim) { if(texanim[i]->frames[0].slot == *n) { if(texanim[i]->on) texanim[i]->pausemillis = lastmillis; texanim[i]->on = false; return; } } conoutf("slot %i not initiated for animation", *n); } void texanimsetframe(int *n, int *fr) { loopv(texanim) if(texanim[i]->frames[0].slot == *n) { TexAnim &anim = *texanim[i]; if (anim.frames.inrange(*fr)) { texanimstop(n); slots[anim.frames[0].slot]->sts[0].t->id = anim.frames[*fr].num; } else { conoutf("frame %i not found in animation", *fr); } return; } conoutf("slot %i not initiated for animation", *n); } void texanimreset(int *n) { loopv(texanim) { if(texanim[i]->frames[0].slot == *n) { texanim[i]->on = false; texanim[i]->pos = 0; slots[*n]->sts[0].t->id = texanim[i]->frames[0].num; texanim[i]->pausemillis = 0; return; } } conoutf("slot %i not initiated for animation", *n); } void writetexanims(stream *f) { loopv(texanim) { TexAnim &anim = *texanim[i]; if(anim.frames.length()) { loopvj(anim.frames) f->printf(j ? "texanimadd %i %i\n" : "texaniminit %i\n", anim.frames[0].slot, anim.frames[j].slot); f->printf("texanimdelay %i %i\n\n", anim.frames[0].slot, anim.delay); } } } void cleartexanims(bool clear) { //return textures to their original states when resetting //the engine uses methods to reuse the old texture in memory, and this manipulation of memory idents most likely causes the wrong texture to be represented if animated // solution: restore the original idents, it's stored afterall loopv(texanim) { slots[texanim[i]->frames[0].slot]->sts[0].t->id = texanim[i]->frames[0].num; } if(clear) texanim.deletecontents(); } void reconftexanims() { loopv(texanim) { loopvj(texanim[i]->frames) { //we're assuming it's still inrange Slot &tmp = lookupslot(texanim[i]->frames[j].slot, true); //load the texture, prevents crashes due to NULL textures in the slot[i].sts vector texanim[i]->frames[j].num = tmp.sts[0].t->id; //TODO handle animated cases } } } COMMAND(texaniminit, "i"); COMMAND(texanimadd, "ii"); COMMAND(texanimstart, "i"); COMMAND(texanimstop, "i"); COMMAND(texanimsetframe, "ii"); COMMAND(texanimreset, "i"); COMMAND(texanimdelay, "ii"); void texturereset(int *n) { if(!(identflags&IDF_OVERRIDDEN) && !game::allowedittoggle()) return; resetslotshader(); int limit = clamp(*n, 0, slots.length()); for(int i = limit; i < slots.length(); i++) resetslotshader(); cleartexanims(true); for(int i = limit; i < slots.length(); i++) { Slot *s = slots[i]; for(VSlot *vs = s->variants; vs; vs = vs->next) vs->slot = &dummyslot; delete s; } slots.setsize(limit); } COMMAND(texturereset, "i"); void materialreset() { if(!(identflags&IDF_OVERRIDDEN) && !game::allowedittoggle()) return; loopi(MATF_VOLUME+1) materialslots[i].reset(); } COMMAND(materialreset, ""); static int compactedvslots = 0, compactvslotsprogress = 0, clonedvslots = 0; static bool markingvslots = false; void clearslots() { resetslotshader(); cleartexanims(true); slots.deletecontents(); vslots.deletecontents(); loopi(MATF_VOLUME+1) materialslots[i].reset(); clonedvslots = 0; } static void assignvslot(VSlot &vs); static inline void assignvslotlayer(VSlot &vs) { if(vs.layer && vslots.inrange(vs.layer)) { VSlot &layer = *vslots[vs.layer]; if(layer.index < 0) assignvslot(layer); } } static void assignvslot(VSlot &vs) { vs.index = compactedvslots++; assignvslotlayer(vs); } void compactvslot(int &index) { if(vslots.inrange(index)) { VSlot &vs = *vslots[index]; if(vs.index < 0) assignvslot(vs); if(!markingvslots) index = vs.index; } } void compactvslots(cube *c, int n) { if((compactvslotsprogress++&0xFFF)==0) renderprogress(min(float(compactvslotsprogress)/allocnodes, 1.0f), markingvslots ? "marking slots..." : "compacting slots..."); loopi(n) { if(c[i].children) compactvslots(c[i].children); else loopj(6) if(vslots.inrange(c[i].texture[j])) { VSlot &vs = *vslots[c[i].texture[j]]; if(vs.index < 0) assignvslot(vs); if(!markingvslots) c[i].texture[j] = vs.index; } } } int compactvslots() { clonedvslots = 0; markingvslots = false; compactedvslots = 0; compactvslotsprogress = 0; loopv(vslots) vslots[i]->index = -1; loopv(slots) slots[i]->variants->index = compactedvslots++; loopv(slots) assignvslotlayer(*slots[i]->variants); loopv(vslots) { VSlot &vs = *vslots[i]; if(!vs.changed && vs.index < 0) { markingvslots = true; break; } } compactvslots(worldroot); int total = compactedvslots; compacteditvslots(); loopv(vslots) { VSlot *vs = vslots[i]; if(vs->changed) continue; while(vs->next) { if(vs->next->index < 0) vs->next = vs->next->next; else vs = vs->next; } } if(markingvslots) { markingvslots = false; compactedvslots = 0; compactvslotsprogress = 0; int lastdiscard = 0; loopv(vslots) { VSlot &vs = *vslots[i]; if(vs.changed || (vs.index < 0 && !vs.next)) vs.index = -1; else { while(lastdiscard < i) { VSlot &ds = *vslots[lastdiscard++]; if(!ds.changed && ds.index < 0) ds.index = compactedvslots++; } vs.index = compactedvslots++; } } compactvslots(worldroot); total = compactedvslots; compacteditvslots(); } compactmruvslots(); loopv(vslots) { VSlot &vs = *vslots[i]; if(vs.index >= 0 && vs.layer && vslots.inrange(vs.layer)) vs.layer = vslots[vs.layer]->index; } loopv(vslots) { while(vslots[i]->index >= 0 && vslots[i]->index != i) swap(vslots[i], vslots[vslots[i]->index]); } for(int i = compactedvslots; i < vslots.length(); i++) delete vslots[i]; vslots.setsize(compactedvslots); return total; } ICOMMAND(compactvslots, "", (), { extern int nompedit; if(nompedit && multiplayer()) return; compactvslots(); allchanged(); }); static Slot &loadslot(Slot &s, bool forceload); static void clampvslotoffset(VSlot &dst, Slot *slot = NULL) { if(!slot) slot = dst.slot; if(slot && slot->sts.inrange(0)) { if(!slot->loaded) loadslot(*slot, false); int xs = slot->sts[0].t->xs, ys = slot->sts[0].t->ys; if((dst.rotation&5)==1) swap(xs, ys); dst.xoffset %= xs; if(dst.xoffset < 0) dst.xoffset += xs; dst.yoffset %= ys; if(dst.yoffset < 0) dst.yoffset += ys; } else { dst.xoffset = max(dst.xoffset, 0); dst.yoffset = max(dst.yoffset, 0); } } static void propagatevslot(VSlot &dst, const VSlot &src, int diff, bool edit = false) { if(diff & (1<next; vs; vs = vs->next) { int diff = changed & ~vs->changed; if(diff) propagatevslot(*vs, *root, diff); } } static void mergevslot(VSlot &dst, const VSlot &src, int diff, Slot *slot = NULL) { if(diff & (1<slot = &owner; vs->linked = false; vs = vs->next; } return owner.variants; } static VSlot *emptyvslot(Slot &owner) { int offset = 0; loopvrev(slots) if(slots[i]->variants) { offset = slots[i]->variants->index + 1; break; } for(int i = offset; i < vslots.length(); i++) if(!vslots[i]->changed) return reassignvslot(owner, vslots[i]); return vslots.add(new VSlot(&owner, vslots.length())); } static bool comparevslot(const VSlot &dst, const VSlot &src, int diff) { if(diff & (1<next) { if((!dst->changed || dst->changed == (src.changed | delta.changed)) && comparevslot(*dst, src, src.changed & ~delta.changed) && comparevslot(*dst, delta, delta.changed)) return dst; } return NULL; } static VSlot *clonevslot(const VSlot &src, const VSlot &delta) { VSlot *dst = vslots.add(new VSlot(src.slot, vslots.length())); dst->changed = src.changed | delta.changed; propagatevslot(*dst, src, ((1<=0x10000) { compactvslots(); allchanged(); if(vslots.length()>=0x10000) return NULL; } if(autocompactvslots && ++clonedvslots >= autocompactvslots) { compactvslots(); allchanged(); } return clonevslot(src, delta); } static void fixinsidefaces(cube *c, const ivec &o, int size, int tex) { loopi(8) { ivec co(i, o.x, o.y, o.z, size); if(c[i].children) fixinsidefaces(c[i].children, co, size>>1, tex); else loopj(6) if(!visibletris(c[i], j, co.x, co.y, co.z, size)) c[i].texture[j] = tex; } } ICOMMAND(fixinsidefaces, "i", (int *tex), { extern int nompedit; if(noedit(true) || (nompedit && multiplayer())) return; fixinsidefaces(worldroot, ivec(0, 0, 0), worldsize>>1, *tex && vslots.inrange(*tex) ? *tex : DEFAULT_GEOM); allchanged(); }); void texture(char *type, char *name, int *rot, int *xoffset, int *yoffset, float *scale) { if(slots.length()>=0x10000) return; static const struct { const char *name; int type; } types[] = { {"c", TEX_DIFFUSE}, {"u", TEX_UNKNOWN}, {"d", TEX_DECAL}, {"n", TEX_NORMAL}, {"g", TEX_GLOW}, {"s", TEX_SPEC}, {"z", TEX_DEPTH}, {"e", TEX_ENVMAP} }; static int lastmatslot = -1; int tnum = -1, matslot = findmaterial(type); loopi(sizeof(types)/sizeof(types[0])) if(!strcmp(types[i].name, type)) { tnum = i; break; } if(tnum<0) tnum = atoi(type); if(tnum==TEX_DIFFUSE) lastmatslot = matslot; else if(lastmatslot>=0) matslot = lastmatslot; else if(slots.empty()) return; Slot &s = matslot>=0 ? materialslots[matslot] : *(tnum!=TEX_DIFFUSE ? slots.last() : slots.add(new Slot(slots.length()))); s.loaded = false; s.texmask |= 1<=8) conoutf(CON_WARN, "warning: too many textures in slot %d", slots.length()-1); Slot::Tex &st = s.sts.add(); st.type = tnum; st.combined = -1; st.t = NULL; copystring(st.name, name); path(st.name); if(tnum==TEX_DIFFUSE) { setslotshader(s); VSlot &vs = matslot >= 0 ? materialslots[matslot] : *emptyvslot(s); vs.reset(); vs.rotation = clamp(*rot, 0, 5); vs.xoffset = max(*xoffset, 0); vs.yoffset = max(*yoffset, 0); vs.scale = *scale <= 0 ? 1 : *scale; propagatevslot(&vs, (1<'); file++; } else { file = name; } defformatstring(pfile)("packages/%s", file); path(pfile); //fallback, if texture file doesnt exist, handled by game mods if(!fileexists(findfile(pfile, "r"), "r")) game::texturefailed(pfile, slots.length() - 1); } COMMAND(texture, "ssiiif"); void autograss(char *name) { if(slots.empty()) return; Slot &s = *slots.last(); DELETEA(s.autograss); const char *cmd = NULL; if(!strstr(name, "")) cmd = ""; if(!strstr(name, "")) cmd = cmd ? "" : ""; s.autograss = name[0] ? newstring( makerelpath( strstr(name, "packages") ? NULL : "packages", name, NULL, cmd ) ) : NULL; } COMMAND(autograss, "s"); void texscroll(float *scrollS, float *scrollT) { if(slots.empty()) return; Slot &s = *slots.last(); s.variants->scrollS = *scrollS/1000.0f; s.variants->scrollT = *scrollT/1000.0f; propagatevslot(s.variants, 1<xoffset = max(*xoffset, 0); s.variants->yoffset = max(*yoffset, 0); propagatevslot(s.variants, 1<rotation = clamp(*rot, 0, 5); propagatevslot(s.variants, 1<scale = *scale <= 0 ? 1 : *scale; propagatevslot(s.variants, 1<layer = *layer < 0 ? max(slots.length()-1+*layer, 0) : *layer; s.layermaskname = name[0] ? newstring(path(makerelpath("packages", name))) : NULL; s.layermaskmode = *mode; s.layermaskscale = *scale <= 0 ? 1 : *scale; propagatevslot(s.variants, 1<alphafront = clamp(*front, 0.0f, 1.0f); s.variants->alphaback = clamp(*back, 0.0f, 1.0f); propagatevslot(s.variants, 1<colorscale = vec(clamp(*r, 0.0f, 1.0f), clamp(*g, 0.0f, 1.0f), clamp(*b, 0.0f, 1.0f)); propagatevslot(s.variants, 1<0; } COMMAND(texffenv, "i"); static int findtextype(Slot &s, int type, int last = -1) { for(int i = last+1; i &key, Slot &slot, Slot::Tex &t, bool combined = false, const char *prefix = NULL) { if(combined) key.add('&'); if(prefix) { while(*prefix) key.add(*prefix++); } defformatstring(tname)("packages/%s", t.name); for(const char *s = path(tname); *s; key.add(*s++)); } static void texcombine(Slot &s, int index, Slot::Tex &t, bool forceload = false) { if(renderpath==R_FIXEDFUNCTION && t.type!=TEX_DIFFUSE && t.type!=TEX_GLOW && !forceload) { t.t = notexture; return; } vector key; addname(key, s, t); int texmask = 0; bool envmap = renderpath==R_FIXEDFUNCTION && s.shader->type&SHADER_ENVMAP && s.ffenv && hasCM && maxtmus >= 2; if(!forceload) switch(t.type) { case TEX_DIFFUSE: if(renderpath==R_FIXEDFUNCTION) { int mask = (1<=0;) { texmask |= 1<" : NULL); } break; } // fall through to shader case case TEX_NORMAL: { if(renderpath==R_FIXEDFUNCTION) break; int i = findtextype(s, t.type==TEX_DIFFUSE ? (1<= 0) continue; switch(t.type) { case TEX_ENVMAP: if(hasCM && (renderpath != R_FIXEDFUNCTION || (s.shader->type&SHADER_ENVMAP && s.ffenv && maxtmus >= 2) || forceload)) t.t = cubemapload(t.name); break; default: texcombine(s, i, t, forceload); break; } } s.loaded = true; return s; } //__offtools__: just a debugging routine void debugtexture(int slot) { conoutf("debug slot %d", slot); } //__offtools__: dirty workaround on receiving textures void reloadslot(int n) { loadslot(*slots[n], true); } MSlot &lookupmaterialslot(int index, bool load) { MSlot &s = materialslots[index]; if(load && !s.linked) { if(!s.loaded) loadslot(s, true); linkvslotshader(s); s.linked = true; } return s; } Slot &lookupslot(int index, bool load) { Slot &s = slots.inrange(index) ? *slots[index] : (slots.inrange(DEFAULT_GEOM) ? *slots[DEFAULT_GEOM] : dummyslot); return s.loaded || !load ? s : loadslot(s, false); } VSlot &lookupvslot(int index, bool load) { VSlot &s = vslots.inrange(index) && vslots[index]->slot ? *vslots[index] : (slots.inrange(DEFAULT_GEOM) && slots[DEFAULT_GEOM]->variants ? *slots[DEFAULT_GEOM]->variants : dummyvslot); if(load && !s.linked) { if(!s.slot->loaded) loadslot(*s.slot, false); linkvslotshader(s); s.linked = true; } return s; } void linkslotshaders() { loopv(slots) if(slots[i]->loaded) linkslotshader(*slots[i]); loopv(vslots) if(vslots[i]->linked) linkvslotshader(*vslots[i]); loopi(MATF_VOLUME+1) if(materialslots[i].loaded) { linkslotshader(materialslots[i]); linkvslotshader(materialslots[i]); } } Texture *loadthumbnail(Slot &slot) { if(slot.thumbnail) return slot.thumbnail; if(!slot.variants) { slot.thumbnail = notexture; return slot.thumbnail; } VSlot &vslot = *slot.variants; linkslotshader(slot, false); linkvslotshader(vslot, false); vector name; if(vslot.colorscale == vec(1, 1, 1)) addname(name, slot, slot.sts[0], false, ""); else { defformatstring(prefix)("", vslot.colorscale.x, vslot.colorscale.y, vslot.colorscale.z); addname(name, slot, slot.sts[0], false, prefix); } int glow = -1; if(slot.texmask&(1<= 0) { defformatstring(prefix)("", vslot.glowcolor.x, vslot.glowcolor.y, vslot.glowcolor.z); addname(name, slot, slot.sts[glow], true, prefix); } } VSlot *layer = vslot.layer ? &lookupvslot(vslot.layer, false) : NULL; if(layer) { if(layer->colorscale == vec(1, 1, 1)) addname(name, *layer->slot, layer->slot->sts[0], true, ""); else { defformatstring(prefix)("", vslot.colorscale.x, vslot.colorscale.y, vslot.colorscale.z); addname(name, *layer->slot, layer->slot->sts[0], true, prefix); } } name.add('\0'); Texture *t = textures.access(path(name.getbuf())); if(t) slot.thumbnail = t; else { ImageData s, g, l; texturedata(s, NULL, &slot.sts[0], false); if(vslot.colorscale != vec(1, 1, 1)) texmad(s, vslot.colorscale, vec(0, 0, 0)); if(glow >= 0) texturedata(g, NULL, &slot.sts[glow], false); if(layer) { texturedata(l, NULL, &layer->slot->sts[0], false); if(layer->colorscale != vec(1, 1, 1)) texmad(l, layer->colorscale, vec(0, 0, 0)); } if(!s.data) t = slot.thumbnail = notexture; else { int xs = s.w, ys = s.h; if(s.w > 64 || s.h > 64) scaleimage(s, min(s.w, 64), min(s.h, 64)); if(g.data) { if(g.w != s.w || g.h != s.h) scaleimage(g, s.w, s.h); addglow(s, g, vslot.glowcolor); } if(l.data) { if(l.w != s.w/2 || l.h != s.h/2) scaleimage(l, s.w/2, s.h/2); forcergbimage(s); forcergbimage(l); uchar *dstrow = &s.data[s.pitch*l.h + s.bpp*l.w], *srcrow = l.data; loop(y, l.h) { for(uchar *dst = dstrow, *src = srcrow, *end = &srcrow[l.w*l.bpp]; src < end; dst += s.bpp, src += l.bpp) loopk(3) dst[k] = src[k]; dstrow += s.pitch; srcrow += l.pitch; } } t = newtexture(NULL, name.getbuf(), s, 0, false, false, true); t->xs = xs; t->ys = ys; slot.thumbnail = t; } } return t; } void loadlayermasks() { loopv(slots) { Slot &slot = *slots[i]; if(slot.loaded && slot.layermaskname && !slot.layermask) { slot.layermask = new ImageData; texturedata(*slot.layermask, slot.layermaskname); if(!slot.layermask->data) DELETEP(slot.layermask); } } } // environment mapped reflections void forcecubemapload(GLuint tex) { extern int ati_cubemap_bug; if(!ati_cubemap_bug || !tex) return; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); cubemapshader->set(); GLenum tex2d = glIsEnabled(GL_TEXTURE_2D), depthtest = glIsEnabled(GL_DEPTH_TEST), blend = glIsEnabled(GL_BLEND); if(tex2d) glDisable(GL_TEXTURE_2D); if(depthtest) glDisable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_CUBE_MAP_ARB); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, tex); if(!blend) glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBegin(GL_POINTS); glColor4f(1, 1, 1, 0); glTexCoord3f(0, 0, 1); glVertex2f(0, 0); glEnd(); if(!blend) glDisable(GL_BLEND); glDisable(GL_TEXTURE_CUBE_MAP_ARB); if(depthtest) glEnable(GL_DEPTH_TEST); if(tex2d) glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } cubemapside cubemapsides[6] = { { GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB, "lf", true, true, true }, { GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB, "rt", false, false, true }, { GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB, "ft", true, false, false }, { GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB, "bk", false, true, false }, { GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB, "dn", false, false, true }, { GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB, "up", false, false, true }, }; VARFP(envmapsize, 4, 7, 10, setupmaterials()); Texture *cubemaploadwildcard(Texture *t, const char *name, bool mipit, bool msg, bool transient = false) { if(!hasCM) return NULL; string tname; if(!name) copystring(tname, t->name); else { copystring(tname, name); t = textures.access(path(tname)); if(t) { if(!transient && t->type&Texture::TRANSIENT) t->type &= ~Texture::TRANSIENT; return t; } } char *wildcard = strchr(tname, '*'); ImageData surface[6]; string sname; if(!wildcard) copystring(sname, tname); GLenum format = GL_FALSE; int tsize = 0, compress = 0; loopi(6) { if(wildcard) { copystring(sname, tname, wildcard-tname+1); concatstring(sname, cubemapsides[i].name); concatstring(sname, wildcard+1); } ImageData &s = surface[i]; texturedata(s, sname, NULL, msg, &compress); if(!s.data) return NULL; if(s.w != s.h) { if(msg) conoutf(CON_ERROR, "cubemap texture %s does not have square size", sname); return NULL; } if(!format) format = s.compressed ? s.compressed : texformat(s.bpp); else if((s.compressed ? s.compressed : texformat(s.bpp))!=format || (s.compressed && (s.w!=surface[0].w || s.h!=surface[0].h || s.levels!=surface[0].levels))) { if(msg) conoutf(CON_ERROR, "cubemap texture %s doesn't match other sides' format", sname); return NULL; } tsize = max(tsize, max(s.w, s.h)); } if(name) { char *key = newstring(tname); t = &textures[key]; t->name = key; } t->bpp = surface[0].compressed ? formatsize(uncompressedformat(format)) : surface[0].bpp; t->mipmap = mipit; t->clamp = 3; t->type = Texture::CUBEMAP | (transient ? Texture::TRANSIENT : 0); t->xs = t->ys = tsize; t->w = t->h = min(1<w, t->h, mipit, false, GL_TEXTURE_CUBE_MAP_ARB, compress, t->w, t->h); GLenum component = compressedformat(format, t->w, t->h, compress); switch(component) { case GL_RGB: component = GL_RGB5; break; } glGenTextures(1, &t->id); loopi(6) { ImageData &s = surface[i]; cubemapside &side = cubemapsides[i]; texreorient(s, side.flipx, side.flipy, side.swapxy); if(s.compressed) { int w = s.w, h = s.h, levels = s.levels, level = 0; uchar *data = s.data; while(levels > 1 && (w > t->w || h > t->h)) { data += s.calclevelsize(level++); levels--; if(w > 1) w /= 2; if(h > 1) h /= 2; } createcompressedtexture(!i ? t->id : 0, w, h, data, s.align, s.bpp, levels, 3, mipit ? 2 : 1, s.compressed, side.target); } else { createtexture(!i ? t->id : 0, t->w, t->h, s.data, 3, mipit ? 2 : 1, component, side.target, s.w, s.h, s.pitch, false, format); } } forcecubemapload(t->id); return t; } Texture *cubemapload(const char *name, bool mipit, bool msg, bool transient) { if(!hasCM) return NULL; string pname; copystring(pname, makerelpath("packages", name)); path(pname); Texture *t = NULL; if(!strchr(pname, '*')) { defformatstring(fname)("%s_*", pname); t = cubemaploadwildcard(NULL, fname, mipit, false, transient);; if(!t && msg) conoutf(CON_ERROR, "could not load envmap %s", name); } else t = cubemaploadwildcard(NULL, pname, mipit, msg, transient); return t; } VARR(envmapradius, 0, 128, 10000); struct envmap { int radius, size, blur; vec o; GLuint tex; }; static vector envmaps; static Texture *skyenvmap = NULL; void clearenvmaps() { if(skyenvmap) { if(skyenvmap->type&Texture::TRANSIENT) cleanuptexture(skyenvmap); skyenvmap = NULL; } loopv(envmaps) glDeleteTextures(1, &envmaps[i].tex); envmaps.shrink(0); } VAR(aaenvmap, 0, 2, 4); GLuint genenvmap(const vec &o, int envmapsize, int blur) { int rendersize = 1<<(envmapsize+aaenvmap), sizelimit = min(hwcubetexsize, min(screen->w, screen->h)); if(maxtexsize) sizelimit = min(sizelimit, maxtexsize); while(rendersize > sizelimit) rendersize /= 2; int texsize = min(rendersize, 1< 0 ? new uchar[3*rendersize*rendersize] : NULL; glPixelStorei(GL_PACK_ALIGNMENT, texalign(pixels, rendersize, 3)); loopi(6) { const cubemapside &side = cubemapsides[i]; switch(side.target) { case GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB: // lf yaw = 90; pitch = 0; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB: // rt yaw = 270; pitch = 0; break; case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB: // ft yaw = 180; pitch = 0; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB: // bk yaw = 0; pitch = 0; break; case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB: // dn yaw = 270; pitch = -90; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB: // up yaw = 270; pitch = 90; break; } glFrontFace((side.flipx==side.flipy)!=side.swapxy ? GL_CW : GL_CCW); drawcubemap(rendersize, o, yaw, pitch, side); glReadPixels(0, 0, rendersize, rendersize, GL_RGB, GL_UNSIGNED_BYTE, pixels); if(blurbuf) { blurtexture(blur, 3, rendersize, rendersize, blurbuf, pixels); swap(blurbuf, pixels); } createtexture(tex, texsize, texsize, pixels, 3, 2, GL_RGB5, side.target, rendersize, rendersize); } glFrontFace(GL_CW); delete[] pixels; if(blurbuf) delete[] blurbuf; glViewport(0, 0, screen->w, screen->h); clientkeepalive(); forcecubemapload(tex); return tex; } void initenvmaps() { if(!hasCM) return; clearenvmaps(); extern char *skybox; skyenvmap = skybox[0] ? cubemapload(skybox, true, false, true) : NULL; const vector &ents = entities::getents(); loopv(ents) { const extentity &ent = *ents[i]; if(ent.type != ET_ENVMAP) continue; envmap &em = envmaps.add(); em.radius = ent.attr[0] ? clamp(int(ent.attr[0]), 0, 10000) : envmapradius; em.size = ent.attr[1] ? clamp(int(ent.attr[1]), 4, 9) : 0; em.blur = ent.attr[2] ? clamp(int(ent.attr[2]), 1, 2) : 0; em.o = ent.o; em.tex = 0; } } void genenvmaps() { if(envmaps.empty()) return; renderprogress(0, "generating environment maps..."); int lastprogress = SDL_GetTicks(); loopv(envmaps) { envmap &em = envmaps[i]; em.tex = genenvmap(em.o, em.size ? em.size : envmapsize, em.blur); if(renderedframe) continue; int millis = SDL_GetTicks(); if(millis - lastprogress >= 250) { renderprogress(float(i+1)/envmaps.length(), "generating environment maps...", 0, true); lastprogress = millis; } } } ushort closestenvmap(const vec &o) { ushort minemid = EMID_SKY; float mindist = 1e16f; loopv(envmaps) { envmap &em = envmaps[i]; float dist = em.o.dist(o); if(dist < em.radius && dist < mindist) { minemid = EMID_RESERVED + i; mindist = dist; } } return minemid; } ushort closestenvmap(int orient, int x, int y, int z, int size) { vec loc(x, y, z); int dim = dimension(orient); if(dimcoord(orient)) loc[dim] += size; loc[R[dim]] += size/2; loc[C[dim]] += size/2; return closestenvmap(loc); } GLuint lookupenvmap(Slot &slot) { loopv(slot.sts) if(slot.sts[i].type==TEX_ENVMAP && slot.sts[i].t) return slot.sts[i].t->id; return skyenvmap ? skyenvmap->id : 0; } GLuint lookupenvmap(ushort emid) { if(emid==EMID_SKY || emid==EMID_CUSTOM) return skyenvmap ? skyenvmap->id : 0; if(emid==EMID_NONE || !envmaps.inrange(emid-EMID_RESERVED)) return 0; GLuint tex = envmaps[emid-EMID_RESERVED].tex; return tex ? tex : (skyenvmap ? skyenvmap->id : 0); } void cleanuptexture(Texture *t) { DELETEA(t->alphamask); if(t->id) { glDeleteTextures(1, &t->id); t->id = 0; } if(t->type&Texture::TRANSIENT) textures.remove(t->name); } void cleanuptextures() { clearenvmaps(); loopv(slots) slots[i]->cleanup(); loopv(vslots) vslots[i]->cleanup(); loopi(MATF_VOLUME+1) materialslots[i].cleanup(); enumerate(textures, Texture, tex, cleanuptexture(&tex)); } bool reloadtexture(const char *name) { Texture *t = textures.access(path(name, true)); if(t) return reloadtexture(*t); return true; } bool reloadtexture(Texture &tex) { if(tex.id) return true; switch(tex.type&Texture::TYPE) { case Texture::STUB: case Texture::IMAGE: { int compress = 0; ImageData s; if(!texturedata(s, tex.name, NULL, true, &compress) || !newtexture(&tex, NULL, s, tex.clamp, tex.mipmap, false, false, compress)) return false; break; } case Texture::CUBEMAP: if(!cubemaploadwildcard(&tex, NULL, tex.mipmap, true)) return false; break; } return true; } void reloadtex(char *name) { Texture *t = textures.access(path(name, true)); if(!t) { conoutf(CON_ERROR, "texture %s is not loaded", name); return; } if(t->type&Texture::TRANSIENT) { conoutf(CON_ERROR, "can't reload transient texture %s", name); return; } DELETEA(t->alphamask); Texture oldtex = *t; t->id = 0; if(!reloadtexture(*t)) { if(t->id) glDeleteTextures(1, &t->id); *t = oldtex; conoutf(CON_ERROR, "failed to reload texture %s", name); } } COMMAND(reloadtex, "s"); void reloadtextures() { int reloaded = 0; enumerate(textures, Texture, tex, { loadprogress = float(++reloaded)/textures.numelems; reloadtexture(tex); }); loadprogress = 0; } enum { DDSD_CAPS = 0x00000001, DDSD_HEIGHT = 0x00000002, DDSD_WIDTH = 0x00000004, DDSD_PITCH = 0x00000008, DDSD_PIXELFORMAT = 0x00001000, DDSD_MIPMAPCOUNT = 0x00020000, DDSD_LINEARSIZE = 0x00080000, DDSD_BACKBUFFERCOUNT = 0x00800000, DDPF_ALPHAPIXELS = 0x00000001, DDPF_FOURCC = 0x00000004, DDPF_INDEXED = 0x00000020, DDPF_ALPHA = 0x00000002, DDPF_RGB = 0x00000040, DDPF_COMPRESSED = 0x00000080, DDPF_LUMINANCE = 0x00020000, DDSCAPS_COMPLEX = 0x00000008, DDSCAPS_TEXTURE = 0x00001000, DDSCAPS_MIPMAP = 0x00400000, DDSCAPS2_CUBEMAP = 0x00000200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000, DDSCAPS2_VOLUME = 0x00200000, FOURCC_DXT1 = 0x31545844, FOURCC_DXT2 = 0x32545844, FOURCC_DXT3 = 0x33545844, FOURCC_DXT4 = 0x34545844, FOURCC_DXT5 = 0x35545844 }; struct DDCOLORKEY { uint dwColorSpaceLowValue, dwColorSpaceHighValue; }; struct DDPIXELFORMAT { uint dwSize, dwFlags, dwFourCC; union { uint dwRGBBitCount, dwYUVBitCount, dwZBufferBitDepth, dwAlphaBitDepth, dwLuminanceBitCount, dwBumpBitCount, dwPrivateFormatBitCount; }; union { uint dwRBitMask, dwYBitMask, dwStencilBitDepth, dwLuminanceBitMask, dwBumpDuBitMask, dwOperations; }; union { uint dwGBitMask, dwUBitMask, dwZBitMask, dwBumpDvBitMask; struct { ushort wFlipMSTypes, wBltMSTypes; } MultiSampleCaps; }; union { uint dwBBitMask, dwVBitMask, dwStencilBitMask, dwBumpLuminanceBitMask; }; union { uint dwRGBAlphaBitMask, dwYUVAlphaBitMask, dwLuminanceAlphaBitMask, dwRGBZBitMask, dwYUVZBitMask; }; }; struct DDSCAPS2 { uint dwCaps, dwCaps2, dwCaps3, dwCaps4; }; struct DDSURFACEDESC2 { uint dwSize, dwFlags, dwHeight, dwWidth; union { int lPitch; uint dwLinearSize; }; uint dwBackBufferCount; union { uint dwMipMapCount, dwRefreshRate, dwSrcVBHandle; }; uint dwAlphaBitDepth, dwReserved, lpSurface; union { DDCOLORKEY ddckCKDestOverlay; uint dwEmptyFaceColor; }; DDCOLORKEY ddckCKDestBlt, ddckCKSrcOverlay, ddckCKSrcBlt; union { DDPIXELFORMAT ddpfPixelFormat; uint dwFVF; }; DDSCAPS2 ddsCaps; uint dwTextureStage; }; bool loaddds(const char *filename, ImageData &image) { stream *f = openfile(filename, "rb"); if(!f) return false; GLenum format = GL_FALSE; uchar magic[4]; if(f->read(magic, 4) != 4 || memcmp(magic, "DDS ", 4)) { delete f; return false; } DDSURFACEDESC2 d; if(f->read(&d, sizeof(d)) != sizeof(d)) { delete f; return false; } lilswap((uint *)&d, sizeof(d)/sizeof(uint)); if(d.dwSize != sizeof(DDSURFACEDESC2) || d.ddpfPixelFormat.dwSize != sizeof(DDPIXELFORMAT)) { delete f; return false; } if(d.ddpfPixelFormat.dwFlags & DDPF_FOURCC) { switch(d.ddpfPixelFormat.dwFourCC) { case FOURCC_DXT1: format = d.ddpfPixelFormat.dwFlags & DDPF_ALPHAPIXELS ? GL_COMPRESSED_RGBA_S3TC_DXT1_EXT : GL_COMPRESSED_RGB_S3TC_DXT1_EXT; break; case FOURCC_DXT2: case FOURCC_DXT3: format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; case FOURCC_DXT4: case FOURCC_DXT5: format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; } } if(!format) { delete f; return false; } if(dbgdds) conoutf(CON_DEBUG, "%s: format 0x%X, %d x %d, %d mipmaps", filename, format, d.dwWidth, d.dwHeight, d.dwMipMapCount); int bpp = 0; switch(format) { case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: bpp = 8; break; case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: bpp = 16; break; } image.setdata(NULL, d.dwWidth, d.dwHeight, bpp, d.dwMipMapCount, 4, format); int size = image.calcsize(); if(f->read(image.data, size) != size) { delete f; image.cleanup(); return false; } delete f; return true; } void gendds(char *infile, char *outfile) { if(!hasTC) { conoutf(CON_ERROR, "OpenGL driver does not support texture compression"); return; } glHint(GL_TEXTURE_COMPRESSION_HINT_ARB, GL_NICEST); defformatstring(cfile)("%s", infile); extern void reloadtex(char *name); Texture *t = textures.access(path(cfile)); if(t) reloadtex(cfile); t = textureload(cfile); if(t==notexture) { conoutf(CON_ERROR, "failed loading %s", infile); return; } glBindTexture(GL_TEXTURE_2D, t->id); GLint compressed = 0, format = 0, width = 0, height = 0; glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_COMPRESSED_ARB, &compressed); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &format); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height); if(!compressed) { conoutf(CON_ERROR, "failed compressing %s", infile); return; } int fourcc = 0; switch(format) { case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: fourcc = FOURCC_DXT1; conoutf("compressed as DXT1"); break; case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: fourcc = FOURCC_DXT1; conoutf("compressed as DXT1a"); break; case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: fourcc = FOURCC_DXT3; conoutf("compressed as DXT3"); break; case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: fourcc = FOURCC_DXT5; conoutf("compressed as DXT5"); break; default: conoutf(CON_ERROR, "failed compressing %s: unknown format: 0x%X", infile, format); break; return; } if(!outfile[0]) { static string buf; copystring(buf, infile); int len = strlen(buf); if(len > 4 && buf[len-4]=='.') memcpy(&buf[len-4], ".dds", 4); else concatstring(buf, ".dds"); outfile = buf; } stream *f = openfile(path(outfile, true), "wb"); if(!f) { conoutf(CON_ERROR, "failed writing to %s", outfile); return; } int csize = 0; for(int lw = width, lh = height, level = 0;;) { GLint size = 0; glGetTexLevelParameteriv(GL_TEXTURE_2D, level++, GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB, &size); csize += size; if(max(lw, lh) <= 1) break; if(lw > 1) lw /= 2; if(lh > 1) lh /= 2; } DDSURFACEDESC2 d; memset(&d, 0, sizeof(d)); d.dwSize = sizeof(DDSURFACEDESC2); d.dwWidth = width; d.dwHeight = height; d.dwLinearSize = csize; d.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_LINEARSIZE | DDSD_MIPMAPCOUNT; d.ddsCaps.dwCaps = DDSCAPS_TEXTURE | DDSCAPS_COMPLEX | DDSCAPS_MIPMAP; d.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT); d.ddpfPixelFormat.dwFlags = DDPF_FOURCC | (format!=GL_COMPRESSED_RGB_S3TC_DXT1_EXT ? DDPF_ALPHAPIXELS : 0); d.ddpfPixelFormat.dwFourCC = fourcc; uchar *data = new uchar[csize], *dst = data; for(int lw = width, lh = height;;) { GLint size; glGetTexLevelParameteriv(GL_TEXTURE_2D, d.dwMipMapCount, GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB, &size); glGetCompressedTexImage_(GL_TEXTURE_2D, d.dwMipMapCount++, dst); dst += size; if(max(lw, lh) <= 1) break; if(lw > 1) lw /= 2; if(lh > 1) lh /= 2; } lilswap((uint *)&d, sizeof(d)/sizeof(uint)); f->write("DDS ", 4); f->write(&d, sizeof(d)); f->write(data, csize); delete f; delete[] data; conoutf("wrote DDS file %s", outfile); setuptexcompress(); } COMMAND(gendds, "ss"); void writepngchunk(stream *f, const char *type, uchar *data = NULL, uint len = 0) { f->putbig(len); f->write(type, 4); f->write(data, len); uint crc = crc32(0, Z_NULL, 0); crc = crc32(crc, (const Bytef *)type, 4); if(data) crc = crc32(crc, data, len); f->putbig(crc); } VARP(compresspng, 0, 9, 9); void savepng(const char *filename, ImageData &image, bool flip) { uchar ctype = 0; switch(image.bpp) { case 1: ctype = 0; break; case 2: ctype = 4; break; case 3: ctype = 2; break; case 4: ctype = 6; break; default: conoutf(CON_ERROR, "failed saving png to %s", filename); return; } stream *f = openfile(filename, "wb"); if(!f) { conoutf(CON_ERROR, "could not write to %s", filename); return; } uchar signature[] = { 137, 80, 78, 71, 13, 10, 26, 10 }; f->write(signature, sizeof(signature)); struct pngihdr { uint width, height; uchar bitdepth, colortype, compress, filter, interlace; } ihdr = { bigswap(image.w), bigswap(image.h), 8, ctype, 0, 0, 0 }; writepngchunk(f, "IHDR", (uchar *)&ihdr, 13); stream::offset idat = f->tell(); uint len = 0; f->write("\0\0\0\0IDAT", 8); uint crc = crc32(0, Z_NULL, 0); crc = crc32(crc, (const Bytef *)"IDAT", 4); z_stream z; z.zalloc = NULL; z.zfree = NULL; z.opaque = NULL; if(deflateInit(&z, compresspng) != Z_OK) goto error; uchar buf[1<<12]; z.next_out = (Bytef *)buf; z.avail_out = sizeof(buf); loopi(image.h) { uchar filter = 0; loopj(2) { z.next_in = j ? (Bytef *)image.data + (flip ? image.h-i-1 : i)*image.pitch : (Bytef *)&filter; z.avail_in = j ? image.w*image.bpp : 1; while(z.avail_in > 0) { if(deflate(&z, Z_NO_FLUSH) != Z_OK) goto cleanuperror; #define FLUSHZ do { \ int flush = sizeof(buf) - z.avail_out; \ crc = crc32(crc, buf, flush); \ len += flush; \ f->write(buf, flush); \ z.next_out = (Bytef *)buf; \ z.avail_out = sizeof(buf); \ } while(0) FLUSHZ; } } } for(;;) { int err = deflate(&z, Z_FINISH); if(err != Z_OK && err != Z_STREAM_END) goto cleanuperror; FLUSHZ; if(err == Z_STREAM_END) break; } deflateEnd(&z); f->seek(idat, SEEK_SET); f->putbig(len); f->seek(0, SEEK_END); f->putbig(crc); writepngchunk(f, "IEND"); delete f; return; cleanuperror: deflateEnd(&z); error: delete f; conoutf(CON_ERROR, "failed saving png to %s", filename); } struct tgaheader { uchar identsize; uchar cmaptype; uchar imagetype; uchar cmaporigin[2]; uchar cmapsize[2]; uchar cmapentrysize; uchar xorigin[2]; uchar yorigin[2]; uchar width[2]; uchar height[2]; uchar pixelsize; uchar descbyte; }; VARP(compresstga, 0, 1, 1); void savetga(const char *filename, ImageData &image, bool flip) { switch(image.bpp) { case 3: case 4: break; default: conoutf(CON_ERROR, "failed saving tga to %s", filename); return; } stream *f = openfile(filename, "wb"); if(!f) { conoutf(CON_ERROR, "could not write to %s", filename); return; } tgaheader hdr; memset(&hdr, 0, sizeof(hdr)); hdr.pixelsize = image.bpp*8; hdr.width[0] = image.w&0xFF; hdr.width[1] = (image.w>>8)&0xFF; hdr.height[0] = image.h&0xFF; hdr.height[1] = (image.h>>8)&0xFF; hdr.imagetype = compresstga ? 10 : 2; f->write(&hdr, sizeof(hdr)); uchar buf[128*4]; loopi(image.h) { uchar *src = image.data + (flip ? i : image.h - i - 1)*image.pitch; for(int remaining = image.w; remaining > 0;) { int raw = 1; if(compresstga) { int run = 1; for(uchar *scan = src; run < min(remaining, 128); run++) { scan += image.bpp; if(src[0]!=scan[0] || src[1]!=scan[1] || src[2]!=scan[2] || (image.bpp==4 && src[3]!=scan[3])) break; } if(run > 1) { f->putchar(0x80 | (run-1)); f->putchar(src[2]); f->putchar(src[1]); f->putchar(src[0]); if(image.bpp==4) f->putchar(src[3]); src += run*image.bpp; remaining -= run; if(remaining <= 0) break; } for(uchar *scan = src; raw < min(remaining, 128); raw++) { scan += image.bpp; if(src[0]==scan[0] && src[1]==scan[1] && src[2]==scan[2] && (image.bpp!=4 || src[3]==scan[3])) break; } f->putchar(raw - 1); } else raw = min(remaining, 128); uchar *dst = buf; loopj(raw) { dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; if(image.bpp==4) dst[3] = src[3]; dst += image.bpp; src += image.bpp; } f->write(buf, raw*image.bpp); remaining -= raw; } } delete f; } enum { IMG_BMP = 0, IMG_TGA = 1, IMG_PNG = 2, NUMIMG }; VARP(screenshotformat, 0, IMG_PNG, NUMIMG-1); const char *imageexts[NUMIMG] = { ".bmp", ".tga", ".png" }; int guessimageformat(const char *filename, int format = IMG_BMP) { int len = strlen(filename); loopi(NUMIMG) { int extlen = strlen(imageexts[i]); if(len >= extlen && !strcasecmp(&filename[len-extlen], imageexts[i])) return i; } return format; } void saveimage(const char *filename, int format, ImageData &image, bool flip = false) { switch(format) { case IMG_PNG: savepng(filename, image, flip); break; case IMG_TGA: savetga(filename, image, flip); break; default: { ImageData flipped(image.w, image.h, image.bpp, image.data); if(flip) texflip(flipped); SDL_Surface *s = wrapsurface(flipped.data, flipped.w, flipped.h, flipped.bpp); if(!s) break; stream *f = openfile(filename, "wb"); if(f) { SDL_SaveBMP_RW(s, f->rwops(), 1); delete f; } SDL_FreeSurface(s); break; } } } bool loadimage(const char *filename, ImageData &image) { SDL_Surface *s = loadsurface(path(filename, true)); if(!s) return false; image.wrap(s); return true; } //for engine use only void scaledscreenshot(char *filename, int format, int x, int y) { ImageData image(screen->w, screen->h, 3); glPixelStorei(GL_PACK_ALIGNMENT, texalign(image.data, screen->w, 3)); glReadPixels(0, 0, screen->w, screen->h, GL_RGB, GL_UNSIGNED_BYTE, image.data); if(x || y) { float ratio = min(1.0f, min(x ? (float)x / image.w : 1, y ? (float)y / image.h : 1)); scaleimage(image, image.w * ratio, image.h * ratio); } saveimage(path(filename), format, image, true); } SVARP(screenshotdir, ""); void screenshot(char *filename, int *x, int *y) { static string buf; int format = -1; copystring(buf, screenshotdir); if(screenshotdir[0]) { int len = strlen(buf); if(buf[len] != '/' && buf[len] != '\\' && len+1 < (int)sizeof(buf)) { buf[len] = '/'; buf[len+1] = '\0'; } const char *dir = findfile(buf, "w"); if(!fileexists(dir, "w")) createdir(dir); } if(filename[0]) { concatstring(buf, filename); format = guessimageformat(buf, -1); } else { defformatstring(name)("screenshot_%d", totalmillis); concatstring(buf, name); } if(format < 0) { format = screenshotformat; concatstring(buf, imageexts[format]); } scaledscreenshot(path(buf), format, *x, *y); } COMMAND(screenshot, "sii"); void flipnormalmapy(char *destfile, char *normalfile) // jpg/png /tga-> tga { ImageData ns; if(!loadimage(normalfile, ns)) return; ImageData d(ns.w, ns.h, 3); readwritetex(d, ns, dst[0] = src[0]; dst[1] = 255 - src[1]; dst[2] = src[2]; ); saveimage(destfile, guessimageformat(destfile, IMG_TGA), d); } void mergenormalmaps(char *heightfile, char *normalfile) // jpg/png/tga + tga -> tga { ImageData hs, ns; if(!loadimage(heightfile, hs) || !loadimage(normalfile, ns) || hs.w != ns.w || hs.h != ns.h) return; ImageData d(ns.w, ns.h, 3); read2writetex(d, hs, srch, ns, srcn, *(bvec *)dst = bvec(((bvec *)srcn)->tovec().mul(2).add(((bvec *)srch)->tovec()).normalize()); ); saveimage(normalfile, guessimageformat(normalfile, IMG_TGA), d); } COMMAND(flipnormalmapy, "ss"); COMMAND(mergenormalmaps, "ss"); sandboxgamemaker-2.7.1+dfsg/src/engine/shadowmap.cpp0000664000175000017500000004057211544613352022411 0ustar showardshoward#include "engine.h" #include "rendertarget.h" VARP(shadowmap, 0, 0, 1); extern void cleanshadowmap(); VARFP(shadowmapsize, 7, 9, 11, cleanshadowmap()); VARP(shadowmapradius, 64, 96, 256); VAR(shadowmapheight, 0, 32, 128); VARP(ffshadowmapdist, 128, 1024, 4096); VARP(shadowmapdist, 128, 256, 512); VARFP(fpshadowmap, 0, 0, 1, cleanshadowmap()); VARFP(shadowmapprecision, 0, 0, 1, cleanshadowmap()); bvec shadowmapambientcolor(0, 0, 0); HVARFR(shadowmapambient, 0, 0, 0xFFFFFF, { //if(shadowmapambient <= 255) shadowmapambient |= (shadowmapambient<<8) | (shadowmapambient<<16); shadowmapambientcolor = bvec((shadowmapambient>>16)&0xFF, (shadowmapambient>>8)&0xFF, shadowmapambient&0xFF); }); VARP(shadowmapintensity, 0, 40, 100); VARP(blurshadowmap, 0, 1, 3); VARP(blursmsigma, 1, 100, 200); #define SHADOWSKEW 0.7071068f vec shadowoffset(0, 0, 0), shadowfocus(0, 0, 0), shadowdir(0, SHADOWSKEW, 1); VAR(shadowmapcasters, 1, 0, 0); float shadowmapmaxz = 0; void setshadowdir(int angle) { shadowdir = vec(0, SHADOWSKEW, 1); shadowdir.rotate_around_z(angle*RAD); } VARFR(shadowmapangle, 0, 0, 360, setshadowdir(shadowmapangle)); void guessshadowdir() { if(shadowmapangle) return; vec dir; extern int sunlight; extern vec sunlightdir; if(sunlight) dir = sunlightdir; else { vec lightpos(0, 0, 0), casterpos(0, 0, 0); int numlights = 0, numcasters = 0; const vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; switch(e.type) { case ET_LIGHT: if(!e.attr[0]) { lightpos.add(e.o); numlights++; } break; case ET_MAPMODEL: casterpos.add(e.o); numcasters++; break; default: if(e.typew-vieww, screen->h-viewh, vieww, viewh); } glClearColor(0, 0, 0, 0); glClear(GL_DEPTH_BUFFER_BIT | (renderpath!=R_FIXEDFUNCTION ? GL_COLOR_BUFFER_BIT : 0)); if(!hasFBO && rtscissor) glDisable(GL_SCISSOR_TEST); } bool dorender() { // nvidia bug, must push modelview here, then switch to projection, then back to modelview before can safely modify it glPushMatrix(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(-shadowmapradius, shadowmapradius, -shadowmapradius, shadowmapradius, renderpath==R_FIXEDFUNCTION ? 0 : -shadowmapdist, renderpath==R_FIXEDFUNCTION ? ffshadowmapdist : shadowmapdist); glMatrixMode(GL_MODELVIEW); vec skewdir(shadowdir); skewdir.rotate_around_z(-camera1->yaw*RAD); vec dir; vecfromyawpitch(camera1->yaw, camera1->pitch, 1, 0, dir); dir.z = 0; dir.mul(shadowmapradius); vec dirx, diry; vecfromyawpitch(camera1->yaw, 0, 0, 1, dirx); vecfromyawpitch(camera1->yaw, 0, 1, 0, diry); shadowoffset.x = -fmod(dirx.dot(camera1->o) - skewdir.x*camera1->o.z, 2.0f*shadowmapradius/vieww); shadowoffset.y = -fmod(diry.dot(camera1->o) - skewdir.y*camera1->o.z, 2.0f*shadowmapradius/viewh); GLfloat skew[] = { 1, 0, 0, 0, 0, 1, 0, 0, skewdir.x, skewdir.y, 1, 0, 0, 0, 0, 1 }; glLoadMatrixf(skew); glTranslatef(skewdir.x*shadowmapheight + shadowoffset.x, skewdir.y*shadowmapheight + shadowoffset.y + dir.magnitude(), -shadowmapheight); glRotatef(camera1->yaw+180, 0, 0, -1); glTranslatef(-camera1->o.x, -camera1->o.y, -camera1->o.z); shadowfocus = camera1->o; shadowfocus.add(dir); shadowfocus.add(vec(shadowdir).mul(shadowmapheight)); shadowfocus.add(dirx.mul(shadowoffset.x)); shadowfocus.add(diry.mul(shadowoffset.y)); glmatrixf proj, mv; glGetFloatv(GL_PROJECTION_MATRIX, proj.v); glGetFloatv(GL_MODELVIEW_MATRIX, mv.v); shadowmapmatrix.mul(proj, mv); if(renderpath==R_FIXEDFUNCTION) shadowmapmatrix.projective(); else shadowmapmatrix.projective(-1, 1-shadowmapbias/float(shadowmapdist)); glColor3f(0, 0, 0); glDisable(GL_TEXTURE_2D); if(renderpath!=R_FIXEDFUNCTION) setenvparamf("shadowmapbias", SHPARAM_VERTEX, 0, -shadowmapbias/float(shadowmapdist), 1 - (shadowmapbias + (smoothshadowmappeel ? 0 : shadowmappeelbias))/float(shadowmapdist)); else glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); shadowmapcasters = 0; shadowmapmaxz = shadowfocus.z - shadowmapdist; shadowmapping = true; rendergame(); shadowmapping = false; shadowmapmaxz = min(shadowmapmaxz, shadowfocus.z); glEnable(GL_TEXTURE_2D); if(renderpath==R_FIXEDFUNCTION) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); else if(shadowmapcasters && smdepthpeel) { int sx, sy, sw, sh; bool scissoring = rtscissor && scissorblur(sx, sy, sw, sh) && sw > 0 && sh > 0; if(scissoring) { if(!hasFBO) { sx += screen->w-vieww; sy += screen->h-viewh; } glScissor(sx, sy, sw, sh); } if(!rtscissor || scissoring) rendershadowmapreceivers(); } glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); return shadowmapcasters>0; } bool flipdebug() const { return false; } void dodebug(int w, int h) { if(shadowmapcasters) { glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE); debugscissor(w, h); glColorMask(GL_FALSE, GL_FALSE, GL_TRUE, GL_FALSE); debugblurtiles(w, h); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } } } shadowmaptex; void cleanshadowmap() { shadowmaptex.cleanup(true); } VAR(ffsmscissor, 0, 1, 1); static void calcscissorbox() { int smx, smy, smw, smh; shadowmaptex.scissorblur(smx, smy, smw, smh); vec forward, right; vecfromyawpitch(camera1->yaw, 0, -1, 0, forward); vecfromyawpitch(camera1->yaw, 0, 0, -1, right); forward.mul(shadowmapradius*2.0f/shadowmaptex.viewh); right.mul(shadowmapradius*2.0f/shadowmaptex.vieww); vec bottom(shadowfocus); bottom.sub(vec(shadowdir).mul(shadowmapdist)); bottom.add(vec(forward).mul(smy - shadowmaptex.viewh/2)).add(vec(right).mul(smx - shadowmaptex.vieww/2)); vec top(bottom); top.add(vec(shadowdir).mul(shadowmapmaxz - (shadowfocus.z - shadowmapdist))); vec4 v[8]; float sx1 = 1, sy1 = 1, sx2 = -1, sy2 = -1; loopi(8) { vec c = i&4 ? top : bottom; if(i&1) c.add(vec(right).mul(smw)); if(i&2) c.add(vec(forward).mul(smh)); if(reflecting) c.z = 2*reflectz - c.z; vec4 &p = v[i]; mvpmatrix.transform(c, p); if(p.z >= -p.w) { float x = p.x / p.w, y = p.y / p.w; sx1 = min(sx1, x); sy1 = min(sy1, y); sx2 = max(sx2, x); sy2 = max(sy2, y); } } if(sx1 >= sx2 || sy1 >= sy2) return; loopi(8) { const vec4 &p = v[i]; if(p.z >= -p.w) continue; loopj(3) { const vec4 &o = v[i^(1<yaw*RAD); vec ro(o); ro.sub(camera1->o); ro.rotate_around_z(-(camera1->yaw+180)*RAD); ro.x += ro.z * skewdir.x + shadowoffset.x; ro.y += ro.z * skewdir.y + shadowmapradius * cosf(camera1->pitch*RAD) + shadowoffset.y; vec high(ro), low(ro); high.x += zrad * skewdir.x; high.y += zrad * skewdir.y; low.x -= zrad * skewdir.x; low.y -= zrad * skewdir.y; x1 = (min(high.x, low.x) - xyrad) / shadowmapradius; y1 = (min(high.y, low.y) - xyrad) / shadowmapradius; x2 = (max(high.x, low.x) + xyrad) / shadowmapradius; y2 = (max(high.y, low.y) + xyrad) / shadowmapradius; } bool addshadowmapcaster(const vec &o, float xyrad, float zrad) { if(o.z + zrad <= shadowfocus.z - shadowmapdist || o.z - zrad >= shadowfocus.z) return false; shadowmapmaxz = max(shadowmapmaxz, o.z + zrad); float x1, y1, x2, y2; calcshadowmapbb(o, xyrad, zrad, x1, y1, x2, y2); if(!shadowmaptex.addblurtiles(x1, y1, x2, y2, 2)) return false; shadowmapcasters++; return true; } bool isshadowmapreceiver(vtxarray *va) { if(!shadowmap || !shadowmapcasters) return false; if(va->shadowmapmax.z <= shadowfocus.z - shadowmapdist || va->shadowmapmin.z >= shadowmapmaxz) return false; float xyrad = SQRT2*0.5f*max(va->shadowmapmax.x-va->shadowmapmin.x, va->shadowmapmax.y-va->shadowmapmin.y), zrad = 0.5f*(va->shadowmapmax.z-va->shadowmapmin.z), x1, y1, x2, y2; if(xyrad<0 || zrad<0) return false; vec center(va->shadowmapmin.tovec()); center.add(va->shadowmapmax.tovec()).mul(0.5f); calcshadowmapbb(center, xyrad, zrad, x1, y1, x2, y2); return shadowmaptex.checkblurtiles(x1, y1, x2, y2, 2); #if 0 // cheaper inexact test float dz = va->o.z + va->size/2 - shadowfocus.z; float cx = shadowfocus.x + dz*shadowdir.x, cy = shadowfocus.y + dz*shadowdir.y; float skew = va->size/2*SHADOWSKEW; if(!shadowmap || !shadowmaptex || va->o.z + va->size <= shadowfocus.z - shadowmapdist || va->o.z >= shadowmapmaxz || va->o.x + va->size <= cx - shadowmapradius-skew || va->o.x >= cx + shadowmapradius+skew || va->o.y + va->size <= cy - shadowmapradius-skew || va->o.y >= cy + shadowmapradius+skew) return false; return true; #endif } bool isshadowmapcaster(const vec &o, float rad) { // cheaper inexact test float dz = o.z - shadowfocus.z; float cx = shadowfocus.x + dz*shadowdir.x, cy = shadowfocus.y + dz*shadowdir.y; float skew = rad*SHADOWSKEW; if(!shadowmapping || o.z + rad <= shadowfocus.z - shadowmapdist || o.z - rad >= shadowfocus.z || o.x + rad <= cx - shadowmapradius-skew || o.x - rad >= cx + shadowmapradius+skew || o.y + rad <= cy - shadowmapradius-skew || o.y - rad >= cy + shadowmapradius+skew) return false; return true; } void pushshadowmap() { if(!shadowmap || !shadowmaptex.rendertex) return; if(renderpath==R_FIXEDFUNCTION) { glBindTexture(GL_TEXTURE_2D, shadowmaptex.rendertex); const GLfloat *v = shadowmapmatrix.v; GLfloat texgenS[4] = { v[0], v[4], v[8], v[12] }, texgenT[4] = { v[1], v[5], v[9], v[13] }, texgenR[4] = { v[2], v[6], v[10], v[14] }; glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, texgenS); glEnable(GL_TEXTURE_GEN_S); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_T, GL_OBJECT_PLANE, texgenT); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_R, GL_OBJECT_PLANE, texgenR); glEnable(GL_TEXTURE_GEN_R); // intel driver bug workaround: when R texgen is enabled, it uses the value of Q, even if not enabled! // MUST set Q with glTexCoord4f, glTexCoord3f does not work glTexCoord4f(0, 0, 0, 1); glColor3f(shadowmapintensity/100.0f, shadowmapintensity/100.0f, shadowmapintensity/100.0f); if(ffsmscissor) calcscissorbox(); return; } glActiveTexture_(GL_TEXTURE7_ARB); glBindTexture(GL_TEXTURE_2D, shadowmaptex.rendertex); glActiveTexture_(GL_TEXTURE2_ARB); glMatrixMode(GL_TEXTURE); glLoadMatrixf(shadowmapmatrix.v); glMatrixMode(GL_MODELVIEW); glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); float r, g, b; if(!shadowmapambient) { if(skylightcolor[0] || skylightcolor[1] || skylightcolor[2]) { r = max(25.0f, 0.4f*ambientcolor[0] + 0.6f*max(ambientcolor[0], skylightcolor[0])); g = max(25.0f, 0.4f*ambientcolor[1] + 0.6f*max(ambientcolor[1], skylightcolor[1])); b = max(25.0f, 0.4f*ambientcolor[2] + 0.6f*max(ambientcolor[2], skylightcolor[2])); } else { r = max(25.0f, 2.0f*ambientcolor[0]); g = max(25.0f, 2.0f*ambientcolor[1]); b = max(25.0f, 2.0f*ambientcolor[2]); } } else { r = shadowmapambientcolor[0]; g = shadowmapambientcolor[1]; b = shadowmapambientcolor[2]; } setenvparamf("shadowmapambient", SHPARAM_PIXEL, 7, r/255.0f, g/255.0f, b/255.0f); } void popshadowmap() { if(!shadowmap || !shadowmaptex.rendertex) return; if(renderpath==R_FIXEDFUNCTION) { popscissor(); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_R); } } void rendershadowmap() { if(!shadowmap || (renderpath==R_FIXEDFUNCTION && (!hasSGIDT || !hasSGISH))) return; // Apple/ATI bug - fixed-function fog state can force software fallback even when fragment program is enabled glDisable(GL_FOG); shadowmaptex.render(1< mapmodels; vector other; occludequery *query; octaentities *next, *rnext; int distance; ivec o; int size; ivec bbmin, bbmax; octaentities(const ivec &o, int size) : query(0), o(o), size(size), bbmin(o), bbmax(o) { bbmin.add(size); } }; enum { OCCLUDE_NOTHING = 0, OCCLUDE_GEOM, OCCLUDE_BB, OCCLUDE_PARENT }; enum { MERGE_ORIGIN = 1<<0, MERGE_PART = 1<<1, MERGE_USE = 1<<2 }; struct vtxarray { vtxarray *parent; vector children; vtxarray *next, *rnext; // linked list of visible VOBs vertex *vdata; // vertex data ushort voffset; // offset into vertex data ushort *edata, *skydata; // vertex indices GLuint vbuf, ebuf, skybuf; // VBOs ushort minvert, maxvert; // DRE info elementset *eslist; // List of element indices sets (range) per texture materialsurface *matbuf; // buffer of material surfaces int verts, tris, texs, blendtris, blends, alphabacktris, alphaback, alphafronttris, alphafront, texmask, sky, explicitsky, skyfaces, skyclip, matsurfs, distance; double skyarea; ivec o; int size; // location and size of cube. ivec geommin, geommax; // BB of geom ivec shadowmapmin, shadowmapmax; // BB of shadowmapped surfaces ivec matmin, matmax; // BB of any materials ivec bbmin, bbmax; // BB of everything including children uchar curvfc, occluded; occludequery *query; vector mapmodels; vector grasstris; int hasmerges, mergelevel; uint dynlightmask; bool shadowed; }; struct cube; struct clipplanes { vec o, r, v[8]; plane p[12]; uchar side[12]; uchar size, visible; cube *owner; int version; }; struct facebounds { ushort u1, u2, v1, v2; bool empty() const { return u1 >= u2 || v1 >= v2; } }; struct tjoint { int next; ushort offset; uchar edge; }; struct cubeext { vtxarray *va; // vertex array for children, or NULL octaentities *ents; // map entities inside cube surfaceinfo surfaces[6]; // render info for each surface int tjoints; // linked list of t-joints uchar maxverts; // allocated space for verts vertinfo *verts() { return (vertinfo *)(this+1); } }; struct cube { cube *children; // points to 8 cube structures which are its children, or NULL. -Z first, then -Y, -X cubeext *ext; // extended info for the cube union { uchar edges[12]; // edges of the cube, each uchar is 2 4bit values denoting the range. // see documentation jpgs for more info. uint faces[3]; // 4 edges of each dimension together representing 2 perpendicular faces }; ushort texture[6]; // one for each face. same order as orient. uchar material; // empty-space material uchar collide; // collision faces of the cube uchar merged; // merged faces of the cube union { uchar escaped; // mask of which children have escaped merges, mask of merged faces that escaped if no children uchar visible; // visibility info for non-merged faces }; }; struct block3 { ivec o, s; int grid, orient; block3() {} block3(const selinfo &sel) : o(sel.o), s(sel.s), grid(sel.grid), orient(sel.orient) {} cube *c() { return (cube *)(this+1); } int size() const { return s.x*s.y*s.z; } }; struct editinfo { block3 *copy; editinfo() : copy(NULL) {} }; struct undoent { int i; entity e; }; struct undoblock // undo header, all data sits in payload { undoblock *prev, *next; int size, timestamp, numents; // if numents is 0, is a cube undo record, otherwise an entity undo record block3 *block() { return (block3 *)(this + 1); } int *gridmap() { block3 *ub = block(); return (int *)(ub->c() + ub->size()); } undoent *ents() { return (undoent *)(this + 1); } }; extern cube *worldroot; // the world data. only a ptr to 8 cubes (ie: like cube.children above) extern int wtris, wverts, vtris, vverts, glde, gbatches, rplanes; extern int allocnodes, allocva, selchildcount; const uint F_EMPTY = 0; // all edges in the range (0,0) const uint F_SOLID = 0x80808080; // all edges in the range (0,8) #define isempty(c) ((c).faces[0]==F_EMPTY) #define isentirelysolid(c) ((c).faces[0]==F_SOLID && (c).faces[1]==F_SOLID && (c).faces[2]==F_SOLID) #define setfaces(c, face) { (c).faces[0] = (c).faces[1] = (c).faces[2] = face; } #define solidfaces(c) setfaces(c, F_SOLID) #define emptyfaces(c) setfaces(c, F_EMPTY) #define edgemake(a, b) ((b)<<4|a) #define edgeget(edge, coord) ((coord) ? (edge)>>4 : (edge)&0xF) #define edgeset(edge, coord, val) ((edge) = ((coord) ? ((edge)&0xF)|((val)<<4) : ((edge)&0xF0)|(val))) #define cubeedge(c, d, x, y) ((c).edges[(((d)<<2)+((y)<<1)+(x))]) #define octadim(d) (1<<(d)) // creates mask for bit of given dimension #define octacoord(d, i) (((i)&octadim(d))>>(d)) #define oppositeocta(d, i) ((i)^octadim(D[d])) #define octaindex(d,x,y,z) (((z)<>(scale))&1)<<2) | ((((y)>>(scale))&1)<<1) | (((x)>>(scale))&1)) #define loopoctabox(c, size, o, s) uchar possible = octantrectangleoverlap(c, size, o, s); loopi(8) if(possible&(1<>1) #define dimcoord(orient) ((orient)&1) #define opposite(orient) ((orient)^1) enum { VFC_FULL_VISIBLE = 0, VFC_PART_VISIBLE, VFC_FOGGED, VFC_NOT_VISIBLE, PVS_FULL_VISIBLE, PVS_PART_VISIBLE, PVS_FOGGED }; sandboxgamemaker-2.7.1+dfsg/src/engine/material.cpp0000664000175000017500000010151311642642476022225 0ustar showardshoward#include "engine.h" struct QuadNode { int x, y, size; uint filled; QuadNode *child[4]; QuadNode(int x, int y, int size) : x(x), y(y), size(size), filled(0) { loopi(4) child[i] = 0; } void clear() { loopi(4) DELETEP(child[i]); } ~QuadNode() { clear(); } void insert(int mx, int my, int msize) { if(size == msize) { filled = 0xF; return; } int csize = size>>1, i = 0; if(mx >= x+csize) i |= 1; if(my >= y+csize) i |= 2; if(csize == msize) { filled |= (1 << i); return; } if(!child[i]) child[i] = new QuadNode(i&1 ? x+csize : x, i&2 ? y+csize : y, csize); child[i]->insert(mx, my, msize); loopj(4) if(child[j]) { if(child[j]->filled == 0xF) { DELETEP(child[j]); filled |= (1 << j); } } } void genmatsurf(uchar mat, uchar orient, uchar flags, int x, int y, int z, int size, materialsurface *&matbuf) { materialsurface &m = *matbuf++; m.material = mat; m.orient = orient; m.flags = flags; m.csize = size; m.rsize = size; int dim = dimension(orient); m.o[C[dim]] = x; m.o[R[dim]] = y; m.o[dim] = z; } void genmatsurfs(uchar mat, uchar orient, uchar flags, int z, materialsurface *&matbuf) { if(filled == 0xF) genmatsurf(mat, orient, flags, x, y, z, size, matbuf); else if(filled) { int csize = size>>1; loopi(4) if(filled & (1 << i)) genmatsurf(mat, orient, flags, i&1 ? x+csize : x, i&2 ? y+csize : y, z, csize, matbuf); } loopi(4) if(child[i]) child[i]->genmatsurfs(mat, orient, flags, z, matbuf); } }; void renderwaterfall(const materialsurface &m, Texture *tex, float scale, float offset, uchar mat, const vec *normal = NULL) { float xf = TEX_SCALE/(tex->xs*scale); float yf = TEX_SCALE/(tex->ys*scale); float d = 16.0f*lastmillis; int dim = dimension(m.orient), csize = C[dim]==2 ? m.rsize : m.csize, rsize = R[dim]==2 ? m.rsize : m.csize; float t = lastmillis; switch(mat) { case MAT_WATER: t /= renderpath!=R_FIXEDFUNCTION ? 600.0f : 300.0f; d /= 1000.0f; break; case MAT_LAVA: t /= 2000.0f; d /= 3000.0f; break; } if(varray::data.empty()) { varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); if(normal) varray::defattrib(varray::ATTRIB_NORMAL, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); varray::begin(GL_QUADS); } float wave = m.ends&2 ? (vertwater ? WATER_AMPLITUDE*sinf(t)-WATER_OFFSET : -WATER_OFFSET) : 0; loopi(4) { vec v(m.o.tovec()); v[dim] += dimcoord(m.orient) ? -offset : offset; if(i==1 || i==2) v[dim^1] += csize; if(i<=1) v.z += rsize; if(m.ends&(i<=1 ? 2 : 1)) v.z += i<=1 ? wave : -WATER_OFFSET-WATER_AMPLITUDE; varray::attribv<3>(v.v); if(normal) varray::attribv<3>(normal->v); varray::attrib(xf*v[dim^1], yf*(v.z+d)); } } void drawmaterial(int orient, int x, int y, int z, int csize, int rsize, float offset) { if(varray::data.empty()) { varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); varray::begin(GL_QUADS); } int dim = dimension(orient), c = C[dim], r = R[dim]; loopi(4) { const ivec &cc = facecoords[orient][i]; vec v(x, y, z); v[c] += cc[c]/8*csize; v[r] += cc[r]/8*rsize; v[dim] += dimcoord(orient) ? -offset : offset; varray::attribv<3>(v.v); } } struct material { const char *name; uchar id; } materials[] = { {"air", MAT_AIR}, {"water", MAT_WATER}, {"clip", MAT_CLIP}, {"glass", MAT_GLASS}, {"noclip", MAT_NOCLIP}, {"lava", MAT_LAVA}, {"aiclip", MAT_GAMECLIP}, {"respawn", MAT_DEATH}, {"alpha", MAT_ALPHA} }; int findmaterial(const char *name) { loopi(sizeof(materials)/sizeof(material)) { if(!strcmp(materials[i].name, name)) return materials[i].id; } return -1; } int visiblematerial(cube &c, int orient, int x, int y, int z, int size, uchar matmask) { uchar mat = c.material&matmask; switch(mat) { case MAT_AIR: break; case MAT_LAVA: case MAT_WATER: if(visibleface(c, orient, x, y, z, size, mat, MAT_AIR, matmask)) return (orient != O_BOTTOM ? MATSURF_VISIBLE : MATSURF_EDIT_ONLY); break; case MAT_GLASS: if(visibleface(c, orient, x, y, z, size, MAT_GLASS, MAT_AIR, matmask)) return MATSURF_VISIBLE; break; default: if(visibleface(c, orient, x, y, z, size, mat, MAT_AIR, matmask)) return MATSURF_EDIT_ONLY; break; } return MATSURF_NOT_VISIBLE; } void genmatsurfs(cube &c, int cx, int cy, int cz, int size, vector &matsurfs) { loopi(6) { static uchar matmasks[] = { MATF_VOLUME, MATF_CLIP, MAT_DEATH, MAT_ALPHA }; loopj(sizeof(matmasks)/sizeof(matmasks[0])) { int matmask = matmasks[j]; int vis = visiblematerial(c, i, cx, cy, cz, size, matmask); if(vis != MATSURF_NOT_VISIBLE) { materialsurface m; m.material = c.material&matmask; m.orient = i; m.flags = vis == MATSURF_EDIT_ONLY ? materialsurface::F_EDIT : 0; m.o = ivec(cx, cy, cz); m.csize = m.rsize = size; if(dimcoord(i)) m.o[dimension(i)] += size; matsurfs.add(m); break; } } } } static inline bool mergematcmp(const materialsurface &x, const materialsurface &y) { int dim = dimension(x.orient), c = C[dim], r = R[dim]; if(x.o[r] + x.rsize < y.o[r] + y.rsize) return true; if(x.o[r] + x.rsize > y.o[r] + y.rsize) return false; return x.o[c] < y.o[c]; } static int mergematr(materialsurface *m, int sz, materialsurface &n) { int dim = dimension(n.orient), c = C[dim], r = R[dim]; for(int i = sz-1; i >= 0; --i) { if(m[i].o[r] + m[i].rsize < n.o[r]) break; if(m[i].o[r] + m[i].rsize == n.o[r] && m[i].o[c] == n.o[c] && m[i].csize == n.csize) { n.o[r] = m[i].o[r]; n.rsize += m[i].rsize; memmove(&m[i], &m[i+1], (sz - (i+1)) * sizeof(materialsurface)); return 1; } } return 0; } static int mergematc(materialsurface &m, materialsurface &n) { int dim = dimension(n.orient), c = C[dim], r = R[dim]; if(m.o[r] == n.o[r] && m.rsize == n.rsize && m.o[c] + m.csize == n.o[c]) { n.o[c] = m.o[c]; n.csize += m.csize; return 1; } return 0; } static int mergemat(materialsurface *m, int sz, materialsurface &n) { for(bool merged = false; sz; merged = true) { int rmerged = mergematr(m, sz, n); sz -= rmerged; if(!rmerged && merged) break; if(!sz) break; int cmerged = mergematc(m[sz-1], n); sz -= cmerged; if(!cmerged) break; } m[sz++] = n; return sz; } static int mergemats(materialsurface *m, int sz) { quicksort(m, sz, mergematcmp); int nsz = 0; loopi(sz) nsz = mergemat(m, nsz, m[i]); return nsz; } static inline bool optmatcmp(const materialsurface &x, const materialsurface &y) { if(x.material < y.material) return true; if(x.material > y.material) return false; if(x.orient > y.orient) return true; if(x.orient < y.orient) return false; int dim = dimension(x.orient); return x.o[dim] < y.o[dim]; } VARF(optmats, 0, 1, 1, allchanged()); int optimizematsurfs(materialsurface *matbuf, int matsurfs) { quicksort(matbuf, matsurfs, optmatcmp); if(!optmats) return matsurfs; materialsurface *cur = matbuf, *end = matbuf+matsurfs; while(cur < end) { materialsurface *start = cur++; int dim = dimension(start->orient); while(cur < end && cur->material == start->material && cur->orient == start->orient && cur->flags == start->flags && cur->o[dim] == start->o[dim]) ++cur; if(!isliquid(start->material) || start->orient != O_TOP || !vertwater) { if(start!=matbuf) memmove(matbuf, start, (cur-start)*sizeof(materialsurface)); matbuf += mergemats(matbuf, cur-start); } else if(cur-start>=4) { QuadNode vmats(0, 0, worldsize); loopi(cur-start) vmats.insert(start[i].o[C[dim]], start[i].o[R[dim]], start[i].csize); vmats.genmatsurfs(start->material, start->orient, start->flags, start->o[dim], matbuf); } else { if(start!=matbuf) memmove(matbuf, start, (cur-start)*sizeof(materialsurface)); matbuf += cur-start; } } return matsurfs - (end-matbuf); } extern vector valist; struct waterinfo { materialsurface *m; double depth, area; }; void setupmaterials(int start, int len) { int hasmat = 0; vector water; unionfind uf; if(!len) len = valist.length(); for(int i = start; i < len; i++) { vtxarray *va = valist[i]; materialsurface *skip = NULL; loopj(va->matsurfs) { materialsurface &m = va->matbuf[j]; if(m.material==MAT_WATER && m.orient==O_TOP) { m.index = water.length(); loopvk(water) { materialsurface &n = *water[k].m; if(m.o.z!=n.o.z) continue; if(n.o.x+n.rsize==m.o.x || m.o.x+m.rsize==n.o.x) { if(n.o.y+n.csize>m.o.y && n.o.ym.o.x && n.o.xmaterial && m.orient == skip->orient && skip->skip < 0xFF) skip->skip++; else skip = &m; } } loopv(water) { int root = uf.find(i); if(i==root) continue; materialsurface &m = *water[i].m, &n = *water[root].m; if(m.light && (!m.light->attr[0] || !n.light || (n.light->attr[0] && m.light->attr[0] > n.light->attr[0]))) n.light = m.light; water[root].depth += water[i].depth; water[root].area += water[i].area; } loopv(water) { int root = uf.find(i); water[i].m->light = water[root].m->light; water[i].m->depth = (short)(water[root].depth/water[root].area); } if(hasmat&(1< ymin && ymax > xmin) continue; int c = sortorigin[dim]; if(c > xmin && c < xmax) return sortedit; if(c > ymin && c < ymax) return !sortedit; xmin = abs(xmin - c); xmax = abs(xmax - c); ymin = abs(ymin - c); ymax = abs(ymax - c); if(max(xmin, xmax) <= min(ymin, ymax)) return sortedit; else if(max(ymin, ymax) <= min(xmin, xmax)) return !sortedit; } if(x.material < y.material) return sortedit; if(x.material > y.material) return !sortedit; return false; } extern vtxarray *visibleva, *reflectedva; void sortmaterials(vector &vismats) { sortorigin = ivec(camera1->o); if(reflecting) sortorigin.z = int(reflectz - (camera1->o.z - reflectz)); vec dir; vecfromyawpitch(camera1->yaw, reflecting ? -camera1->pitch : camera1->pitch, 1, 0, dir); loopi(3) { dir[i] = fabs(dir[i]); sortdim[i] = i; } if(dir[sortdim[2]] > dir[sortdim[1]]) swap(sortdim[2], sortdim[1]); if(dir[sortdim[1]] > dir[sortdim[0]]) swap(sortdim[1], sortdim[0]); if(dir[sortdim[2]] > dir[sortdim[1]]) swap(sortdim[2], sortdim[1]); for(vtxarray *va = reflecting ? reflectedva : visibleva; va; va = reflecting ? va->rnext : va->next) { if(!va->matsurfs || va->occluded >= OCCLUDE_BB) continue; if(reflecting || refracting>0 ? va->o.z+va->size <= reflectz : va->o.z >= reflectz) continue; loopi(va->matsurfs) { materialsurface &m = va->matbuf[i]; if(!editmode || !showmat || envmapping) { if(m.material==MAT_WATER && (m.orient==O_TOP || (refracting<0 && reflectz>worldsize))) { i += m.skip; continue; } if(m.flags&materialsurface::F_EDIT) { i += m.skip; continue; } if(glaring && m.material!=MAT_LAVA) { i += m.skip; continue; } } else if(glaring) continue; vismats.add(&m); } } sortedit = editmode && showmat && !envmapping; vismats.sort(vismatcmp); } void rendermatgrid(vector &vismats) { enablepolygonoffset(GL_POLYGON_OFFSET_LINE); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); int lastmat = -1; loopvrev(vismats) { materialsurface &m = *vismats[i]; if(m.material != lastmat) { xtraverts += varray::end(); lastmat = m.material; switch(m.material) { case MAT_WATER: glColor3ub( 0, 0, 85); break; // blue case MAT_CLIP: glColor3ub(85, 0, 0); break; // red case MAT_GLASS: glColor3ub( 0, 85, 85); break; // cyan case MAT_NOCLIP: glColor3ub( 0, 85, 0); break; // green case MAT_LAVA: glColor3ub(85, 40, 0); break; // orange case MAT_GAMECLIP: glColor3ub(85, 85, 0); break; // yellow case MAT_DEATH: glColor3ub(40, 40, 40); break; // black case MAT_ALPHA: glColor3ub(85, 0, 85); break; // pink } } drawmaterial(m.orient, m.o.x, m.o.y, m.o.z, m.csize, m.rsize, -0.1f); } xtraverts += varray::end(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); disablepolygonoffset(GL_POLYGON_OFFSET_LINE); } VARP(glassenv, 0, 1, 1); void drawglass(int orient, int x, int y, int z, int csize, int rsize, float offset, const vec *normal = NULL) { if(varray::data.empty()) { varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); if(normal) varray::defattrib(varray::ATTRIB_NORMAL, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); varray::begin(GL_QUADS); } int dim = dimension(orient), c = C[dim], r = R[dim]; loopi(4) { const ivec &cc = facecoords[orient][i]; vec v(x, y, z); v[c] += cc[c]/8*csize; v[r] += cc[r]/8*rsize; v[dim] += dimcoord(orient) ? -offset : offset; vec reflect(v); reflect.sub(camera1->o); reflect[dim] = -reflect[dim]; varray::attribv<3>(v.v); if(normal) varray::attribv<3>(normal->v); varray::attribv<3>(reflect.v); } } VARFP(waterfallenv, 0, 1, 1, preloadwatershaders()); void rendermaterials() { vector vismats; sortmaterials(vismats); if(vismats.empty()) return; glDisable(GL_CULL_FACE); varray::enable(); MSlot &wslot = lookupmaterialslot(MAT_WATER, false), &lslot = lookupmaterialslot(MAT_LAVA, false); uchar wcol[4] = { watercolor[0], watercolor[1], watercolor[2], 192 }, wfcol[4] = { waterfallcolor[0], waterfallcolor[1], waterfallcolor[2], 192 }; if(!wfcol[0] && !wfcol[1] && !wfcol[2]) memcpy(wfcol, wcol, 3); int lastorient = -1, lastmat = -1; GLenum textured = GL_TEXTURE_2D; bool depth = true, blended = false, overbright = false, usedcamera = false, usedwaterfall = false; ushort envmapped = EMID_NONE; static const vec normals[6] = { vec(-1, 0, 0), vec( 1, 0, 0), vec(0, -1, 0), vec(0, 1, 0), vec(0, 0, -1), vec(0, 0, 1) }; static const float zerofog[4] = { 0, 0, 0, 1 }; float oldfogc[4]; glGetFloatv(GL_FOG_COLOR, oldfogc); int lastfogtype = 1; if(editmode && showmat && !envmapping) { glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); glEnable(GL_BLEND); blended = true; glDisable(GL_TEXTURE_2D); textured = 0; foggednotextureshader->set(); glFogfv(GL_FOG_COLOR, zerofog); lastfogtype = 0; loopv(vismats) { const materialsurface &m = *vismats[i]; if(lastmat!=m.material) { xtraverts += varray::end(); switch(m.material) { case MAT_WATER: glColor3ub(255, 128, 0); break; // blue case MAT_CLIP: glColor3ub( 0, 255, 255); break; // red case MAT_GLASS: glColor3ub(255, 0, 0); break; // cyan case MAT_NOCLIP: glColor3ub(255, 0, 255); break; // green case MAT_LAVA: glColor3ub( 0, 128, 255); break; // orange case MAT_GAMECLIP: glColor3ub( 0, 0, 255); break; // yellow case MAT_DEATH: glColor3ub(192, 192, 192); break; // black case MAT_ALPHA: glColor3ub( 0, 255, 0); break; // pink default: continue; } lastmat = m.material; } drawmaterial(m.orient, m.o.x, m.o.y, m.o.z, m.csize, m.rsize, -0.1f); } } else loopv(vismats) { const materialsurface &m = *vismats[i]; if(lastmat!=m.material || lastorient!=m.orient || (m.material==MAT_GLASS && envmapped && m.envmap != envmapped)) { int fogtype = lastfogtype; switch(m.material) { case MAT_WATER: if(!wslot.loaded || m.orient == O_TOP) continue; else if(lastmat==MAT_WATER) break; else { if(!wslot.sts.inrange(1)) continue; xtraverts += varray::end(); glBindTexture(GL_TEXTURE_2D, wslot.sts[1].t->id); } if(lastmat!=MAT_WATER || (lastorient==O_TOP)!=(m.orient==O_TOP)) { if(overbright) { resettmu(0); overbright = false; } if(m.orient==O_TOP) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4ubv(wcol); foggedshader->set(); fogtype = 1; if(!blended) { glEnable(GL_BLEND); blended = true; } if(depth) { glDepthMask(GL_FALSE); depth = false; } } else if(renderpath==R_FIXEDFUNCTION || ((!waterfallrefract || reflecting || refracting) && (!hasCM || !waterfallenv))) { glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); glColor3ubv(wfcol); foggedshader->set(); fogtype = 0; if(!blended) { glEnable(GL_BLEND); blended = true; } if(depth) { glDepthMask(GL_FALSE); depth = false; } } else { glColor3ubv(wfcol); fogtype = 1; if(!usedcamera) { setenvparamf("camera", SHPARAM_VERTEX, 0, camera1->o.x, camera1->o.y, camera1->o.z); usedcamera = true; } #define SETWATERFALLSHADER(name) \ do { \ static Shader *name##shader = NULL; \ if(!name##shader) name##shader = lookupshaderbyname(#name); \ name##shader->set(); \ } while(0) if(waterfallrefract && !reflecting && !refracting) { if(hasCM && waterfallenv) SETWATERFALLSHADER(waterfallenvrefract); else SETWATERFALLSHADER(waterfallrefract); if(blended) { glDisable(GL_BLEND); blended = false; } if(!depth) { glDepthMask(GL_TRUE); depth = true; } } else { SETWATERFALLSHADER(waterfallenv); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(!blended) { glEnable(GL_BLEND); blended = true; } if(depth) { glDepthMask(GL_FALSE); depth = false; } } if(!usedwaterfall) { Texture *dudv = wslot.sts.inrange(5) ? wslot.sts[5].t : notexture; float scale = 8.0f/(dudv->ys*wslot.scale); setlocalparamf("dudvoffset", SHPARAM_PIXEL, 1, 0, scale*16*lastmillis/1000.0f); glActiveTexture_(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, wslot.sts.inrange(4) ? wslot.sts[4].t->id : notexture->id); glActiveTexture_(GL_TEXTURE2_ARB); glBindTexture(GL_TEXTURE_2D, wslot.sts.inrange(5) ? wslot.sts[5].t->id : notexture->id); if(hasCM && waterfallenv) { glActiveTexture_(GL_TEXTURE3_ARB); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(wslot)); } if(waterfallrefract && (!reflecting || !refracting)) { extern void setupwaterfallrefract(GLenum tmu1, GLenum tmu2); setupwaterfallrefract(GL_TEXTURE4_ARB, GL_TEXTURE0_ARB); } else glActiveTexture_(GL_TEXTURE0_ARB); usedwaterfall = true; } } } if(textured!=GL_TEXTURE_2D) { if(textured) glDisable(textured); glEnable(GL_TEXTURE_2D); textured = GL_TEXTURE_2D; } break; case MAT_LAVA: if(!lslot.loaded) continue; if(lastmat==MAT_LAVA && lastorient!=O_TOP && m.orient!=O_TOP) break; else { int subslot = m.orient==O_TOP ? 0 : 1; if(!lslot.sts.inrange(subslot)) continue; xtraverts += varray::end(); glBindTexture(GL_TEXTURE_2D, lslot.sts[subslot].t->id); } if(lastmat!=MAT_LAVA) { if(!depth) { glDepthMask(GL_TRUE); depth = true; } if(blended) { glDisable(GL_BLEND); blended = false; } if(renderpath==R_FIXEDFUNCTION && !overbright) { setuptmu(0, "C * T x 2"); overbright = true; } float t = lastmillis/2000.0f; t -= floor(t); t = 1.0f - 2*fabs(t-0.5f); extern int glare; if(renderpath!=R_FIXEDFUNCTION && glare) t = 0.625f + 0.075f*t; else t = 0.5f + 0.5f*t; glColor3f(t, t, t); static Shader *lavashader = NULL, *lavaglareshader = NULL; if(!lavashader) lavashader = lookupshaderbyname("lava"); if(!lavaglareshader) lavaglareshader = lookupshaderbyname("lavaglare"); (glaring ? lavaglareshader : lavashader)->set(); fogtype = 1; } if(textured!=GL_TEXTURE_2D) { if(textured) glDisable(textured); glEnable(GL_TEXTURE_2D); textured = GL_TEXTURE_2D; } break; case MAT_GLASS: if((m.envmap==EMID_NONE || !glassenv || (envmapped==m.envmap && textured==GL_TEXTURE_CUBE_MAP_ARB)) && lastmat==MAT_GLASS) break; xtraverts += varray::end(); if(m.envmap!=EMID_NONE && glassenv) { if(textured!=GL_TEXTURE_CUBE_MAP_ARB) { if(textured) glDisable(textured); glEnable(GL_TEXTURE_CUBE_MAP_ARB); textured = GL_TEXTURE_CUBE_MAP_ARB; } if(envmapped!=m.envmap) { glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(m.envmap)); if(renderpath!=R_FIXEDFUNCTION && !usedcamera) { setenvparamf("camera", SHPARAM_VERTEX, 0, camera1->o.x, camera1->o.y, camera1->o.z); usedcamera = true; } envmapped = m.envmap; } } if(lastmat!=MAT_GLASS) { if(!blended) { glEnable(GL_BLEND); blended = true; } if(overbright) { resettmu(0); overbright = false; } if(depth) { glDepthMask(GL_FALSE); depth = false; } if(m.envmap!=EMID_NONE && glassenv) { if(renderpath==R_FIXEDFUNCTION) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(0.8f, 0.9f, 1.0f, 0.25f); fogtype = 1; } else { glBlendFunc(GL_ONE, GL_SRC_ALPHA); glColor3f(0, 0.5f, 1.0f); } static Shader *glassshader = NULL; if(!glassshader) glassshader = lookupshaderbyname("glass"); glassshader->set(); } else { if(textured) { glDisable(textured); textured = 0; } glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); glColor3f(0.3f, 0.15f, 0.0f); foggednotextureshader->set(); fogtype = 0; } } break; default: continue; } lastmat = m.material; lastorient = m.orient; if(fogtype!=lastfogtype) { glFogfv(GL_FOG_COLOR, fogtype ? oldfogc : zerofog); lastfogtype = fogtype; } } switch(m.material) { case MAT_WATER: renderwaterfall(m, wslot.sts[1].t, wslot.scale, 0.1f, MAT_WATER, renderpath!=R_FIXEDFUNCTION && hasCM && waterfallenv ? &normals[m.orient] : NULL); break; case MAT_LAVA: if(m.orient==O_TOP) renderlava(m, lslot.sts[0].t, lslot.scale); else renderwaterfall(m, lslot.sts[1].t, lslot.scale, 0.1f, MAT_LAVA); break; case MAT_GLASS: if(m.envmap!=EMID_NONE && glassenv) drawglass(m.orient, m.o.x, m.o.y, m.o.z, m.csize, m.rsize, 0.1f, renderpath!=R_FIXEDFUNCTION ? &normals[m.orient] : NULL); else drawmaterial(m.orient, m.o.x, m.o.y, m.o.z, m.csize, m.rsize, 0.1f); break; } } xtraverts += varray::end(); if(!depth) glDepthMask(GL_TRUE); if(blended) glDisable(GL_BLEND); if(overbright) resettmu(0); if(!lastfogtype) glFogfv(GL_FOG_COLOR, oldfogc); if(editmode && showmat && !envmapping) { foggedlineshader->set(); rendermatgrid(vismats); } varray::disable(); glEnable(GL_CULL_FACE); if(textured!=GL_TEXTURE_2D) { if(textured) glDisable(textured); glEnable(GL_TEXTURE_2D); } } sandboxgamemaker-2.7.1+dfsg/src/engine/server.cpp0000664000175000017500000010253311660231276021730 0ustar showardshoward// server.cpp: little more than enhanced multicaster // runs dedicated or as client coroutine #include "engine.h" #define LOGSTRLEN 512 static FILE *logfile = NULL; void closelogfile() { if(logfile) { fclose(logfile); logfile = NULL; } } void setlogfile(const char *fname) { closelogfile(); if(fname && fname[0]) { fname = findfile(fname, "w"); if(fname) logfile = fopen(fname, "w"); } setvbuf(logfile ? logfile : stdout, NULL, _IOLBF, BUFSIZ); } void logoutf(const char *fmt, ...) { va_list args; va_start(args, fmt); logoutfv(fmt, args); va_end(args); } static void writelog(FILE *file, const char *fmt, va_list args) { static char buf[LOGSTRLEN]; static uchar ubuf[512]; vformatstring(buf, fmt, args, sizeof(buf)); int len = strlen(buf), carry = 0; while(carry < len) { int numu = encodeutf8(ubuf, sizeof(ubuf)-1, &((uchar *)buf)[carry], len - carry, &carry); if(carry >= len) ubuf[numu++] = '\n'; fwrite(ubuf, 1, numu, file); } } #ifdef STANDALONE void fatal(const char *fmt, ...) { void cleanupserver(); cleanupserver(); defvformatstring(msg,fmt,fmt); if(logfile) logoutf("%s", msg); #ifdef WIN32 MessageBox(NULL, msg, "Cube 2: Sauerbraten fatal error", MB_OK|MB_SYSTEMMODAL); #else fprintf(stderr, "server error: %s\n", msg); #endif closelogfile(); exit(EXIT_FAILURE); } void conoutfv(int type, const char *fmt, va_list args) { string sf, sp; vformatstring(sf, fmt, args); filtertext(sp, sf); logoutf("%s", sp); } void conoutf(const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(CON_INFO, fmt, args); va_end(args); } void conoutf(int type, const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(type, fmt, args); va_end(args); } #endif // all network traffic is in 32bit ints, which are then compressed using the following simple scheme (assumes that most values are small). template static inline void putint_(T &p, int n) { if(n<128 && n>-127) p.put(n); else if(n<0x8000 && n>=-0x8000) { p.put(0x80); p.put(n); p.put(n>>8); } else { p.put(0x81); p.put(n); p.put(n>>8); p.put(n>>16); p.put(n>>24); } } void putint(ucharbuf &p, int n) { putint_(p, n); } void putint(packetbuf &p, int n) { putint_(p, n); } void putint(vector &p, int n) { putint_(p, n); } int getint(ucharbuf &p) { int c = (char)p.get(); if(c==-128) { int n = p.get(); n |= char(p.get())<<8; return n; } else if(c==-127) { int n = p.get(); n |= p.get()<<8; n |= p.get()<<16; return n|(p.get()<<24); } else return c; } // much smaller encoding for unsigned integers up to 28 bits, but can handle signed template static inline void putuint_(T &p, int n) { if(n < 0 || n >= (1<<21)) { p.put(0x80 | (n & 0x7F)); p.put(0x80 | ((n >> 7) & 0x7F)); p.put(0x80 | ((n >> 14) & 0x7F)); p.put(n >> 21); } else if(n < (1<<7)) p.put(n); else if(n < (1<<14)) { p.put(0x80 | (n & 0x7F)); p.put(n >> 7); } else { p.put(0x80 | (n & 0x7F)); p.put(0x80 | ((n >> 7) & 0x7F)); p.put(n >> 14); } } void putuint(ucharbuf &p, int n) { putuint_(p, n); } void putuint(packetbuf &p, int n) { putuint_(p, n); } void putuint(vector &p, int n) { putuint_(p, n); } int getuint(ucharbuf &p) { int n = p.get(); if(n & 0x80) { n += (p.get() << 7) - 0x80; if(n & (1<<14)) n += (p.get() << 14) - (1<<14); if(n & (1<<21)) n += (p.get() << 21) - (1<<21); if(n & (1<<28)) n |= -1<<28; } return n; } template static inline void putfloat_(T &p, float f) { lilswap(&f, 1); p.put((uchar *)&f, sizeof(float)); } void putfloat(ucharbuf &p, float f) { putfloat_(p, f); } void putfloat(packetbuf &p, float f) { putfloat_(p, f); } void putfloat(vector &p, float f) { putfloat_(p, f); } float getfloat(ucharbuf &p) { float f; p.get((uchar *)&f, sizeof(float)); return lilswap(f); } template static inline void sendstring_(const char *t, T &p) { while(*t) putint(p, *t++); putint(p, 0); } void sendstring(const char *t, ucharbuf &p) { sendstring_(t, p); } void sendstring(const char *t, packetbuf &p) { sendstring_(t, p); } void sendstring(const char *t, vector &p) { sendstring_(t, p); } void getstring(char *text, ucharbuf &p, int len) { char *t = text; do { if(t>=&text[len]) { text[len-1] = 0; return; } if(!p.remaining()) { *t = 0; return; } *t = getint(p); } while(*t++); } void filtertext(char *dst, const char *src, bool whitespace, int len) { for(int c = uchar(*src); c; c = uchar(*++src)) { if(c == '\f') { if(!*++src) break; continue; } if(iscubeprint(c) || (isspace(c) && whitespace)) { *dst++ = c; if(!--len) break; } } *dst = '\0'; } enum { ST_EMPTY, ST_LOCAL, ST_TCPIP }; struct client // server side version of "dynent" type { int type; int num; ENetPeer *peer; string hostname; void *info; }; vector clients; ENetHost *serverhost = NULL; int laststatus = 0; ENetSocket pongsock = ENET_SOCKET_NULL, lansock = ENET_SOCKET_NULL; void cleanupserver() { if(serverhost) enet_host_destroy(serverhost); serverhost = NULL; if(pongsock != ENET_SOCKET_NULL) enet_socket_destroy(pongsock); if(lansock != ENET_SOCKET_NULL) enet_socket_destroy(lansock); pongsock = lansock = ENET_SOCKET_NULL; } void process(ENetPacket *packet, int sender, int chan); //void disconnect_client(int n, int reason); void *getclientinfo(int i) { return !clients.inrange(i) || clients[i]->type==ST_EMPTY ? NULL : clients[i]->info; } ENetPeer *getclientpeer(int i) { return clients.inrange(i) && clients[i]->type==ST_TCPIP ? clients[i]->peer : NULL; } int getnumclients() { return clients.length(); } uint getclientip(int n) { return clients.inrange(n) && clients[n]->type==ST_TCPIP ? clients[n]->peer->address.host : 0; } void sendpacket(int n, int chan, ENetPacket *packet, int exclude) { if(n<0) { server::recordpacket(chan, packet->data, packet->dataLength); loopv(clients) if(i!=exclude && server::allowbroadcast(i)) sendpacket(i, chan, packet); return; } switch(clients[n]->type) { case ST_TCPIP: { enet_peer_send(clients[n]->peer, chan, packet); break; } #ifndef STANDALONE case ST_LOCAL: localservertoclient(chan, packet); break; #endif } } ENetPacket *sendf(int cn, int chan, const char *format, ...) { int exclude = -1; bool reliable = false; if(*format=='r') { reliable = true; ++format; } packetbuf p(MAXTRANS, reliable ? ENET_PACKET_FLAG_RELIABLE : 0); va_list args; va_start(args, format); while(*format) switch(*format++) { case 'x': exclude = va_arg(args, int); break; case 'v': { int n = va_arg(args, int); int *v = va_arg(args, int *); loopi(n) putint(p, v[i]); break; } case 'i': { int n = isdigit(*format) ? *format++-'0' : 1; loopi(n) putint(p, va_arg(args, int)); break; } case 'f': { int n = isdigit(*format) ? *format++-'0' : 1; loopi(n) putfloat(p, (float)va_arg(args, double)); break; } case 's': sendstring(va_arg(args, const char *), p); break; case 'm': { int n = va_arg(args, int); p.put(va_arg(args, uchar *), n); break; } } va_end(args); ENetPacket *packet = p.finalize(); sendpacket(cn, chan, packet, exclude); return packet->referenceCount > 0 ? packet : NULL; } ENetPacket *sendfile(int cn, int chan, stream *file, const char *format, ...) { if(cn < 0) { #ifdef STANDALONE return NULL; #endif } else if(!clients.inrange(cn)) return NULL; int len = (int)min(file->size(), stream::offset(INT_MAX)); if(len <= 0 || len > 16<<20) return NULL; packetbuf p(MAXTRANS+len, ENET_PACKET_FLAG_RELIABLE); va_list args; va_start(args, format); while(*format) switch(*format++) { case 'i': { int n = isdigit(*format) ? *format++-'0' : 1; loopi(n) putint(p, va_arg(args, int)); break; } case 's': sendstring(va_arg(args, const char *), p); break; case 'l': putint(p, len); break; } va_end(args); file->seek(0, SEEK_SET); file->read(p.subbuf(len).buf, len); ENetPacket *packet = p.finalize(); if(cn >= 0) sendpacket(cn, chan, packet, -1); #ifndef STANDALONE else sendclientpacket(packet, chan); #endif return packet->referenceCount > 0 ? packet : NULL; } const char *disc_reasons[] = { "normal", "end of packet", "client num", "kicked/banned", "tag type", "ip is banned", "server is in private mode", "server FULL", "connection timed out", "overflow" }; void disconnect_client(int n, int reason) { if(!clients.inrange(n) || clients[n]->type!=ST_TCPIP) return; enet_peer_disconnect(clients[n]->peer, reason); server::clientdisconnect(n); clients[n]->type = ST_EMPTY; clients[n]->peer->data = NULL; server::deleteclientinfo(clients[n]->info); clients[n]->info = NULL; defformatstring(s)("client (%s) disconnected because: %s", clients[n]->hostname, disc_reasons[reason]); logoutf("%s", s); server::sendservmsg(s); } void kicknonlocalclients(int reason) { loopv(clients) if(clients[i]->type==ST_TCPIP) disconnect_client(i, reason); } void process(ENetPacket *packet, int sender, int chan) // sender may be -1 { packetbuf p(packet); server::parsepacket(sender, chan, p); if(p.overread()) { disconnect_client(sender, DISC_EOP); return; } } void localclienttoserver(int chan, ENetPacket *packet) { client *c = NULL; loopv(clients) if(clients[i]->type==ST_LOCAL) { c = clients[i]; break; } if(c) process(packet, c->num, chan); } client &addclient() { loopv(clients) if(clients[i]->type==ST_EMPTY) { clients[i]->info = server::newclientinfo(); return *clients[i]; } client *c = new client; c->num = clients.length(); c->info = server::newclientinfo(); clients.add(c); return *c; } int localclients = 0, nonlocalclients = 0; bool hasnonlocalclients() { return nonlocalclients!=0; } bool haslocalclients() { return localclients!=0; } #ifdef STANDALONE bool resolverwait(const char *name, ENetAddress *address) { return enet_address_set_host(address, name) >= 0; } int connectwithtimeout(ENetSocket sock, const char *hostname, const ENetAddress &remoteaddress) { int result = enet_socket_connect(sock, &remoteaddress); if(result<0) enet_socket_destroy(sock); return result; } #endif ENetSocket mastersock = ENET_SOCKET_NULL; ENetAddress masteraddress = { ENET_HOST_ANY, ENET_PORT_ANY }, serveraddress = { ENET_HOST_ANY, ENET_PORT_ANY }; int lastupdatemaster = 0; vector masterout, masterin; int masteroutpos = 0, masterinpos = 0; VARN(updatemaster, allowupdatemaster, 0, 1, 1); void disconnectmaster() { if(mastersock != ENET_SOCKET_NULL) { enet_socket_destroy(mastersock); mastersock = ENET_SOCKET_NULL; } masterout.setsize(0); masterin.setsize(0); masteroutpos = masterinpos = 0; masteraddress.host = ENET_HOST_ANY; masteraddress.port = ENET_PORT_ANY; lastupdatemaster = 0; } SVARF(mastername, server::defaultmaster(), disconnectmaster()); VARF(masterport, 1, server::masterport(), 0xFFFF, disconnectmaster()); ENetSocket connectmaster() { if(!mastername[0]) return ENET_SOCKET_NULL; if(masteraddress.host == ENET_HOST_ANY) { #ifdef STANDALONE logoutf("looking up %s...", mastername); #endif masteraddress.port = masterport; if(!resolverwait(mastername, &masteraddress)) return ENET_SOCKET_NULL; } ENetSocket sock = enet_socket_create(ENET_SOCKET_TYPE_STREAM); if(sock != ENET_SOCKET_NULL && serveraddress.host != ENET_HOST_ANY && enet_socket_bind(sock, &serveraddress) < 0) { enet_socket_destroy(sock); sock = ENET_SOCKET_NULL; } if(sock == ENET_SOCKET_NULL || connectwithtimeout(sock, mastername, masteraddress) < 0) { #ifdef STANDALONE logoutf(sock==ENET_SOCKET_NULL ? "could not open socket" : "could not connect"); #endif return ENET_SOCKET_NULL; } enet_socket_set_option(sock, ENET_SOCKOPT_NONBLOCK, 1); return sock; } bool requestmaster(const char *req) { if(mastersock == ENET_SOCKET_NULL) { mastersock = connectmaster(); if(mastersock == ENET_SOCKET_NULL) return false; } masterout.put(req, strlen(req)); return true; } bool requestmasterf(const char *fmt, ...) { defvformatstring(req, fmt, fmt); return requestmaster(req); } void processmasterinput() { if(masterinpos >= masterin.length()) return; char *input = &masterin[masterinpos], *end = (char *)memchr(input, '\n', masterin.length() - masterinpos); while(end) { *end++ = '\0'; const char *args = input; while(args < end && !isspace(*args)) args++; int cmdlen = args - input; while(args < end && isspace(*args)) args++; if(!strncmp(input, "failreg", cmdlen)) conoutf(CON_ERROR, "master server registration failed: %s", args); else if(!strncmp(input, "succreg", cmdlen)) conoutf("master server registration succeeded"); else server::processmasterinput(input, cmdlen, args); masterinpos = end - masterin.getbuf(); input = end; end = (char *)memchr(input, '\n', masterin.length() - masterinpos); } if(masterinpos >= masterin.length()) { masterin.setsize(0); masterinpos = 0; } } void flushmasteroutput() { if(masterout.empty()) return; ENetBuffer buf; buf.data = &masterout[masteroutpos]; buf.dataLength = masterout.length() - masteroutpos; int sent = enet_socket_send(mastersock, NULL, &buf, 1); if(sent >= 0) { masteroutpos += sent; if(masteroutpos >= masterout.length()) { masterout.setsize(0); masteroutpos = 0; } } else disconnectmaster(); } void flushmasterinput() { if(masterin.length() >= masterin.capacity()) masterin.reserve(4096); ENetBuffer buf; buf.data = &masterin[masterin.length()]; buf.dataLength = masterin.capacity() - masterin.length(); int recv = enet_socket_receive(mastersock, NULL, &buf, 1); if(recv > 0) { masterin.advance(recv); processmasterinput(); } else disconnectmaster(); } static ENetAddress pongaddr; void sendserverinforeply(ucharbuf &p) { ENetBuffer buf; buf.data = p.buf; buf.dataLength = p.length(); enet_socket_send(pongsock, &pongaddr, &buf, 1); } void checkserversockets() // reply all server info requests { static ENetSocketSet sockset; ENET_SOCKETSET_EMPTY(sockset); ENetSocket maxsock = pongsock; ENET_SOCKETSET_ADD(sockset, pongsock); if(mastersock != ENET_SOCKET_NULL) { maxsock = max(maxsock, mastersock); ENET_SOCKETSET_ADD(sockset, mastersock); } if(lansock != ENET_SOCKET_NULL) { maxsock = max(maxsock, lansock); ENET_SOCKETSET_ADD(sockset, lansock); } if(enet_socketset_select(maxsock, &sockset, NULL, 0) <= 0) return; ENetBuffer buf; uchar pong[MAXTRANS]; loopi(2) { ENetSocket sock = i ? lansock : pongsock; if(sock == ENET_SOCKET_NULL || !ENET_SOCKETSET_CHECK(sockset, sock)) continue; buf.data = pong; buf.dataLength = sizeof(pong); int len = enet_socket_receive(sock, &pongaddr, &buf, 1); if(len < 0) return; ucharbuf req(pong, len), p(pong, sizeof(pong)); p.len += len; server::serverinforeply(req, p); } if(mastersock != ENET_SOCKET_NULL && ENET_SOCKETSET_CHECK(sockset, mastersock)) flushmasterinput(); } #define DEFAULTCLIENTS 8 VARF(maxclients, 0, DEFAULTCLIENTS, MAXCLIENTS, { if(!maxclients) maxclients = DEFAULTCLIENTS; }); VAR(serveruprate, 0, 0, INT_MAX); SVAR(serverip, ""); VARF(serverport, 0, server::serverport(), 0xFFFF, { if(!serverport) serverport = server::serverport(); }); #ifdef STANDALONE int curtime = 0, lastmillis = 0, totalmillis = 0; #endif void updatemasterserver() { if(mastername[0] && allowupdatemaster) requestmasterf("regserv %d\n", serverport); lastupdatemaster = totalmillis ? totalmillis : 1; } uint totalsecs = 0; void updatetime() { static int lastsec = 0; if(totalmillis - lastsec >= 1000) { int cursecs = (totalmillis - lastsec) / 1000; totalsecs += cursecs; lastsec += cursecs * 1000; } } void serverslice(bool dedicated, uint timeout) // main server update, called from main loop in sp, or from below in dedicated server { localclients = nonlocalclients = 0; loopv(clients) switch(clients[i]->type) { case ST_LOCAL: localclients++; break; case ST_TCPIP: nonlocalclients++; break; } if(!serverhost) { server::serverupdate(); server::sendpackets(); return; } // below is network only if(dedicated) { int millis = (int)enet_time_get(); curtime = server::ispaused() ? 0 : millis - totalmillis; totalmillis = millis; lastmillis += curtime; updatetime(); } server::serverupdate(); flushmasteroutput(); checkserversockets(); if(!lastupdatemaster || totalmillis-lastupdatemaster>60*60*1000) // send alive signal to masterserver every hour of uptime updatemasterserver(); if(totalmillis-laststatus>60*1000) // display bandwidth stats, useful for server ops { laststatus = totalmillis; if(nonlocalclients || serverhost->totalSentData || serverhost->totalReceivedData) logoutf("status: %d remote clients, %.1f send, %.1f rec (K/sec)", nonlocalclients, serverhost->totalSentData/60.0f/1024, serverhost->totalReceivedData/60.0f/1024); serverhost->totalSentData = serverhost->totalReceivedData = 0; } ENetEvent event; bool serviced = false; while(!serviced) { if(enet_host_check_events(serverhost, &event) <= 0) { if(enet_host_service(serverhost, &event, timeout) <= 0) break; serviced = true; } switch(event.type) { case ENET_EVENT_TYPE_CONNECT: { client &c = addclient(); c.type = ST_TCPIP; c.peer = event.peer; c.peer->data = &c; char hn[1024]; copystring(c.hostname, (enet_address_get_host_ip(&c.peer->address, hn, sizeof(hn))==0) ? hn : "unknown"); logoutf("client connected (%s)", c.hostname); int reason = server::clientconnect(c.num, c.peer->address.host); if(!reason) nonlocalclients++; else disconnect_client(c.num, reason); break; } case ENET_EVENT_TYPE_RECEIVE: { client *c = (client *)event.peer->data; if(c) process(event.packet, c->num, event.channelID); if(event.packet->referenceCount==0) enet_packet_destroy(event.packet); break; } case ENET_EVENT_TYPE_DISCONNECT: { client *c = (client *)event.peer->data; if(!c) break; logoutf("disconnected client (%s)", c->hostname); server::clientdisconnect(c->num); nonlocalclients--; c->type = ST_EMPTY; event.peer->data = NULL; server::deleteclientinfo(c->info); c->info = NULL; break; } default: break; } } if(server::sendpackets()) enet_host_flush(serverhost); } void flushserver(bool force) { if(server::sendpackets(force) && serverhost) enet_host_flush(serverhost); } #ifndef STANDALONE void localdisconnect(bool cleanup) { bool disconnected = false; loopv(clients) if(clients[i]->type==ST_LOCAL) { server::localdisconnect(i); localclients--; clients[i]->type = ST_EMPTY; server::deleteclientinfo(clients[i]->info); clients[i]->info = NULL; disconnected = true; } if(!disconnected) return; game::gamedisconnect(cleanup); #ifndef NEWGUI mainmenu = 1; #else UI::mainmenu = 1; #endif } void localconnect() { client &c = addclient(); c.type = ST_LOCAL; copystring(c.hostname, "local"); localclients++; game::gameconnect(false); server::localconnect(c.num); } #endif #ifdef WIN32 #include "shellapi.h" #define IDI_ICON1 1 static string apptip = ""; static HINSTANCE appinstance = NULL; static ATOM wndclass = 0; static HWND appwindow = NULL, conwindow = NULL; static HICON appicon = NULL; static HMENU appmenu = NULL; static HANDLE outhandle = NULL; static const int MAXLOGLINES = 200; struct logline { int len; char buf[LOGSTRLEN]; }; static ringbuf loglines; static void cleanupsystemtray() { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(nid)); nid.cbSize = sizeof(nid); nid.hWnd = appwindow; nid.uID = IDI_ICON1; Shell_NotifyIcon(NIM_DELETE, &nid); } static bool setupsystemtray(UINT uCallbackMessage) { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(nid)); nid.cbSize = sizeof(nid); nid.hWnd = appwindow; nid.uID = IDI_ICON1; nid.uCallbackMessage = uCallbackMessage; nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; nid.hIcon = appicon; strcpy(nid.szTip, apptip); if(Shell_NotifyIcon(NIM_ADD, &nid) != TRUE) return false; atexit(cleanupsystemtray); return true; } #if 0 static bool modifysystemtray() { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(nid)); nid.cbSize = sizeof(nid); nid.hWnd = appwindow; nid.uID = IDI_ICON1; nid.uFlags = NIF_TIP; strcpy(nid.szTip, apptip); return Shell_NotifyIcon(NIM_MODIFY, &nid) == TRUE; } #endif static void cleanupwindow() { if(!appinstance) return; if(appmenu) { DestroyMenu(appmenu); appmenu = NULL; } if(wndclass) { UnregisterClass(MAKEINTATOM(wndclass), appinstance); wndclass = 0; } } static BOOL WINAPI consolehandler(DWORD dwCtrlType) { switch(dwCtrlType) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: case CTRL_CLOSE_EVENT: exit(EXIT_SUCCESS); return TRUE; } return FALSE; } static void writeline(logline &line) { static uchar ubuf[512]; int len = strlen(line.buf), carry = 0; while(carry < len) { int numu = encodeutf8(ubuf, sizeof(ubuf), &((uchar *)line.buf)[carry], len - carry, &carry); DWORD written = 0; WriteConsole(outhandle, ubuf, numu, &written, NULL); } } static void setupconsole() { if(conwindow) return; if(!AllocConsole()) return; SetConsoleCtrlHandler(consolehandler, TRUE); conwindow = GetConsoleWindow(); SetConsoleTitle(apptip); //SendMessage(conwindow, WM_SETICON, ICON_SMALL, (LPARAM)appicon); SendMessage(conwindow, WM_SETICON, ICON_BIG, (LPARAM)appicon); outhandle = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO coninfo; GetConsoleScreenBufferInfo(outhandle, &coninfo); coninfo.dwSize.Y = MAXLOGLINES; SetConsoleScreenBufferSize(outhandle, coninfo.dwSize); SetConsoleCP(CP_UTF8); SetConsoleOutputCP(CP_UTF8); loopv(loglines) writeline(loglines[i]); } enum { MENU_OPENCONSOLE = 0, MENU_SHOWCONSOLE, MENU_HIDECONSOLE, MENU_EXIT }; static LRESULT CALLBACK handlemessages(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_APP: SetForegroundWindow(hWnd); switch(lParam) { //case WM_MOUSEMOVE: // break; case WM_LBUTTONUP: case WM_RBUTTONUP: { POINT pos; GetCursorPos(&pos); TrackPopupMenu(appmenu, TPM_CENTERALIGN|TPM_BOTTOMALIGN|TPM_RIGHTBUTTON, pos.x, pos.y, 0, hWnd, NULL); PostMessage(hWnd, WM_NULL, 0, 0); break; } } return 0; case WM_COMMAND: switch(LOWORD(wParam)) { case MENU_OPENCONSOLE: setupconsole(); if(conwindow) ModifyMenu(appmenu, 0, MF_BYPOSITION|MF_STRING, MENU_HIDECONSOLE, "Hide Console"); break; case MENU_SHOWCONSOLE: ShowWindow(conwindow, SW_SHOWNORMAL); ModifyMenu(appmenu, 0, MF_BYPOSITION|MF_STRING, MENU_HIDECONSOLE, "Hide Console"); break; case MENU_HIDECONSOLE: ShowWindow(conwindow, SW_HIDE); ModifyMenu(appmenu, 0, MF_BYPOSITION|MF_STRING, MENU_SHOWCONSOLE, "Show Console"); break; case MENU_EXIT: PostMessage(hWnd, WM_CLOSE, 0, 0); break; } return 0; case WM_CLOSE: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } static void setupwindow(const char *title) { copystring(apptip, title); //appinstance = GetModuleHandle(NULL); if(!appinstance) fatal("failed getting application instance"); appicon = LoadIcon(appinstance, MAKEINTRESOURCE(IDI_ICON1));//(HICON)LoadImage(appinstance, MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE); if(!appicon) fatal("failed loading icon"); appmenu = CreatePopupMenu(); if(!appmenu) fatal("failed creating popup menu"); AppendMenu(appmenu, MF_STRING, MENU_OPENCONSOLE, "Open Console"); AppendMenu(appmenu, MF_SEPARATOR, 0, NULL); AppendMenu(appmenu, MF_STRING, MENU_EXIT, "Exit"); //SetMenuDefaultItem(appmenu, 0, FALSE); WNDCLASS wc; memset(&wc, 0, sizeof(wc)); wc.hCursor = NULL; //LoadCursor(NULL, IDC_ARROW); wc.hIcon = appicon; wc.lpszMenuName = NULL; wc.lpszClassName = title; wc.style = 0; wc.hInstance = appinstance; wc.lpfnWndProc = handlemessages; wc.cbWndExtra = 0; wc.cbClsExtra = 0; wndclass = RegisterClass(&wc); if(!wndclass) fatal("failed registering window class"); appwindow = CreateWindow(MAKEINTATOM(wndclass), title, 0, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, HWND_MESSAGE, NULL, appinstance, NULL); if(!appwindow) fatal("failed creating window"); atexit(cleanupwindow); if(!setupsystemtray(WM_APP)) fatal("failed adding to system tray"); } static char *parsecommandline(const char *src, vector &args) { char *buf = new char[strlen(src) + 1], *dst = buf; for(;;) { while(isspace(*src)) src++; if(!*src) break; args.add(dst); for(bool quoted = false; *src && (quoted || !isspace(*src)); src++) { if(*src != '"') *dst++ = *src; else if(dst > buf && src[-1] == '\\') dst[-1] = '"'; else quoted = !quoted; } *dst++ = '\0'; } args.add(NULL); return buf; } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) { vector args; char *buf = parsecommandline(GetCommandLine(), args); appinstance = hInst; #ifdef STANDALONE int standalonemain(int argc, char **argv); int status = standalonemain(args.length()-1, args.getbuf()); #define main standalonemain #else SDL_SetModuleHandle(hInst); int status = SDL_main(args.length()-1, args.getbuf()); #endif delete[] buf; exit(status); return 0; } void logoutfv(const char *fmt, va_list args) { if(logfile) writelog(logfile, fmt, args); if(appwindow) { logline &line = loglines.add(); vformatstring(line.buf, fmt, args, sizeof(line.buf)); line.len = min(strlen(line.buf), sizeof(line.buf)-2); line.buf[line.len++] = '\n'; line.buf[line.len] = '\0'; if(outhandle) writeline(line); } } #else void logoutfv(const char *fmt, va_list args) { writelog(logfile ? logfile : stdout, fmt, args); } #endif void rundedicatedserver() { #ifdef WIN32 setupwindow("Cube 2: Sauerbraten server"); #endif logoutf("dedicated server started, waiting for clients..."); #ifdef WIN32 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); for(;;) { MSG msg; while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if(msg.message == WM_QUIT) exit(EXIT_SUCCESS); TranslateMessage(&msg); DispatchMessage(&msg); } serverslice(true, 5); } #else for(;;) serverslice(true, 5); #endif } bool servererror(bool dedicated, const char *desc) { #ifndef STANDALONE if(!dedicated) { conoutf(CON_ERROR, desc); cleanupserver(); } else #endif fatal(desc); return false; } bool setuplistenserver(bool dedicated) { ENetAddress address = { ENET_HOST_ANY, serverport <= 0 ? server::serverport() : serverport }; if(*serverip) { if(enet_address_set_host(&address, serverip)<0) conoutf(CON_WARN, "WARNING: server ip not resolved"); else serveraddress.host = address.host; } serverhost = enet_host_create(&address, min(maxclients + server::reserveclients(), MAXCLIENTS), server::numchannels(), 0, serveruprate); if(!serverhost) return servererror(dedicated, "could not create server host"); loopi(maxclients) serverhost->peers[i].data = NULL; address.port = server::serverinfoport(serverport > 0 ? serverport : -1); pongsock = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM); if(pongsock != ENET_SOCKET_NULL && enet_socket_bind(pongsock, &address) < 0) { enet_socket_destroy(pongsock); pongsock = ENET_SOCKET_NULL; } if(pongsock == ENET_SOCKET_NULL) return servererror(dedicated, "could not create server info socket"); else enet_socket_set_option(pongsock, ENET_SOCKOPT_NONBLOCK, 1); address.port = server::laninfoport(); lansock = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM); if(lansock != ENET_SOCKET_NULL && (enet_socket_set_option(lansock, ENET_SOCKOPT_REUSEADDR, 1) < 0 || enet_socket_bind(lansock, &address) < 0)) { enet_socket_destroy(lansock); lansock = ENET_SOCKET_NULL; } if(lansock == ENET_SOCKET_NULL) conoutf(CON_WARN, "WARNING: could not create LAN server info socket"); else enet_socket_set_option(lansock, ENET_SOCKOPT_NONBLOCK, 1); return true; } void initserver(bool listen, bool dedicated) { if(dedicated) execfile("server-init.cfg", false); if(listen) setuplistenserver(dedicated); server::serverinit(); if(listen) { updatemasterserver(); if(dedicated) rundedicatedserver(); // never returns #ifndef STANDALONE else conoutf("listen server started"); #endif } } #ifndef STANDALONE void startlistenserver(int *usemaster) { if(serverhost) { conoutf(CON_ERROR, "listen server is already running"); return; } allowupdatemaster = *usemaster>0 ? 1 : 0; if(!setuplistenserver(false)) return; updatemasterserver(); conoutf("listen server started for %d clients%s", maxclients, allowupdatemaster ? " and listed with master server" : ""); } COMMAND(startlistenserver, "i"); void stoplistenserver() { if(!serverhost) { conoutf(CON_ERROR, "listen server is not running"); return; } kicknonlocalclients(); enet_host_flush(serverhost); cleanupserver(); conoutf("listen server stopped"); } COMMAND(stoplistenserver, ""); #endif bool serveroption(char *opt) { switch(opt[1]) { case 'u': setvar("serveruprate", atoi(opt+2)); return true; case 'c': setvar("maxclients", atoi(opt+2)); return true; case 'i': setsvar("serverip", opt+2); return true; case 'j': setvar("serverport", atoi(opt+2)); return true; case 'm': setsvar("mastername", opt+2); setvar("updatemaster", mastername[0] ? 1 : 0); return true; #ifdef STANDALONE case 'q': logoutf("Using home directory: %s", opt); sethomedir(opt+2); return true; case 'k': logoutf("Adding package directory: %s", opt); addpackagedir(opt+2); return true; case 'g': logoutf("Setting log file: %s", opt); setlogfile(opt+2); return true; #endif default: return false; } } vector gameargs; #ifdef STANDALONE int main(int argc, char **argv) { setlogfile(NULL); if(enet_initialize()<0) fatal("Unable to initialise network module"); atexit(enet_deinitialize); enet_time_set(0); for(int i = 1; i0 ? 0.2f : -0.2f); o[D[d]] += float(dc) * s[D[d]] + f, glBegin(GL_LINE_LOOP); glVertex3fv(o.v); o[R[d]] += s[R[d]]; glVertex3fv(o.v); o[C[d]] += s[C[d]]; glVertex3fv(o.v); o[R[d]] -= s[R[d]]; glVertex3fv(o.v); glEnd(); xtraverts += 4; } void boxs3D(const vec &o, vec s, int g) { s.mul(g); loopi(6) boxs(i, o, s); } void boxsgrid(int orient, vec o, vec s, int g) { int d = dimension(orient), dc= dimcoord(orient); float ox = o[R[d]], oy = o[C[d]], xs = s[R[d]], ys = s[C[d]], f = !outline ? 0 : (dc>0 ? 0.2f : -0.2f); o[D[d]] += dc * s[D[d]]*g + f; glBegin(GL_LINES); loop(x, xs) { o[R[d]] += g; glVertex3fv(o.v); o[C[d]] += ys*g; glVertex3fv(o.v); o[C[d]] = oy; } loop(y, ys) { o[C[d]] += g; o[R[d]] = ox; glVertex3fv(o.v); o[R[d]] += xs*g; glVertex3fv(o.v); } glEnd(); xtraverts += 2*int(xs+ys); } selinfo sel, lastsel; int orient = 0; int gridsize = 8; ivec cor, lastcor; ivec cur, lastcur; extern int entediting; bool editmode = false; bool havesel = false; bool hmapsel = false; int horient = 0; extern int entmoving; VARF(dragging, 0, 0, 1, if(!dragging || cor[0]<0) return; lastcur = cur; lastcor = cor; sel.grid = gridsize; sel.orient = orient; ); VARF(moving, 0, 0, 1, if(!moving) return; vec v(cur.v); v.add(1); moving = pointinsel(sel, v); if(moving) havesel = false; // tell cursorupdate to create handle ); VARF(gridpower, 0, 3, 12, { if(dragging) return; gridsize = 1<=worldsize) gridsize = worldsize/2; cancelsel(); }); VAR(passthroughsel, 0, 0, 1); VAR(editing, 1, 0, 0); VAR(selectcorners, 0, 0, 1); VARF(hmapedit, 0, 0, 1, horient = sel.orient); void forcenextundo() { lastsel.orient = -1; } void cubecancel() { havesel = false; moving = dragging = hmapedit = passthroughsel = 0; forcenextundo(); } void cancelsel() { cubecancel(); entcancel(); } void toggleedit(bool force) { if(player->state!=CS_ALIVE && player->state!=CS_DEAD && player->state!=CS_EDITING) return; // do not allow dead players to edit to avoid state confusion if(!editmode && !game::allowedittoggle()) return; // not in most multiplayer modes if(!(editmode = !editmode)) { player->state = player->editstate; player->o.z -= player->eyeheight; // entinmap wants feet pos entinmap(player); // find spawn closest to current floating pos } else { game::resetgamestate(); player->editstate = player->state; player->state = CS_EDITING; } cancelsel(); stoppaintblendmap(); keyrepeat(editmode); editing = entediting = editmode; extern int fullbright; if(fullbright) initlights(); if(!force) game::edittoggled(editmode); } bool noedit(bool view, bool msg) { if(!editmode) { if(msg) conoutf(CON_ERROR, "operation only allowed in edit mode"); return true; } if(view || haveselent()) return false; float r = 1.0f; vec o = sel.o.tovec(), s = sel.s.tovec(); s.mul(float(sel.grid) / 2.0f); o.add(s); r = float(max(s.x, max(s.y, s.z))); bool viewable = (isvisiblesphere(r, o) != VFC_NOT_VISIBLE); if(!viewable && msg) conoutf(CON_ERROR, "selection not in view"); return !viewable; } extern void createheightmap(); void reorient() { sel.cx = 0; sel.cy = 0; sel.cxs = sel.s[R[dimension(orient)]]*2; sel.cys = sel.s[C[dimension(orient)]]*2; sel.orient = orient; } void selextend() { if(noedit(true)) return; loopi(3) { if(cur[i]=sel.o[i]+sel.s[i]*sel.grid) { sel.s[i] = (cur[i]-sel.o[i])/sel.grid+1; } } } ICOMMAND(edittoggle, "", (), toggleedit(false)); COMMAND(entcancel, ""); COMMAND(cubecancel, ""); COMMAND(cancelsel, ""); COMMAND(reorient, ""); COMMAND(selextend, ""); ///////// selection support ///////////// cube &blockcube(int x, int y, int z, const block3 &b, int rgrid) // looks up a world cube, based on coordinates mapped by the block { int dim = dimension(b.orient), dc = dimcoord(b.orient); ivec s(dim, x*b.grid, y*b.grid, dc*(b.s[dim]-1)*b.grid); s.add(b.o); if(dc) s[dim] -= z*b.grid; else s[dim] += z*b.grid; return lookupcube(s.x, s.y, s.z, rgrid); } #define loopxy(b) loop(y,(b).s[C[dimension((b).orient)]]) loop(x,(b).s[R[dimension((b).orient)]]) #define loopxyz(b, r, f) { loop(z,(b).s[D[dimension((b).orient)]]) loopxy((b)) { cube &c = blockcube(x,y,z,b,r); f; } } #define loopselxyz(f) { makeundo(); loopxyz(sel, sel.grid, f); changed(sel); } #define selcube(x, y, z) blockcube(x, y, z, sel, sel.grid) ////////////// cursor /////////////// int selchildcount=0; ICOMMAND(havesel, "", (), intret(havesel ? selchildcount : 0)); void countselchild(cube *c, const ivec &cor, int size) { ivec ss(sel.s); ss.mul(sel.grid); loopoctabox(cor, size, sel.o, ss) { ivec o(i, cor.x, cor.y, cor.z, size); if(c[i].children) countselchild(c[i].children, o, size/2); else selchildcount++; } } void normalizelookupcube(int x, int y, int z) { if(lusize>gridsize) { lu.x += (x-lu.x)/gridsize*gridsize; lu.y += (y-lu.y)/gridsize*gridsize; lu.z += (z-lu.z)/gridsize*gridsize; } else if(gridsize>lusize) { lu.x &= ~(gridsize-1); lu.y &= ~(gridsize-1); lu.z &= ~(gridsize-1); } lusize = gridsize; } void updateselection() { sel.o.x = min(lastcur.x, cur.x); sel.o.y = min(lastcur.y, cur.y); sel.o.z = min(lastcur.z, cur.z); sel.s.x = abs(lastcur.x-cur.x)/sel.grid+1; sel.s.y = abs(lastcur.y-cur.y)/sel.grid+1; sel.s.z = abs(lastcur.z-cur.z)/sel.grid+1; } void editmoveplane(const vec &o, const vec &ray, int d, float off, vec &handle, vec &dest, bool first) { plane pl(d, off); float dist = 0.0f; if(pl.rayintersect(player->o, ray, dist)) { dest = ray; dest.mul(dist); dest.add(player->o); if(first) { handle = dest; handle.sub(o); } dest.sub(handle); } } inline bool isheightmap(int orient, int d, bool empty, cube *c); extern void entdrag(const vec &ray); extern bool hoveringonent(int ent, int orient); extern void renderentselection(const vec &o, const vec &ray, bool entmoving); extern float rayent(const vec &o, const vec &ray, float radius, int mode, int size, int &orient, int &ent); VAR(gridlookup, 0, 0, 1); VAR(passthroughcube, 0, 1, 1); VARP(showselgrid, 0, 1, 1); void rendereditcursor() { int d = dimension(sel.orient), od = dimension(orient), odc = dimcoord(orient); #ifndef NEWGUI bool hidecursor = g3d_windowhit(true, false) || blendpaintmode, hovering = false; #else bool hidecursor = blendpaintmode, hovering = false; #endif hmapsel = false; if(moving) { ivec e; static vec v, handle; editmoveplane(sel.o.tovec(), camdir, od, sel.o[D[od]]+odc*sel.grid*sel.s[D[od]], handle, v, !havesel); if(!havesel) { v.add(handle); (e = handle).mask(~(sel.grid-1)); v.sub(handle = e.tovec()); havesel = true; } (e = v).mask(~(sel.grid-1)); sel.o[R[od]] = e[R[od]]; sel.o[C[od]] = e[C[od]]; } else if(entmoving) { entdrag(camdir); } else { ivec w; float sdist = 0, wdist = 0, t; int entorient = 0, ent = -1; wdist = rayent(player->o, camdir, 1e16f, (editmode && showmat ? RAY_EDITMAT : 0) // select cubes first | (!dragging && entediting ? RAY_ENTS : 0) | RAY_SKIPFIRST | (passthroughcube==1 ? RAY_PASS : 0), gridsize, entorient, ent); if((havesel || dragging) && !passthroughsel && !hmapedit) // now try selecting the selection if(rayrectintersect(sel.o.tovec(), vec(sel.s.tovec()).mul(sel.grid), player->o, camdir, sdist, orient)) { // and choose the nearest of the two if(sdist < wdist) { wdist = sdist; ent = -1; } } if((hovering = hoveringonent(hidecursor ? -1 : ent, entorient))) { if(!havesel) { selchildcount = 0; sel.s = ivec(0, 0, 0); } } else { vec w = vec(camdir).mul(wdist+0.05f).add(player->o); if(!insideworld(w)) { loopi(3) wdist = min(wdist, ((camdir[i] > 0 ? worldsize : 0) - player->o[i]) / camdir[i]); w = vec(camdir).mul(wdist-0.05f).add(player->o); if(!insideworld(w)) { wdist = 0; loopi(3) w[i] = clamp(player->o[i], 0.0f, float(worldsize)); } } cube *c = &lookupcube(int(w.x), int(w.y), int(w.z)); if(gridlookup && !dragging && !moving && !havesel && hmapedit!=1) gridsize = lusize; int mag = lusize / gridsize; normalizelookupcube(int(w.x), int(w.y), int(w.z)); if(sdist == 0 || sdist > wdist) rayrectintersect(lu.tovec(), vec(gridsize), player->o, camdir, t=0, orient); // just getting orient cur = lu; cor = vec(w).mul(2).div(gridsize); od = dimension(orient); d = dimension(sel.orient); if(hmapedit==1 && dimcoord(horient) == (camdir[dimension(horient)]<0)) { hmapsel = isheightmap(horient, dimension(horient), false, c); if(hmapsel) od = dimension(orient = horient); } if(dragging) { updateselection(); sel.cx = min(cor[R[d]], lastcor[R[d]]); sel.cy = min(cor[C[d]], lastcor[C[d]]); sel.cxs = max(cor[R[d]], lastcor[R[d]]); sel.cys = max(cor[C[d]], lastcor[C[d]]); if(!selectcorners) { sel.cx &= ~1; sel.cy &= ~1; sel.cxs &= ~1; sel.cys &= ~1; sel.cxs -= sel.cx-2; sel.cys -= sel.cy-2; } else { sel.cxs -= sel.cx-1; sel.cys -= sel.cy-1; } sel.cx &= 1; sel.cy &= 1; havesel = true; } else if(!havesel) { sel.o = lu; sel.s.x = sel.s.y = sel.s.z = 1; sel.cx = sel.cy = 0; sel.cxs = sel.cys = 2; sel.grid = gridsize; sel.orient = orient; d = od; } sel.corner = (cor[R[d]]-(lu[R[d]]*2)/gridsize)+(cor[C[d]]-(lu[C[d]]*2)/gridsize)*2; selchildcount = 0; countselchild(worldroot, ivec(0, 0, 0), worldsize/2); if(mag>1 && selchildcount==1) selchildcount = -mag; } } glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); // cursors lineshader->set(); renderentselection(player->o, camdir, entmoving!=0); enablepolygonoffset(GL_POLYGON_OFFSET_LINE); if(!moving && !hovering && !hidecursor) { if(hmapedit==1) glColor3ub(0, hmapsel ? 255 : 40, 0); else glColor3ub(120,120,120); boxs(orient, lu.tovec(), vec(lusize)); } // selections if(havesel) { d = dimension(sel.orient); glColor3ub(50,50,50); // grid boxsgrid(sel.orient, sel.o.tovec(), sel.s.tovec(), sel.grid); glColor3ub(200,0,0); // 0 reference boxs3D(sel.o.tovec().sub(0.5f*min(gridsize*0.25f, 2.0f)), vec(min(gridsize*0.25f, 2.0f)), 1); glColor3ub(200,200,200);// 2D selection box vec co(sel.o.v), cs(sel.s.v); co[R[d]] += 0.5f*(sel.cx*gridsize); co[C[d]] += 0.5f*(sel.cy*gridsize); cs[R[d]] = 0.5f*(sel.cxs*gridsize); cs[C[d]] = 0.5f*(sel.cys*gridsize); cs[D[d]] *= gridsize; boxs(sel.orient, co, cs); if(hmapedit==1) // 3D selection box glColor3ub(0,120,0); else glColor3ub(0,0,120); boxs3D(sel.o.tovec(), sel.s.tovec(), sel.grid); if (showselgrid) { vec a, b; glColor3ub(20, 20, 60); //note that vector b is multiplied by g (aka, sel.grid) inside the function, so undo that here (a=sel.o.tovec()).x=0; (b=sel.s.tovec()).x=worldsize/sel.grid; boxs3D(a, b, sel.grid); (a=sel.o.tovec()).y=0; (b=sel.s.tovec()).y=worldsize/sel.grid; boxs3D(a, b, sel.grid); (a=sel.o.tovec()).z=0; (b=sel.s.tovec()).z=worldsize/sel.grid; boxs3D(a, b, sel.grid); } } disablepolygonoffset(GL_POLYGON_OFFSET_LINE); notextureshader->set(); glDisable(GL_BLEND); } void tryedit() { extern int hidehud; if(!editmode || hidehud) return; #ifndef NEWGUI if(mainmenu) return; #else if(UI::mainmenu) return; #endif if(blendpaintmode) trypaintblendmap(); } //////////// ready changes to vertex arrays //////////// static bool haschanged = false; void readychanges(block3 &b, cube *c, const ivec &cor, int size) { loopoctabox(cor, size, b.o, b.s) { ivec o(i, cor.x, cor.y, cor.z, size); if(c[i].ext) { if(c[i].ext->va) // removes va s so that octarender will recreate { int hasmerges = c[i].ext->va->hasmerges; destroyva(c[i].ext->va); c[i].ext->va = NULL; if(hasmerges) invalidatemerges(c[i], o, size, true); } freeoctaentities(c[i]); c[i].ext->tjoints = -1; } if(c[i].children) { if(size<=1) { solidfaces(c[i]); discardchildren(c[i], true); brightencube(c[i]); } else readychanges(b, c[i].children, o, size/2); } else brightencube(c[i]); } } void commitchanges(bool force) { if(!force && !haschanged) return; haschanged = false; extern vector valist; int oldlen = valist.length(); resetclipplanes(); entitiesinoctanodes(); inbetweenframes = false; octarender(); inbetweenframes = true; setupmaterials(oldlen); invalidatepostfx(); updatevabbs(); resetblobs(); } void changed(const block3 &sel, bool commit = true) { if(sel.s.iszero()) return; block3 b = sel; loopi(3) b.s[i] *= b.grid; b.grid = 1; loopi(3) // the changed blocks are the selected cubes { b.o[i] -= 1; b.s[i] += 2; readychanges(b, worldroot, ivec(0, 0, 0), worldsize/2); b.o[i] += 1; b.s[i] -= 2; } haschanged = true; if(commit) commitchanges(); } //////////// copy and undo ///////////// static inline void copycube(const cube &src, cube &dst) { dst = src; dst.visible = 0; dst.collide = 0; dst.merged = 0; dst.ext = NULL; // src cube is responsible for va destruction if(src.children) { dst.children = newcubes(F_EMPTY); loopi(8) copycube(src.children[i], dst.children[i]); } } static inline void pastecube(const cube &src, cube &dst) { discardchildren(dst); copycube(src, dst); } void blockcopy(const block3 &s, int rgrid, block3 *b) { *b = s; cube *q = b->c(); loopxyz(s, rgrid, copycube(c, *q++)); } block3 *blockcopy(const block3 &s, int rgrid) { block3 *b = (block3 *)new uchar[sizeof(block3)+sizeof(cube)*s.size()]; blockcopy(s, rgrid, b); return b; } void freeblock(block3 *b, bool alloced = true) { cube *q = b->c(); loopi(b->size()) discardchildren(*q++); if(alloced) delete[] b; } void selgridmap(selinfo &sel, int *g) // generates a map of the cube sizes at each grid point { loopxyz(sel, -sel.grid, (*g++ = lusize, (void)c)); } void freeundo(undoblock *u) { if(!u->numents) freeblock(u->block(), false); delete[] (uchar *)u; } void pasteundo(undoblock *u) { if(u->numents) pasteundoents(u); else { block3 *b = u->block(); cube *s = b->c(); int *g = u->gridmap(); loopxyz(*b, *g++, pastecube(*s++, c)); } } static inline int undosize(undoblock *u) { if(u->numents) return u->numents*sizeof(undoent); else { block3 *b = u->block(); cube *q = b->c(); int size = b->size(), total = size*sizeof(int); loopj(size) total += familysize(*q++)*sizeof(cube); return total; } } struct undolist { undoblock *first, *last; undolist() : first(NULL), last(NULL) {} bool empty() { return !first; } void add(undoblock *u) { u->next = NULL; u->prev = last; if(!first) first = last = u; else { last->next = u; last = u; } } undoblock *popfirst() { undoblock *u = first; first = first->next; if(first) first->prev = NULL; else last = NULL; return u; } undoblock *poplast() { undoblock *u = last; last = last->prev; if(last) last->next = NULL; else first = NULL; return u; } }; undolist undos, redos; VARP(undomegs, 0, 5, 100); // bounded by n megs int totalundos = 0; void pruneundos(int maxremain) // bound memory { while(totalundos > maxremain && !undos.empty()) { undoblock *u = undos.popfirst(); totalundos -= u->size; freeundo(u); } //conoutf(CON_DEBUG, "undo: %d of %d(%%%d)", totalundos, undomegs<<20, totalundos*100/(undomegs<<20)); while(!redos.empty()) { undoblock *u = redos.popfirst(); totalundos -= u->size; freeundo(u); } } void clearundos() { pruneundos(0); } COMMAND(clearundos, ""); undoblock *newundocube(selinfo &s) { int ssize = s.size(), selgridsize = ssize*sizeof(int), blocksize = sizeof(block3)+ssize*sizeof(cube); undoblock *u = (undoblock *)new uchar[sizeof(undoblock) + blocksize + selgridsize]; u->numents = 0; block3 *b = (block3 *)(u + 1); blockcopy(s, -s.grid, b); int *g = (int *)((uchar *)b + blocksize); selgridmap(s, g); return u; } void addundo(undoblock *u) { u->size = undosize(u); u->timestamp = totalmillis; undos.add(u); totalundos += u->size; pruneundos(undomegs<<20); } VARP(nompedit, 0, 1, 1); void makeundoex(selinfo &s) { if(nompedit && multiplayer(false)) return; undoblock *u = newundocube(s); addundo(u); } void makeundo() // stores state of selected cubes before editing { if(lastsel==sel || sel.s.iszero()) return; lastsel=sel; makeundoex(sel); } void swapundo(undolist &a, undolist &b, const char *s) { if(noedit() || (nompedit && multiplayer())) return; if(a.empty()) { conoutf(CON_WARN, "nothing more to %s", s); return; } int ts = a.last->timestamp; selinfo l = sel; while(!a.empty() && ts==a.last->timestamp) { undoblock *u = a.poplast(), *r; if(u->numents) r = copyundoents(u); else { block3 *ub = u->block(); l.o = ub->o; l.s = ub->s; l.grid = ub->grid; l.orient = ub->orient; r = newundocube(l); } r->size = u->size; r->timestamp = totalmillis; b.add(r); pasteundo(u); if(!u->numents) changed(l, false); freeundo(u); } commitchanges(); if(!hmapsel) { sel = l; reorient(); } forcenextundo(); } void editundo() { swapundo(undos, redos, "undo"); } void editredo() { swapundo(redos, undos, "redo"); } vector editinfos; editinfo *localedit = NULL; static void packcube(cube &c, vector &buf) { if(c.children) { buf.put(0xFF); loopi(8) packcube(c.children[i], buf); } else { buf.put(c.material); cube data = c; lilswap(data.texture, 6); buf.put(data.edges, sizeof(data.edges)); buf.put((uchar *)data.texture, sizeof(data.texture)); } } static bool packeditinfo(editinfo *e, vector &buf) { if(!e || !e->copy || e->copy->size() > (16<<20)) return false; block3 &b = *e->copy; block3 hdr = b; lilswap(hdr.o.v, 3); lilswap(hdr.s.v, 3); lilswap(&hdr.grid, 1); lilswap(&hdr.orient, 1); buf.put((const uchar *)&hdr, sizeof(hdr)); cube *c = b.c(); loopi(b.size()) packcube(c[i], buf); return true; } static void unpackcube(cube &c, ucharbuf &buf) { int mat = buf.get(); if(mat == 0xFF) { c.children = newcubes(F_EMPTY); loopi(8) unpackcube(c.children[i], buf); } else { c.material = mat; buf.get(c.edges, sizeof(c.edges)); buf.get((uchar *)c.texture, sizeof(c.texture)); lilswap(c.texture, 6); } } static bool unpackeditinfo(editinfo *&e, ucharbuf &buf) { if(!e) e = editinfos.add(new editinfo); if(e->copy) { freeblock(e->copy); e->copy = NULL; } block3 hdr; buf.get((uchar *)&hdr, sizeof(hdr)); lilswap(hdr.o.v, 3); lilswap(hdr.s.v, 3); lilswap(&hdr.grid, 1); lilswap(&hdr.orient, 1); if(hdr.size() > (16<<20)) return false; e->copy = (block3 *)new uchar[sizeof(block3)+hdr.size()*sizeof(cube)]; block3 &b = *e->copy; b = hdr; cube *c = b.c(); memset(c, 0, b.size()*sizeof(cube)); loopi(b.size()) unpackcube(c[i], buf); return true; } static bool compresseditinfo(const uchar *inbuf, int inlen, uchar *&outbuf, int &outlen) { uLongf len = compressBound(inlen); if(len > (1<<20)) return false; outbuf = new uchar[len]; if(compress2((Bytef *)outbuf, &len, (const Bytef *)inbuf, inlen, Z_BEST_COMPRESSION) != Z_OK || len > (1<<16)) { delete[] outbuf; outbuf = NULL; return false; } outlen = len; return true; } static bool uncompresseditinfo(const uchar *inbuf, int inlen, uchar *&outbuf, int &outlen) { if(compressBound(outlen) > (1<<20)) return false; uLongf len = outlen; outbuf = new uchar[len]; if(uncompress((Bytef *)outbuf, &len, (const Bytef *)inbuf, inlen) != Z_OK) { delete[] outbuf; outbuf = NULL; return false; } outlen = len; return true; } bool packeditinfo(editinfo *e, int &inlen, uchar *&outbuf, int &outlen) { vector buf; if(!packeditinfo(e, buf)) return false; inlen = buf.length(); return compresseditinfo(buf.getbuf(), buf.length(), outbuf, outlen); } bool unpackeditinfo(editinfo *&e, const uchar *inbuf, int inlen, int outlen) { if(e && e->copy) { freeblock(e->copy); e->copy = NULL; } uchar *outbuf = NULL; if(!uncompresseditinfo(inbuf, inlen, outbuf, outlen)) return false; ucharbuf buf(outbuf, outlen); if(!unpackeditinfo(e, buf)) { delete[] outbuf; return false; } delete[] outbuf; return true; } void freeeditinfo(editinfo *&e) { if(!e) return; editinfos.removeobj(e); if(e->copy) freeblock(e->copy); delete e; e = NULL; } // guard against subdivision #define protectsel(f) { undoblock *_u = newundocube(sel); f; pasteundo(_u); freeundo(_u); } void mpcopy(editinfo *&e, selinfo &sel, bool local) { if(local) game::edittrigger(sel, EDIT_COPY); if(e==NULL) e = editinfos.add(new editinfo); if(e->copy) freeblock(e->copy); e->copy = NULL; protectsel(e->copy = blockcopy(block3(sel), sel.grid)); changed(sel); } void mppaste(editinfo *&e, selinfo &sel, bool local) { if(e==NULL) return; if(local) game::edittrigger(sel, EDIT_PASTE); if(e->copy) { sel.s = e->copy->s; int o = sel.orient; sel.orient = e->copy->orient; cube *s = e->copy->c(); loopselxyz(if (!isempty(*s) || s->children) pastecube(*s, c); s++); // 'transparent'. old opaque by 'delcube; paste' sel.orient = o; } } void copy() { if(noedit(true)) return; mpcopy(localedit, sel, true); } void pastehilite() { if(!localedit) return; sel.s = localedit->copy->s; reorient(); havesel = true; } void paste() { if(noedit()) return; mppaste(localedit, sel, true); } COMMAND(copy, ""); COMMAND(pastehilite, ""); COMMAND(paste, ""); COMMANDN(undo, editundo, ""); COMMANDN(redo, editredo, ""); static VSlot *editingvslot = NULL; void compacteditvslots() { if(editingvslot && editingvslot->layer) compactvslot(editingvslot->layer); loopv(editinfos) { editinfo *e = editinfos[i]; compactvslots(e->copy->c(), e->copy->size()); } for(undoblock *u = undos.first; u; u = u->next) if(!u->numents) compactvslots(u->block()->c(), u->block()->size()); for(undoblock *u = redos.first; u; u = u->next) if(!u->numents) compactvslots(u->block()->c(), u->block()->size()); } ///////////// height maps //////////////// #define MAXBRUSH 64 #define MAXBRUSHC 63 #define MAXBRUSH2 32 int brush[MAXBRUSH][MAXBRUSH]; VAR(brushx, 0, MAXBRUSH2, MAXBRUSH); VAR(brushy, 0, MAXBRUSH2, MAXBRUSH); bool paintbrush = 0; int brushmaxx = 0, brushminx = MAXBRUSH; int brushmaxy = 0, brushminy = MAXBRUSH; void clearbrush() { memset(brush, 0, sizeof brush); brushmaxx = brushmaxy = 0; brushminx = brushminy = MAXBRUSH; paintbrush = false; } void brushvert(int *x, int *y, int *v) { *x += MAXBRUSH2 - brushx + 1; // +1 for automatic padding *y += MAXBRUSH2 - brushy + 1; if(*x<0 || *y<0 || *x>=MAXBRUSH || *y>=MAXBRUSH) return; brush[*x][*y] = clamp(*v, 0, 8); paintbrush = paintbrush || (brush[*x][*y] > 0); brushmaxx = min(MAXBRUSH-1, max(brushmaxx, *x+1)); brushmaxy = min(MAXBRUSH-1, max(brushmaxy, *y+1)); brushminx = max(0, min(brushminx, *x-1)); brushminy = max(0, min(brushminy, *y-1)); } vector htextures; COMMAND(clearbrush, ""); COMMAND(brushvert, "iii"); ICOMMAND(hmapcancel, "", (), htextures.setsize(0); ); ICOMMAND(hmapselect, "", (), int t = lookupcube(cur.x, cur.y, cur.z).texture[orient]; int i = htextures.find(t); if(i<0) htextures.add(t); else htextures.remove(i); ); inline bool ishtexture(int t) { loopv(htextures) if(t == htextures[i]) return false; return true; } VARP(bypassheightmapcheck, 0, 0, 1); // temp inline bool isheightmap(int o, int d, bool empty, cube *c) { return havesel || (empty && isempty(*c)) || ishtexture(c->texture[o]); } namespace hmap { # define PAINTED 1 # define NOTHMAP 2 # define MAPPED 16 uchar flags[MAXBRUSH][MAXBRUSH]; cube *cmap[MAXBRUSHC][MAXBRUSHC][4]; int mapz[MAXBRUSHC][MAXBRUSHC]; int map [MAXBRUSH][MAXBRUSH]; selinfo changes; bool selecting; int d, dc, dr, dcr, biasup, br, hws, fg; int gx, gy, gz, mx, my, mz, nx, ny, nz, bmx, bmy, bnx, bny; uint fs; selinfo hundo; cube *getcube(ivec t, int f) { t[d] += dcr*f*gridsize; if(t[d] > nz || t[d] < mz) return NULL; cube *c = &lookupcube(t.x, t.y, t.z, gridsize); if(c->children) forcemip(*c, false); discardchildren(*c, true); if(!isheightmap(sel.orient, d, true, c)) return NULL; if (t.x < changes.o.x) changes.o.x = t.x; else if(t.x > changes.s.x) changes.s.x = t.x; if (t.y < changes.o.y) changes.o.y = t.y; else if(t.y > changes.s.y) changes.s.y = t.y; if (t.z < changes.o.z) changes.o.z = t.z; else if(t.z > changes.s.z) changes.s.z = t.z; return c; } uint getface(cube *c, int d) { return 0x0f0f0f0f & ((dc ? c->faces[d] : 0x88888888 - c->faces[d]) >> fs); } void pushside(cube &c, int d, int x, int y, int z) { ivec a; getcubevector(c, d, x, y, z, a); a[R[d]] = 8 - a[R[d]]; setcubevector(c, d, x, y, z, a); } void addpoint(int x, int y, int z, int v) { if(!(flags[x][y] & MAPPED)) map[x][y] = v + (z*8); flags[x][y] |= MAPPED; } void select(int x, int y, int z) { if((NOTHMAP & flags[x][y]) || (PAINTED & flags[x][y])) return; ivec t(d, x+gx, y+gy, dc ? z : hws-z); t.shl(gridpower); // selections may damage; must makeundo before hundo.o = t; hundo.o[D[d]] -= dcr*gridsize*2; makeundoex(hundo); cube **c = cmap[x][y]; loopk(4) c[k] = NULL; c[1] = getcube(t, 0); if(!c[1] || !isempty(*c[1])) { // try up c[2] = c[1]; c[1] = getcube(t, 1); if(!c[1] || isempty(*c[1])) { c[0] = c[1], c[1] = c[2], c[2] = NULL; }else z++, t[d]+=fg; } else // drop down { z--; t[d]-= fg; c[0] = c[1]; c[1] = getcube(t, 0); } if(!c[1] || isempty(*c[1])) { flags[x][y] |= NOTHMAP; return; } flags[x][y] |= PAINTED; mapz [x][y] = z; if(!c[0]) c[0] = getcube(t, 1); if(!c[2]) c[2] = getcube(t, -1); c[3] = getcube(t, -2); c[2] = !c[2] || isempty(*c[2]) ? NULL : c[2]; c[3] = !c[3] || isempty(*c[3]) ? NULL : c[3]; uint face = getface(c[1], d); if(face == 0x08080808 && (!c[0] || !isempty(*c[0]))) { flags[x][y] |= NOTHMAP; return; } if(c[1]->faces[R[d]] == F_SOLID) // was single face += 0x08080808; else // was pair face += c[2] ? getface(c[2], d) : 0x08080808; face += 0x08080808; // c[3] uchar *f = (uchar*)&face; addpoint(x, y, z, f[0]); addpoint(x+1, y, z, f[1]); addpoint(x, y+1, z, f[2]); addpoint(x+1, y+1, z, f[3]); if(selecting) // continue to adjacent cubes { if(x>bmx) select(x-1, y, z); if(xbmy) select(x, y-1, z); if(y, <, 1, 0, -); else pullhmap(worldsize, <, >, 0, 8, +); cube **c = cmap[x][y]; int e[2][2]; int notempty = 0; loopk(4) if(c[k]) { loopi(2) loopj(2) { e[i][j] = min(8, map[x+i][y+j] - (mapz[x][y]+3-k)*8); notempty |= e[i][j] > 0; } if(notempty) { c[k]->texture[sel.orient] = c[1]->texture[sel.orient]; solidfaces(*c[k]); loopi(2) loopj(2) { int f = e[i][j]; if(f<0 || (f==0 && e[1-i][j]==0 && e[i][1-j]==0)) { f=0; pushside(*c[k], d, i, j, 0); pushside(*c[k], d, i, j, 1); } edgeset(cubeedge(*c[k], d, i, j), dc, dc ? f : 8-f); } } else emptyfaces(*c[k]); } if(!changed) return; if(x>mx) ripple(x-1, y, mapz[x][y], true); if(xmy) ripple(x, y-1, mapz[x][y], true); if(ymx && y>my)); // do diagonals because adjacents DIAGONAL_RIPPLE(-1, +1, (x>mx && ymy)); } #define loopbrush(i) for(int x=bmx; x<=bnx+i; x++) for(int y=bmy; y<=bny+i; y++) void paint() { loopbrush(1) map[x][y] -= dr * brush[x][y]; } void smooth() { int sum, div; loopbrush(-2) { sum = 0; div = 9; loopi(3) loopj(3) if(flags[x+i][y+j] & MAPPED) sum += map[x+i][y+j]; else div--; if(div) map[x+1][y+1] = sum / div; } } void rippleandset() { loopbrush(0) ripple(x, y, gz, false); } void run(int dir, int mode) { d = dimension(sel.orient); dc = dimcoord(sel.orient); dcr= dc ? 1 : -1; dr = dir>0 ? 1 : -1; br = dir>0 ? 0x08080808 : 0; // biasup = mode == dir<0; biasup = dir<0; bool paintme = paintbrush; int cx = (sel.corner&1 ? 0 : -1); int cy = (sel.corner&2 ? 0 : -1); hws= (worldsize>>gridpower); gx = (cur[R[d]] >> gridpower) + cx - MAXBRUSH2; gy = (cur[C[d]] >> gridpower) + cy - MAXBRUSH2; gz = (cur[D[d]] >> gridpower); fs = dc ? 4 : 0; fg = dc ? gridsize : -gridsize; mx = max(0, -gx); // ripple range my = max(0, -gy); nx = min(MAXBRUSH-1, hws-gx) - 1; ny = min(MAXBRUSH-1, hws-gy) - 1; if(havesel) { // selection range bmx = mx = max(mx, (sel.o[R[d]]>>gridpower)-gx); bmy = my = max(my, (sel.o[C[d]]>>gridpower)-gy); bnx = nx = min(nx, (sel.s[R[d]]+(sel.o[R[d]]>>gridpower))-gx-1); bny = ny = min(ny, (sel.s[C[d]]+(sel.o[C[d]]>>gridpower))-gy-1); } if(havesel && mode<0) // -ve means smooth selection paintme = false; else { // brush range bmx = max(mx, brushminx); bmy = max(my, brushminy); bnx = min(nx, brushmaxx-1); bny = min(ny, brushmaxy-1); } nz = worldsize-gridsize; mz = 0; hundo.s = ivec(d,1,1,5); hundo.orient = sel.orient; hundo.grid = gridsize; forcenextundo(); changes.grid = gridsize; changes.s = changes.o = cur; memset(map, 0, sizeof map); memset(flags, 0, sizeof flags); selecting = true; select(clamp(MAXBRUSH2-cx, bmx, bnx), clamp(MAXBRUSH2-cy, bmy, bny), dc ? gz : hws - gz); selecting = false; if(paintme) paint(); else smooth(); rippleandset(); // pull up points to cubify, and set changes.s.sub(changes.o).shr(gridpower).add(1); changed(changes); } } void edithmap(int dir, int mode) { if((nompedit && multiplayer()) || !hmapsel || gridsize < 8) return; hmap::run(dir, mode); } ///////////// main cube edit //////////////// int bounded(int n) { return n<0 ? 0 : (n>8 ? 8 : n); } void pushedge(uchar &edge, int dir, int dc) { int ne = bounded(edgeget(edge, dc)+dir); edgeset(edge, dc, ne); int oe = edgeget(edge, 1-dc); if((dir<0 && dc && oe>ne) || (dir>0 && dc==0 && oe0) == dc && h<=0) || ((dir<0) == dc && h>=worldsize)) return; if(dir<0) sel.o[d] += sel.grid * seldir; } if(dc) sel.o[d] += sel.us(d)-sel.grid; sel.s[d] = 1; loopselxyz( if(c.children) solidfaces(c); uchar mat = getmaterial(c); discardchildren(c, true); c.material = mat; if(mode==1) // fill command { if(dir<0) { solidfaces(c); cube &o = blockcube(x, y, 1, sel, -sel.grid); loopi(6) c.texture[i] = o.children ? DEFAULT_GEOM : o.texture[i]; } else emptyfaces(c); } else { uint bak = c.faces[d]; uchar *p = (uchar *)&c.faces[d]; if(mode==2) linkedpush(c, d, sel.corner&1, sel.corner>>1, dc, seldir); // corner command else { loop(mx,2) loop(my,2) // pull/push edges command { if(x==0 && mx==0 && sel.cx) continue; if(y==0 && my==0 && sel.cy) continue; if(x==sel.s[R[d]]-1 && mx==1 && (sel.cx+sel.cxs)&1) continue; if(y==sel.s[C[d]]-1 && my==1 && (sel.cy+sel.cys)&1) continue; if(p[mx+my*2] != ((uchar *)&bak)[mx+my*2]) continue; linkedpush(c, d, mx, my, dc, seldir); } } optiface(p, c); if(invalidcubeguard==1 && !isvalidcube(c)) { uint newbak = c.faces[d]; uchar *m = (uchar *)&bak; uchar *n = (uchar *)&newbak; loopk(4) if(n[k] != m[k]) // tries to find partial edit that is valid { c.faces[d] = bak; c.edges[d*4+k] = n[k]; if(isvalidcube(c)) m[k] = n[k]; } c.faces[d] = bak; } } ); if (mode==1 && dir>0) sel.o[d] += sel.grid * seldir; } void editface(int *dir, int *mode) { if(noedit(moving!=0)) return; if(hmapedit!=1) mpeditface(*dir, *mode, sel, true); else edithmap(*dir, *mode); } VAR(selectionsurf, 0, 0, 1); void pushsel(int *dir) { if(noedit(moving!=0)) return; int d = dimension(orient); int s = dimcoord(orient) ? -*dir : *dir; sel.o[d] += s*sel.grid; if(selectionsurf==1) { player->o[d] += s*sel.grid; player->resetinterp(); } } void mpdelcube(selinfo &sel, bool local) { if(local) game::edittrigger(sel, EDIT_DELCUBE); loopselxyz(discardchildren(c, true); emptyfaces(c)); } void delcube() { if(noedit()) return; mpdelcube(sel, true); } COMMAND(pushsel, "i"); COMMAND(editface, "ii"); COMMAND(delcube, ""); /////////// texture editing ////////////////// int curtexindex = -1, lasttex = 0, lasttexmillis = -1; int texpaneltimer = 0; vector texmru; void tofronttex() // maintain most recently used of the texture lists when applying texture { int c = curtexindex; if(c>=0) { texmru.insert(0, texmru.remove(c)); curtexindex = -1; } } selinfo repsel; int reptex = -1; struct vslotmap { int index; VSlot *vslot; vslotmap() {} vslotmap(int index, VSlot *vslot) : index(index), vslot(vslot) {} }; static vector remappedvslots; VAR(usevdelta, 1, 0, 0); static VSlot *remapvslot(int index, const VSlot &ds) { loopv(remappedvslots) if(remappedvslots[i].index == index) return remappedvslots[i].vslot; VSlot &vs = lookupvslot(index, false); if(vs.index < 0 || vs.index == DEFAULT_SKY) return NULL; VSlot *edit = NULL; if(usevdelta) { VSlot ms; mergevslot(ms, vs, ds); edit = ms.changed ? editvslot(vs, ms) : vs.slot->variants; } else edit = ds.changed ? editvslot(vs, ds) : vs.slot->variants; if(!edit) edit = &vs; remappedvslots.add(vslotmap(vs.index, edit)); return edit; } static void remapvslots(cube &c, const VSlot &ds, int orient, bool &findrep, VSlot *&findedit) { if(c.children) { loopi(8) remapvslots(c.children[i], ds, orient, findrep, findedit); return; } static VSlot ms; if(orient<0) loopi(6) { VSlot *edit = remapvslot(c.texture[i], ds); if(edit) { c.texture[i] = edit->index; if(!findedit) findedit = edit; } } else { int i = visibleorient(c, orient); VSlot *edit = remapvslot(c.texture[i], ds); if(edit) { if(findrep) { if(reptex < 0) reptex = c.texture[i]; else if(reptex != c.texture[i]) findrep = false; } c.texture[i] = edit->index; if(!findedit) findedit = edit; } } } void edittexcube(cube &c, int tex, int orient, bool &findrep) { if(orient<0) loopi(6) c.texture[i] = tex; else { int i = visibleorient(c, orient); if(findrep) { if(reptex < 0) reptex = c.texture[i]; else if(reptex != c.texture[i]) findrep = false; } c.texture[i] = tex; } if(c.children) loopi(8) edittexcube(c.children[i], tex, orient, findrep); } VAR(allfaces, 0, 0, 1); void mpeditvslot(VSlot &ds, int allfaces, selinfo &sel, bool local) { if(local) { if(!(lastsel==sel)) tofronttex(); if(allfaces || !(repsel == sel)) reptex = -1; repsel = sel; } bool findrep = local && !allfaces && reptex < 0; VSlot *findedit = NULL; editingvslot = &ds; loopselxyz(remapvslots(c, ds, allfaces ? -1 : sel.orient, findrep, findedit)); editingvslot = NULL; remappedvslots.setsize(0); if(local && findedit) { lasttex = findedit->index; lasttexmillis = totalmillis; curtexindex = texmru.find(lasttex); if(curtexindex < 0) { curtexindex = texmru.length(); texmru.add(lasttex); } } } void vdelta(char *body) { if(noedit() || (nompedit && multiplayer())) return; usevdelta++; execute(body); usevdelta--; } COMMAND(vdelta, "s"); void vrotate(int *n) { if(noedit() || (nompedit && multiplayer())) return; VSlot ds; ds.changed = 1<=vslots.length()) { if(curtexindex > i) curtexindex--; else if(curtexindex == i) curtexindex = -1; texmru.remove(i); } loopv(vslots) if(texmru.find(i)<0) texmru.add(i); } } void compactmruvslots() { remappedvslots.setsize(0); loopvrev(texmru) { if(vslots.inrange(texmru[i])) { VSlot &vs = *vslots[texmru[i]]; if(vs.index >= 0) { texmru[i] = vs.index; continue; } } if(curtexindex > i) curtexindex--; else if(curtexindex == i) curtexindex = -1; texmru.remove(i); } if(vslots.inrange(lasttex)) { VSlot &vs = *vslots[lasttex]; lasttex = vs.index >= 0 ? vs.index : 0; } else lasttex = 0; reptex = vslots.inrange(reptex) ? vslots[reptex]->index : -1; } void edittex(int i, bool save = true) { lasttex = i; lasttexmillis = totalmillis; if(save) { loopvj(texmru) if(texmru[j]==lasttex) { curtexindex = j; break; } } mpedittex(i, allfaces, sel, true); } void edittex_(int *dir) { if(noedit()) return; filltexlist(); texpaneltimer = 5000; if(!(lastsel==sel)) tofronttex(); curtexindex = clamp(curtexindex<0 ? 0 : curtexindex+*dir, 0, texmru.length()-1); edittex(texmru[curtexindex], false); } void gettex() { if(noedit(true)) return; filltexlist(); int tex = -1; loopxyz(sel, sel.grid, tex = c.texture[sel.orient]); loopv(texmru) if(texmru[i]==tex) { curtexindex = i; tofronttex(); return; } } void getcurtex() { if(noedit(true)) return; filltexlist(); int index = curtexindex < 0 ? 0 : curtexindex; if(!texmru.inrange(index)) return; intret(texmru[index]); } void getseltex() { if(noedit(true)) return; cube &c = lookupcube(sel.o.x, sel.o.y, sel.o.z, -sel.grid); if(c.children || isempty(c)) return; intret(c.texture[sel.orient]); } void gettexname(int *tex, int *subslot) { if(noedit(true) || *tex<0) return; VSlot &vslot = lookupvslot(*tex, false); Slot &slot = *vslot.slot; if(!slot.sts.inrange(*subslot)) return; result(slot.sts[*subslot].name); } ICOMMAND(texmrunum, "", (), filltexlist(); intret(texmru.length()) ); ICOMMAND(texmruresolve, "i", (int *slot), filltexlist(); if(texmru.inrange(*slot)) intret(texmru[*slot]); else intret(*slot); ); ICOMMAND(settex, "i", (int *slot), edittex(*slot)); COMMANDN(edittex, edittex_, "i"); COMMAND(gettex, ""); COMMAND(getcurtex, ""); COMMAND(getseltex, ""); ICOMMAND(getreptex, "", (), { if(!noedit()) intret(vslots.inrange(reptex) ? reptex : -1); }); COMMAND(gettexname, "ii"); void replacetexcube(cube &c, int oldtex, int newtex) { loopi(6) if(c.texture[i] == oldtex) c.texture[i] = newtex; if(c.children) loopi(8) replacetexcube(c.children[i], oldtex, newtex); } void mpreplacetex(int oldtex, int newtex, bool insel, selinfo &sel, bool local) { if(local) game::edittrigger(sel, EDIT_REPLACE, oldtex, newtex, insel ? 1 : 0); if(insel) { loopselxyz(replacetexcube(c, oldtex, newtex)); } else { loopi(8) replacetexcube(worldroot[i], oldtex, newtex); } allchanged(); } void replace(bool insel) { if(noedit()) return; if(reptex < 0) { conoutf(CON_ERROR, "can only replace after a texture edit"); return; } mpreplacetex(reptex, lasttex, insel, sel, true); } ICOMMAND(replace, "", (), replace(false)); ICOMMAND(replacesel, "", (), replace(true)); ////////// Art Culling functions ///////// void cullmodels() { if(nompedit && multiplayer()) return; extern vector mapmodels; loopvrev(mapmodels) { bool found = false; loopvj(entities::getents()) { extentity &e = *entities::getents()[j]; if(e.type == ET_MAPMODEL) { if(e.attr[1] == i) { found = true; break; } } else if(e.type >= ET_GAMESPECIFIC) { if(entities::checkmodelusage(e, i)) { found = true; break; } } } if(found) continue; loopvj(entities::getents()) { extentity &e = *entities::getents()[j]; if(e.type == ET_MAPMODEL) { if(e.attr[1] >= i) e.attr[1] -= 1; } else if(e.type >= ET_GAMESPECIFIC) { int *modelattr = entities::getmodelattr(e); if(!modelattr) continue; if(*modelattr >= i) *modelattr -= 1; } } mapmodels.remove(i); } } COMMAND(cullmodels, ""); extern vector slots; bool recursetextures(cube *parent, int tex) { loopi(8) { if(parent[i].children) { if(recursetextures(parent[i].children, tex)) { return true; } } else if(!isempty(parent[i])) { loopj(6) { if(parent[i].texture[j] == tex) { return true; } if(slots.inrange(parent[i].texture[j])) { VSlot *slot = slots[parent[i].texture[j]]->variants; while(slot) { if(slot->layer == tex) return true; slot = slot->next; } } } } } return false; } void culltextures() { if(nompedit && multiplayer()) return; loopvrev(slots) { if(slots.length() <= 8) return; if(!recursetextures(worldroot, i)) { bool del = true; extern vector texanim; loopvj(texanim) { loopvk(texanim[j]->frames) { if(texanim[j]->frames[k].slot == i) { if(!k) { texanim.remove(j); break; } else del = false; } } } if(!del) continue; loopvj(texanim) { loopvk(texanim[j]->frames) { if(texanim[j]->frames[k].slot > i) texanim[j]->frames[k].slot--; } } loopj(slots.length()-i) { int oldtex = i+j; loopk(8) replacetexcube(worldroot[k], oldtex, oldtex -1); } loopvj(slots) { VSlot *vs = slots[i]->variants; while(vs) { if(vs->layer > i) vs->layer--; else if(vs->layer == i) vs->layer = 0; vs = vs->next; } } extern Slot dummyslot; VSlot *vs = slots[i]->variants; while(vs) { vs->slot = &dummyslot; vs = vs->next; } slots[i]->reset(); delete slots[i]; slots.remove(i); } } allchanged(); } COMMAND(culltextures, ""); void cullart() { if(nompedit && multiplayer()) return; cullmodels(); culltextures(); //cullsound(); } COMMAND(cullart, ""); ////////// flip and rotate /////////////// uint dflip(uint face) { return face==F_EMPTY ? face : 0x88888888 - (((face&0xF0F0F0F0)>>4) | ((face&0x0F0F0F0F)<<4)); } uint cflip(uint face) { return ((face&0xFF00FF00)>>8) | ((face&0x00FF00FF)<<8); } uint rflip(uint face) { return ((face&0xFFFF0000)>>16)| ((face&0x0000FFFF)<<16); } uint mflip(uint face) { return (face&0xFF0000FF) | ((face&0x00FF0000)>>8) | ((face&0x0000FF00)<<8); } void flipcube(cube &c, int d) { swap(c.texture[d*2], c.texture[d*2+1]); c.faces[D[d]] = dflip(c.faces[D[d]]); c.faces[C[d]] = cflip(c.faces[C[d]]); c.faces[R[d]] = rflip(c.faces[R[d]]); if(c.children) { loopi(8) if(i&octadim(d)) swap(c.children[i], c.children[i-octadim(d)]); loopi(8) flipcube(c.children[i], d); } } void rotatequad(cube &a, cube &b, cube &c, cube &d) { cube t = a; a = b; b = c; c = d; d = t; } void rotatecube(cube &c, int d) // rotates cube clockwise. see pics in cvs for help. { c.faces[D[d]] = cflip (mflip(c.faces[D[d]])); c.faces[C[d]] = dflip (mflip(c.faces[C[d]])); c.faces[R[d]] = rflip (mflip(c.faces[R[d]])); swap(c.faces[R[d]], c.faces[C[d]]); swap(c.texture[2*R[d]], c.texture[2*C[d]+1]); swap(c.texture[2*C[d]], c.texture[2*R[d]+1]); swap(c.texture[2*C[d]], c.texture[2*C[d]+1]); if(c.children) { int row = octadim(R[d]); int col = octadim(C[d]); for(int i=0; i<=octadim(d); i+=octadim(d)) rotatequad ( c.children[i+row], c.children[i], c.children[i+col], c.children[i+col+row] ); loopi(8) rotatecube(c.children[i], d); } } void mpflip(selinfo &sel, bool local) { if(local) game::edittrigger(sel, EDIT_FLIP); int zs = sel.s[dimension(sel.orient)]; makeundo(); loopxy(sel) { loop(z,zs) flipcube(selcube(x, y, z), dimension(sel.orient)); loop(z,zs/2) { cube &a = selcube(x, y, z); cube &b = selcube(x, y, zs-z-1); swap(a, b); } } changed(sel); } void flip() { if(noedit()) return; mpflip(sel, true); } void mprotate(int cw, selinfo &sel, bool local) { if(local) game::edittrigger(sel, EDIT_ROTATE, cw); int d = dimension(sel.orient); if(!dimcoord(sel.orient)) cw = -cw; int m = sel.s[C[d]] < sel.s[R[d]] ? C[d] : R[d]; int ss = sel.s[m] = max(sel.s[R[d]], sel.s[C[d]]); makeundo(); loop(z,sel.s[D[d]]) loopi(cw>0 ? 1 : 3) { loopxy(sel) rotatecube(selcube(x,y,z), d); loop(y,ss/2) loop(x,ss-1-y*2) rotatequad ( selcube(ss-1-y, x+y, z), selcube(x+y, y, z), selcube(y, ss-1-x-y, z), selcube(ss-1-x-y, ss-1-y, z) ); } changed(sel); } void rotate(int *cw) { if(noedit()) return; mprotate(*cw, sel, true); } COMMAND(flip, ""); COMMAND(rotate, "i"); void setmat(cube &c, uchar mat, uchar matmask, uchar filtermat, uchar filtermask) { if(c.children) loopi(8) setmat(c.children[i], mat, matmask, filtermat, filtermask); else if((c.material&filtermask) == filtermat) { if(mat!=MAT_AIR) { c.material &= matmask; c.material |= mat; } else c.material = MAT_AIR; } } void mpeditmat(int matid, int filter, selinfo &sel, bool local) { if(local) game::edittrigger(sel, EDIT_MAT, matid, filter); uchar matmask = matid&MATF_VOLUME ? 0 : (matid&MATF_CLIP ? ~MATF_CLIP : ~matid), filtermat = filter < 0 ? 0 : filter, filtermask = filter < 0 ? 0 : (filter&MATF_VOLUME ? MATF_VOLUME : (filter&MATF_CLIP ? MATF_CLIP : filter)); if(isclipped(matid&MATF_VOLUME)) matid |= MAT_CLIP; if(isdeadly(matid&MATF_VOLUME)) matid |= MAT_DEATH; if(matid < 0 && filter >= 0) { matid = 0; matmask = filtermask; if(isclipped(filter&MATF_VOLUME)) matmask &= ~MATF_CLIP; if(isdeadly(filter&MATF_VOLUME)) matmask &= ~MAT_DEATH; } loopselxyz(setmat(c, matid, matmask, filtermat, filtermask)); } void editmat(char *name, char *filtername) { if(noedit()) return; int filter = -1; if(filtername[0]) { filter = findmaterial(filtername); if(filter < 0) { conoutf(CON_ERROR, "unknown material \"%s\"", filtername); return; } } int id = -1; if(name[0] || filter < 0) { id = findmaterial(name); if(id<0) { conoutf(CON_ERROR, "unknown material \"%s\"", name); return; } } mpeditmat(id, filter, sel, true); } COMMAND(editmat, "ss"); #ifndef NEWGUI extern int menudistance, menuautoclose; VARP(texguiwidth, 1, 15, 1000); VARP(texguiheight, 1, 6, 1000); VARP(texguitime, 0, 25, 1000); static int lastthumbnail = 0; static int texhoveridx = 0; VARP(texgui2d, 0, 1, 1); struct texturegui : g3d_callback { bool menuon; vec menupos; int menustart, menutab; texturegui() : menustart(-1) {} void gui(g3d_gui &g, bool firstpass) { int origtab = menutab, numtabs = max((slots.length() + texguiwidth*texguiheight - 1)/(texguiwidth*texguiheight), 1); g.start(menustart, 0.04f, &menutab); loopi(numtabs) { g.tab(!i ? "Textures" : NULL, 0xAAFFAA); if(i+1 != origtab) continue; //don't load textures on non-visible tabs! loop(h, texguiheight) { g.pushlist(); loop(w, texguiwidth) { extern VSlot dummyvslot; int ti = (i*texguiheight+h)*texguiwidth+w; if(tiname); if(ds[60]) //shorten strings, to avoid a jittery interface { ds[60] = '\0'; ds[59] = ds[58] = ds[57] = '.'; } g.text(ds, guitextcolour, "info"); formatstring(ds)("Scale: %.2f\tAlpha %.2f %.2f", vprev.scale, vprev.alphafront, vprev.alphaback); g.text(ds, guitextcolour, "info"); formatstring(ds)("Scroll: %.2f %.2f\toffset %i %i", vprev.scrollS * 1000.0f, vprev.scrollT * 1000.0f, vprev.xoffset, vprev.yoffset); g.text(ds, guitextcolour, "info"); g.poplist(); g.poplist(); } g.end(); } void showtextures(bool on) { if(on != menuon && (menuon = on)) { if(menustart <= lasttexmillis) menutab = 1+clamp(lookupvslot(lasttex, false).slot->index, 0, slots.length()-1)/(texguiwidth*texguiheight); menupos = menuinfrontofplayer(); menustart = starttime(); } } void show() { if(!menuon) return; filltexlist(); extern int usegui2d; if(!editmode || ((!texgui2d || !usegui2d) && camera1->o.dist(menupos) > menuautoclose)) menuon = false; else g3d_addgui(this, menupos, texgui2d ? GUI_2D : 0); } } gui; void g3d_texturemenu() { gui.show(); } void showtexgui(int *n) { if(!editmode) { conoutf(CON_ERROR, "operation only allowed in edit mode"); return; } gui.showtextures(*n==0 ? !gui.menuon : *n==1); } // 0/noargs = toggle, 1 = on, other = off - will autoclose if too far away or exit editmode COMMAND(showtexgui, "i"); #endif void rendertexturepanel(int w, int h) { if((texpaneltimer -= curtime)>0 && editmode) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glScalef(h/1800.0f, h/1800.0f, 1); int y = 50, gap = 10; static Shader *rgbonlyshader = NULL; if(!rgbonlyshader) rgbonlyshader = lookupshaderbyname("rgbonly"); rgbonlyshader->set(); loopi(7) { int s = (i == 3 ? 285 : 220), ti = curtexindex+i-3; if(ti>=0 && tislot->sts.empty() ? notexture : layer->slot->sts[0].t; } float sx = min(1.0f, tex->xs/(float)tex->ys), sy = min(1.0f, tex->ys/(float)tex->xs); int x = w*1800/h-s-50, r = s; float tc[4][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; float xoff = vslot.xoffset, yoff = vslot.yoffset; if(vslot.rotation) { if((vslot.rotation&5) == 1) { swap(xoff, yoff); loopk(4) swap(tc[k][0], tc[k][1]); } if(vslot.rotation >= 2 && vslot.rotation <= 4) { xoff *= -1; loopk(4) tc[k][0] *= -1; } if(vslot.rotation <= 2 || vslot.rotation == 5) { yoff *= -1; loopk(4) tc[k][1] *= -1; } } loopk(4) { tc[k][0] = tc[k][0]/sx - xoff/tex->xs; tc[k][1] = tc[k][1]/sy - yoff/tex->ys; } glBindTexture(GL_TEXTURE_2D, tex->id); loopj(glowtex ? 3 : 2) { if(j < 2) glColor4f(j*vslot.colorscale.x, j*vslot.colorscale.y, j*vslot.colorscale.z, texpaneltimer/1000.0f); else { glBindTexture(GL_TEXTURE_2D, glowtex->id); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glColor4f(vslot.glowcolor.x, vslot.glowcolor.y, vslot.glowcolor.z, texpaneltimer/1000.0f); } glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x, y); glTexCoord2fv(tc[1]); glVertex2f(x+r, y); glTexCoord2fv(tc[3]); glVertex2f(x, y+r); glTexCoord2fv(tc[2]); glVertex2f(x+r, y+r); glEnd(); xtraverts += 4; if(j==1 && layertex) { glColor4f(layer->colorscale.x, layer->colorscale.y, layer->colorscale.z, texpaneltimer/1000.0f); glBindTexture(GL_TEXTURE_2D, layertex->id); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x+r/2, y+r/2); glTexCoord2fv(tc[1]); glVertex2f(x+r, y+r/2); glTexCoord2fv(tc[3]); glVertex2f(x+r/2, y+r); glTexCoord2fv(tc[2]); glVertex2f(x+r, y+r); glEnd(); xtraverts += 4; } if(!j) { r -= 10; x += 5; y += 5; } else if(j == 2) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } y += s+gap; } defaultshader->set(); glPopMatrix(); } } sandboxgamemaker-2.7.1+dfsg/src/engine/skelmodel.h0000664000175000017500000024047311615526106022053 0ustar showardshowardVARP(gpuskel, 0, 1, 1); VARP(matskel, 0, 1, 1); #define BONEMASK_NOT 0x8000 #define BONEMASK_END 0xFFFF #define BONEMASK_BONE 0x7FFF struct skelmodel : animmodel { struct vert { vec pos, norm; float u, v; int blend, interpindex; }; struct vvert { vec pos; float u, v; }; struct vvertn : vvert { vec norm; }; struct vvertw : vvertn { uchar weights[4]; uchar bones[4]; }; struct vvertbump : vvertn { vec tangent; float bitangent; }; struct vvertbumpw : vvertw { vec tangent; float bitangent; }; struct bumpvert { vec tangent; float bitangent; }; struct tri { ushort vert[3]; }; struct blendcombo { int uses, interpindex; float weights[4]; uchar bones[4], interpbones[4]; blendcombo() : uses(1) { } bool operator==(const blendcombo &c) const { loopk(4) if(bones[k] != c.bones[k]) return false; loopk(4) if(weights[k] != c.weights[k]) return false; return true; } int size() const { int i = 1; while(i < 4 && weights[i]) i++; return i; } static bool sortcmp(const blendcombo &x, const blendcombo &y) { loopi(4) { if(x.weights[i]) { if(!y.weights[i]) return true; } else if(y.weights[i]) return false; else break; } return false; } int addweight(int sorted, float weight, int bone) { if(weight <= 1e-3f) return sorted; loopk(sorted) if(weight > weights[k]) { for(int l = min(sorted-1, 2); l >= k; l--) { weights[l+1] = weights[l]; bones[l+1] = bones[l]; } weights[k] = weight; bones[k] = bone; return sorted<4 ? sorted+1 : sorted; } if(sorted>=4) return sorted; weights[sorted] = weight; bones[sorted] = bone; return sorted+1; } void finalize(int sorted) { loopj(4-sorted) { weights[sorted+j] = 0; bones[sorted+j] = 0; } if(sorted <= 0) return; float total = 0; loopj(sorted) total += weights[j]; total = 1.0f/total; loopj(sorted) weights[j] *= total; } void serialize(vvertw &v) { if(interpindex >= 0) { v.weights[0] = 255; loopk(3) v.weights[k+1] = 0; v.bones[0] = (matskel ? 3 : 2)*interpindex; loopk(3) v.bones[k+1] = v.bones[0]; } else { int total = 0; loopk(4) total += (v.weights[k] = uchar(weights[k]*255)); while(total > 255) { loopk(4) if(v.weights[k] > 0 && total > 255) { v.weights[k]--; total--; } } while(total < 255) { loopk(4) if(v.weights[k] < 255 && total < 255) { v.weights[k]++; total++; } } loopk(4) v.bones[k] = (matskel ? 3 : 2)*interpbones[k]; } } }; struct animcacheentry { animstate as[MAXANIMPARTS]; float pitch; int millis; uchar *partmask; ragdolldata *ragdoll; animcacheentry() : ragdoll(NULL) { loopk(MAXANIMPARTS) as[k].cur.fr1 = as[k].prev.fr1 = -1; } bool operator==(const animcacheentry &c) const { loopi(MAXANIMPARTS) if(as[i]!=c.as[i]) return false; return pitch==c.pitch && partmask==c.partmask && ragdoll==c.ragdoll && (!ragdoll || min(millis, c.millis) >= ragdoll->lastmove); } }; struct vbocacheentry : animcacheentry { uchar *vdata; GLuint vbuf; int owner; vbocacheentry() : vdata(NULL), vbuf(0), owner(-1) {} }; struct skelcacheentry : animcacheentry { dualquat *bdata; matrix3x4 *mdata; int version; GLuint ubuf; bool dirty; skelcacheentry() : bdata(NULL), mdata(NULL), version(-1), ubuf(0), dirty(false) {} void nextversion() { version = Shader::uniformlocversion(); dirty = true; } }; struct blendcacheentry : skelcacheentry { int owner; blendcacheentry() : owner(-1) {} }; struct skelmeshgroup; struct skelmesh : mesh { vert *verts; bumpvert *bumpverts; tri *tris; int numverts, numtris, maxweights; int voffset, eoffset, elen; ushort minvert, maxvert; skelmesh() : verts(NULL), bumpverts(NULL), tris(NULL), numverts(0), numtris(0), maxweights(0) { } virtual ~skelmesh() { DELETEA(verts); DELETEA(bumpverts); DELETEA(tris); } int addblendcombo(const blendcombo &c) { maxweights = max(maxweights, c.size()); return ((skelmeshgroup *)group)->addblendcombo(c); } void smoothnorms(float limit = 0, bool areaweight = true) { mesh::smoothnorms(verts, numverts, tris, numtris, limit, areaweight); } void buildnorms(bool areaweight = true) { mesh::buildnorms(verts, numverts, tris, numtris, areaweight); } void calctangents(bool areaweight = true) { if(bumpverts) return; bumpverts = new bumpvert[numverts]; mesh::calctangents(bumpverts, verts, verts, numverts, tris, numtris, areaweight); } void calcbb(int frame, vec &bbmin, vec &bbmax, const matrix3x4 &m) { loopj(numverts) { vec v = m.transform(verts[j].pos); loopi(3) { bbmin[i] = min(bbmin[i], v[i]); bbmax[i] = max(bbmax[i], v[i]); } } } void gentris(int frame, Texture *tex, vector *out, const matrix3x4 &m) { loopj(numtris) { BIH::tri &t = out[noclip ? 1 : 0].add(); t.tex = tex; vert &av = verts[tris[j].vert[0]], &bv = verts[tris[j].vert[1]], &cv = verts[tris[j].vert[2]]; t.a = m.transform(av.pos); t.b = m.transform(bv.pos); t.c = m.transform(cv.pos); t.tc[0] = av.u; t.tc[1] = av.v; t.tc[2] = bv.u; t.tc[3] = bv.v; t.tc[4] = cv.u; t.tc[5] = cv.v; } } static inline bool comparevert(vvert &w, int j, vert &v) { return v.u==w.u && v.v==w.v && v.pos==w.pos; } static inline bool comparevert(vvertn &w, int j, vert &v) { return v.u==w.u && v.v==w.v && v.pos==w.pos && v.norm==w.norm; } inline bool comparevert(vvertbump &w, int j, vert &v) { return v.u==w.u && v.v==w.v && v.pos==w.pos && v.norm==w.norm && (!bumpverts || (bumpverts[j].tangent==w.tangent && bumpverts[j].bitangent==w.bitangent)); } static inline void assignvert(vvert &vv, int j, vert &v, blendcombo &c) { vv.pos = v.pos; vv.u = v.u; vv.v = v.v; } static inline void assignvert(vvertn &vv, int j, vert &v, blendcombo &c) { vv.pos = v.pos; vv.norm = v.norm; vv.u = v.u; vv.v = v.v; } inline void assignvert(vvertbump &vv, int j, vert &v, blendcombo &c) { vv.pos = v.pos; vv.norm = v.norm; vv.u = v.u; vv.v = v.v; if(bumpverts) { vv.tangent = bumpverts[j].tangent; vv.bitangent = bumpverts[j].bitangent; } else { vv.tangent = vec(0, 0, 0); vv.bitangent = 0; } } static inline void assignvert(vvertw &vv, int j, vert &v, blendcombo &c) { vv.pos = v.pos; vv.norm = v.norm; vv.u = v.u; vv.v = v.v; c.serialize(vv); } inline void assignvert(vvertbumpw &vv, int j, vert &v, blendcombo &c) { vv.pos = v.pos; vv.norm = v.norm; vv.u = v.u; vv.v = v.v; if(bumpverts) { vv.tangent = bumpverts[j].tangent; vv.bitangent = bumpverts[j].bitangent; } else { vv.tangent = vec(0, 0, 0); vv.bitangent = 0; } c.serialize(vv); } template int genvbo(vector &idxs, int offset, vector &vverts) { voffset = offset; eoffset = idxs.length(); loopi(numverts) { vert &v = verts[i]; assignvert(vverts.add(), i, v, ((skelmeshgroup *)group)->blendcombos[v.blend]); } loopi(numtris) loopj(3) idxs.add(voffset + tris[i].vert[j]); elen = idxs.length()-eoffset; minvert = voffset; maxvert = voffset + numverts-1; return numverts; } template int genvbo(vector &idxs, int offset, vector &vverts, int *htdata, int htlen) { voffset = offset; eoffset = idxs.length(); minvert = 0xFFFF; loopi(numtris) { tri &t = tris[i]; loopj(3) { int index = t.vert[j]; vert &v = verts[index]; int htidx = hthash(v.pos)&(htlen-1); loopk(htlen) { int &vidx = htdata[(htidx+k)&(htlen-1)]; if(vidx < 0) { vidx = idxs.add(ushort(vverts.length())); assignvert(vverts.add(), index, v, ((skelmeshgroup *)group)->blendcombos[v.blend]); break; } else if(comparevert(vverts[vidx], index, v)) { minvert = min(minvert, idxs.add(ushort(vidx))); break; } } } } elen = idxs.length()-eoffset; minvert = min(minvert, ushort(voffset)); maxvert = max(minvert, ushort(vverts.length()-1)); return vverts.length()-voffset; } int genvbo(vector &idxs, int offset) { loopi(numverts) verts[i].interpindex = ((skelmeshgroup *)group)->remapblend(verts[i].blend); voffset = offset; eoffset = idxs.length(); loopi(numtris) { tri &t = tris[i]; loopj(3) idxs.add(voffset+t.vert[j]); } minvert = voffset; maxvert = voffset + numverts-1; elen = idxs.length()-eoffset; return numverts; } void filltc(uchar *vdata, size_t stride) { vdata = (uchar *)&((vvert *)&vdata[voffset*stride])->u; loopi(numverts) { ((float *)vdata)[0] = verts[i].u; ((float *)vdata)[1] = verts[i].v; vdata += stride; } } void fillbump(uchar *vdata, size_t stride) { if(stride==sizeof(vvertbumpw)) vdata = (uchar *)&((vvertbumpw *)&vdata[voffset*stride])->tangent; else vdata = (uchar *)&((vvertbump *)&vdata[voffset*stride])->tangent; if(bumpverts) loopi(numverts) { ((bumpvert *)vdata)->bitangent = bumpverts[i].bitangent; vdata += stride; } else loopi(numverts) { memset(vdata, 0, sizeof(bumpvert)); vdata += stride; } } template void interpverts(const M * RESTRICT mdata1, const M * RESTRICT mdata2, bool norms, bool tangents, void * RESTRICT vdata, skin &s) { const int blendoffset = ((skelmeshgroup *)group)->skel->numinterpbones; mdata2 -= blendoffset; #define IPLOOP(type, dosetup, dotransform) \ loopi(numverts) \ { \ const vert &src = verts[i]; \ type &dst = ((type * RESTRICT)vdata)[i]; \ dosetup; \ const M &m = (src.interpindex < blendoffset ? mdata1 : mdata2)[src.interpindex]; \ dst.pos = m.transform(src.pos); \ dotransform; \ } if(tangents) { if(bumpverts) { IPLOOP(vvertbump, bumpvert &bsrc = bumpverts[i], { dst.norm = m.transformnormal(src.norm); dst.tangent = m.transformnormal(bsrc.tangent); }); } else { IPLOOP(vvertbump, , dst.norm = m.transformnormal(src.norm)); } } else if(norms) { IPLOOP(vvertn, , dst.norm = m.transformnormal(src.norm)); } else { IPLOOP(vvert, , ); } #undef IPLOOP } void setshader(Shader *s) { skelmeshgroup *g = (skelmeshgroup *)group; if(glaring) { if(!g->skel->usegpuskel) s->setvariant(0, 2); else if(g->skel->usematskel) s->setvariant(min(maxweights, g->vweights), 2); else s->setvariant(min(maxweights, g->vweights)-1, 3); } else if(!g->skel->usegpuskel) s->set(); else if(g->skel->usematskel) s->setvariant(min(maxweights, g->vweights)-1, 0); else s->setvariant(min(maxweights, g->vweights)-1, 1); } void render(const animstate *as, skin &s, vbocacheentry &vc) { if(!(as->cur.anim&ANIM_NOSKIN)) { if(s.multitextured()) { if(!enablemtc || lastmtcbuf!=lastvbuf) { glClientActiveTexture_(GL_TEXTURE1_ARB); if(!enablemtc) glEnableClientState(GL_TEXTURE_COORD_ARRAY); if(lastmtcbuf!=lastvbuf) { vvert *vverts = hasVBO ? 0 : (vvert *)vc.vdata; glTexCoordPointer(2, GL_FLOAT, ((skelmeshgroup *)group)->vertsize, &vverts->u); } glClientActiveTexture_(GL_TEXTURE0_ARB); lastmtcbuf = lastvbuf; enablemtc = true; } } else if(enablemtc) disablemtc(); if(s.tangents()) { if(!enabletangents || lastxbuf!=lastvbuf) { if(!enabletangents) glEnableVertexAttribArray_(1); if(lastxbuf!=lastvbuf) { if(((skelmeshgroup *)group)->vertsize==sizeof(vvertbumpw)) { vvertbumpw *vverts = hasVBO ? 0 : (vvertbumpw *)vc.vdata; glVertexAttribPointer_(1, 4, GL_FLOAT, GL_FALSE, ((skelmeshgroup *)group)->vertsize, &vverts->tangent.x); } else { vvertbump *vverts = hasVBO ? 0 : (vvertbump *)vc.vdata; glVertexAttribPointer_(1, 4, GL_FLOAT, GL_FALSE, ((skelmeshgroup *)group)->vertsize, &vverts->tangent.x); } } lastxbuf = lastvbuf; enabletangents = true; } } else if(enabletangents) disabletangents(); if(renderpath==R_FIXEDFUNCTION && (s.scrollu || s.scrollv)) { glMatrixMode(GL_TEXTURE); glPushMatrix(); glTranslatef(s.scrollu*lastmillis/1000.0f, s.scrollv*lastmillis/1000.0f, 0); if(s.multitextured()) { glActiveTexture_(GL_TEXTURE1_ARB); glPushMatrix(); glTranslatef(s.scrollu*lastmillis/1000.0f, s.scrollv*lastmillis/1000.0f, 0); } } } if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, minvert, maxvert, elen, GL_UNSIGNED_SHORT, &((skelmeshgroup *)group)->edata[eoffset]); else glDrawElements(GL_TRIANGLES, elen, GL_UNSIGNED_SHORT, &((skelmeshgroup *)group)->edata[eoffset]); glde++; xtravertsva += numverts; if(renderpath==R_FIXEDFUNCTION && !(as->cur.anim&ANIM_NOSKIN) && (s.scrollu || s.scrollv)) { if(s.multitextured()) { glPopMatrix(); glActiveTexture_(GL_TEXTURE0_ARB); } glPopMatrix(); glMatrixMode(GL_MODELVIEW); } return; } }; struct tag { char *name; int bone; matrix3x4 matrix; tag() : name(NULL) {} ~tag() { DELETEA(name); } }; struct skelanimspec { char *name; int frame, range; skelanimspec() : name(NULL), frame(0), range(0) {} ~skelanimspec() { DELETEA(name); } }; struct boneinfo { const char *name; int parent, children, next, group, scheduled, interpindex, interpparent, ragdollindex, correctindex; float pitchscale, pitchoffset, pitchmin, pitchmax; dualquat base, invbase; boneinfo() : name(NULL), parent(-1), children(-1), next(-1), group(INT_MAX), scheduled(-1), interpindex(-1), interpparent(-1), ragdollindex(-1), correctindex(-1), pitchscale(0), pitchoffset(0), pitchmin(0), pitchmax(0) {} ~boneinfo() { DELETEA(name); } }; struct antipode { int parent, child; antipode(int parent, int child) : parent(parent), child(child) {} }; struct pitchdep { int bone, parent; dualquat pose; }; struct pitchtarget { int bone, frame, corrects, deps; float pitchmin, pitchmax, deviated; dualquat pose; }; struct pitchcorrect { int bone, target, parent; float pitchmin, pitchmax, pitchscale, pitchangle, pitchtotal; }; struct skeleton { char *name; int shared; vector users; boneinfo *bones; int numbones, numinterpbones, numgpubones, numframes; dualquat *framebones; vector skelanims; vector tags; vector antipodes; ragdollskel *ragdoll; vector pitchdeps; vector pitchtargets; vector pitchcorrects; bool usegpuskel, usematskel; vector skelcache; skeleton() : name(NULL), shared(0), bones(NULL), numbones(0), numinterpbones(0), numgpubones(0), numframes(0), framebones(NULL), ragdoll(NULL), usegpuskel(false), usematskel(false) { } ~skeleton() { DELETEA(name); DELETEA(bones); DELETEA(framebones); DELETEP(ragdoll); loopv(skelcache) { DELETEA(skelcache[i].bdata); DELETEA(skelcache[i].mdata); if(skelcache[i].ubuf) glDeleteBuffers_(1, &skelcache[i].ubuf); } } skelanimspec *findskelanim(const char *name, char sep = '\0') { int len = sep ? strlen(name) : 0; loopv(skelanims) { if(skelanims[i].name) { if(sep) { const char *end = strchr(skelanims[i].name, ':'); if(end && end - skelanims[i].name == len && !memcmp(name, skelanims[i].name, len)) return &skelanims[i]; } if(!strcmp(name, skelanims[i].name)) return &skelanims[i]; } } return NULL; } skelanimspec &addskelanim(const char *name) { skelanimspec &sa = skelanims.add(); sa.name = name ? newstring(name) : NULL; return sa; } int findbone(const char *name) { loopi(numbones) if(bones[i].name && !strcmp(bones[i].name, name)) return i; return -1; } int findtag(const char *name) { loopv(tags) if(!strcmp(tags[i].name, name)) return i; return -1; } bool addtag(const char *name, int bone, const matrix3x4 &matrix) { if(findtag(name) >= 0) return false; tag &t = tags.add(); t.name = newstring(name); t.bone = bone; t.matrix = matrix; return true; } void calcantipodes() { antipodes.shrink(0); vector schedule; loopi(numbones) { if(bones[i].group >= numbones) { bones[i].scheduled = schedule.length(); schedule.add(i); } else bones[i].scheduled = -1; } loopv(schedule) { int bone = schedule[i]; const boneinfo &info = bones[bone]; loopj(numbones) if(abs(bones[j].group) == bone && bones[j].scheduled < 0) { antipodes.add(antipode(info.interpindex, bones[j].interpindex)); bones[j].scheduled = schedule.length(); schedule.add(j); } if(i + 1 == schedule.length()) { int conflict = INT_MAX; loopj(numbones) if(bones[j].group < numbones && bones[j].scheduled < 0) conflict = min(conflict, abs(bones[j].group)); if(conflict < numbones) { bones[conflict].scheduled = schedule.length(); schedule.add(conflict); } } } } void remapbones() { loopi(numbones) { boneinfo &info = bones[i]; info.interpindex = -1; info.ragdollindex = -1; } numgpubones = 0; loopv(users) { skelmeshgroup *group = users[i]; loopvj(group->blendcombos) { blendcombo &c = group->blendcombos[j]; loopk(4) { if(!c.weights[k]) { c.interpbones[k] = k > 0 ? c.interpbones[k-1] : 0; continue; } boneinfo &info = bones[c.bones[k]]; if(info.interpindex < 0) info.interpindex = numgpubones++; c.interpbones[k] = info.interpindex; if(info.group < 0) continue; loopl(4) { if(!c.weights[l]) break; if(l == k) continue; int parent = c.bones[l]; if(info.parent == parent || (info.parent >= 0 && info.parent == bones[parent].parent)) { info.group = -info.parent; break; } if(info.group <= parent) continue; int child = c.bones[k]; while(parent > child) parent = bones[parent].parent; if(parent != child) info.group = c.bones[l]; } } } } numinterpbones = numgpubones; loopv(tags) { boneinfo &info = bones[tags[i].bone]; if(info.interpindex < 0) info.interpindex = numinterpbones++; } if(ragdoll) { loopv(ragdoll->joints) { boneinfo &info = bones[ragdoll->joints[i].bone]; if(info.interpindex < 0) info.interpindex = numinterpbones++; info.ragdollindex = i; } } loopi(numbones) { boneinfo &info = bones[i]; if(info.interpindex < 0) continue; for(int parent = info.parent; parent >= 0 && bones[parent].interpindex < 0; parent = bones[parent].parent) bones[parent].interpindex = numinterpbones++; } loopi(numbones) { boneinfo &info = bones[i]; if(info.interpindex < 0) continue; info.interpparent = info.parent >= 0 ? bones[info.parent].interpindex : -1; } if(ragdoll) { loopi(numbones) { boneinfo &info = bones[i]; if(info.interpindex < 0 || info.ragdollindex >= 0) continue; for(int parent = info.parent; parent >= 0; parent = bones[parent].parent) { if(bones[parent].ragdollindex >= 0) { ragdoll->addreljoint(i, bones[parent].ragdollindex); break; } } } } calcantipodes(); } void addpitchdep(int bone, int frame) { for(; bone >= 0; bone = bones[bone].parent) { int pos = pitchdeps.length(); loopvj(pitchdeps) if(bone <= pitchdeps[j].bone) { if(bone == pitchdeps[j].bone) goto nextbone; pos = j; break; } { pitchdep d; d.bone = bone; d.parent = -1; d.pose = framebones[frame*numbones + bone]; pitchdeps.insert(pos, d); } nextbone:; } } int findpitchdep(int bone) { loopv(pitchdeps) if(bone <= pitchdeps[i].bone) return bone == pitchdeps[i].bone ? i : -1; return -1; } int findpitchcorrect(int bone) { loopv(pitchcorrects) if(bone <= pitchcorrects[i].bone) return bone == pitchcorrects[i].bone ? i : -1; return -1; } void initpitchdeps() { pitchdeps.setsize(0); if(pitchtargets.empty()) return; loopv(pitchtargets) { pitchtarget &t = pitchtargets[i]; t.deps = -1; addpitchdep(t.bone, t.frame); } loopv(pitchdeps) { pitchdep &d = pitchdeps[i]; int parent = bones[d.bone].parent; if(parent >= 0) { int j = findpitchdep(parent); if(j >= 0) { d.parent = j; d.pose.mul(pitchdeps[j].pose, dualquat(d.pose)); } } } loopv(pitchtargets) { pitchtarget &t = pitchtargets[i]; int j = findpitchdep(t.bone); if(j >= 0) { t.deps = j; t.pose = pitchdeps[j].pose; } t.corrects = -1; for(int parent = t.bone; parent >= 0; parent = bones[parent].parent) { t.corrects = findpitchcorrect(parent); if(t.corrects >= 0) break; } } loopv(pitchcorrects) { pitchcorrect &c = pitchcorrects[i]; bones[c.bone].correctindex = i; c.parent = -1; for(int parent = c.bone;;) { parent = bones[parent].parent; if(parent < 0) break; c.parent = findpitchcorrect(parent); if(c.parent >= 0) break; } } } void optimize() { cleanup(); if(ragdoll) ragdoll->setup(); remapbones(); initpitchdeps(); } void expandbonemask(uchar *expansion, int bone, int val) { expansion[bone] = val; bone = bones[bone].children; while(bone>=0) { expandbonemask(expansion, bone, val); bone = bones[bone].next; } } void applybonemask(ushort *mask, uchar *partmask, int partindex) { if(!mask || *mask==BONEMASK_END) return; uchar *expansion = new uchar[numbones]; memset(expansion, *mask&BONEMASK_NOT ? 1 : 0, numbones); while(*mask!=BONEMASK_END) { expandbonemask(expansion, *mask&BONEMASK_BONE, *mask&BONEMASK_NOT ? 0 : 1); mask++; } loopi(numbones) if(expansion[i]) partmask[i] = partindex; delete[] expansion; } void linkchildren() { loopi(numbones) { boneinfo &b = bones[i]; b.children = -1; if(b.parent<0) b.next = -1; else { b.next = bones[b.parent].children; bones[b.parent].children = i; } } } int maxgpuparams() const { switch(renderpath) { case R_GLSLANG: return maxvsuniforms; case R_ASMGLSLANG: case R_ASMSHADER: return maxvpenvparams; default: return 0; } } int availgpubones() const { return (min(maxgpuparams() - reservevpparams, 256) - 10) / (matskel ? 3 : 2); } bool gpuaccelerate() const { return renderpath!=R_FIXEDFUNCTION && numframes && gpuskel && numgpubones<=availgpubones(); } float calcdeviation(const vec &axis, const vec &forward, const dualquat &pose1, const dualquat &pose2) { vec forward1 = pose1.transformnormal(forward).project(axis).normalize(), forward2 = pose2.transformnormal(forward).project(axis).normalize(), daxis = vec().cross(forward1, forward2); float dx = clamp(forward1.dot(forward2), -1.0f, 1.0f), dy = clamp(daxis.magnitude(), -1.0f, 1.0f); if(daxis.dot(axis) < 0) dy = -dy; return atan2f(dy, dx)/RAD; } void calcpitchcorrects(float pitch, const vec &axis, const vec &forward) { loopv(pitchtargets) { pitchtarget &t = pitchtargets[i]; t.deviated = calcdeviation(axis, forward, t.pose, pitchdeps[t.deps].pose); } loopv(pitchcorrects) { pitchcorrect &c = pitchcorrects[i]; c.pitchangle = c.pitchtotal = 0; } loopvj(pitchtargets) { pitchtarget &t = pitchtargets[j]; float tpitch = pitch - t.deviated; for(int parent = t.corrects; parent >= 0; parent = pitchcorrects[parent].parent) tpitch -= pitchcorrects[parent].pitchangle; if(t.pitchmin || t.pitchmax) tpitch = clamp(tpitch, t.pitchmin, t.pitchmax); loopv(pitchcorrects) { pitchcorrect &c = pitchcorrects[i]; if(c.target != j) continue; float total = c.parent >= 0 ? pitchcorrects[c.parent].pitchtotal : 0, avail = tpitch - total, used = tpitch*c.pitchscale; if(c.pitchmin || c.pitchmax) { if(used < 0) used = clamp(c.pitchmin, used, 0.0f); else used = clamp(c.pitchmax, 0.0f, used); } if(used < 0) used = clamp(avail, used, 0.0f); else used = clamp(avail, 0.0f, used); c.pitchangle = used; c.pitchtotal = used + total; } } } #define INTERPBONE(bone) \ const animstate &s = as[partmask[bone]]; \ const framedata &f = partframes[partmask[bone]]; \ dualquat d; \ (d = f.fr1[bone]).mul((1-s.cur.t)*s.interp); \ d.accumulate(f.fr2[bone], s.cur.t*s.interp); \ if(s.interp<1) \ { \ d.accumulate(f.pfr1[bone], (1-s.prev.t)*(1-s.interp)); \ d.accumulate(f.pfr2[bone], s.prev.t*(1-s.interp)); \ } #define INTERPBONES(outbody, rotbody) \ sc.nextversion(); \ struct framedata \ { \ const dualquat *fr1, *fr2, *pfr1, *pfr2; \ } partframes[MAXANIMPARTS]; \ loopi(numanimparts) \ { \ partframes[i].fr1 = &framebones[as[i].cur.fr1*numbones]; \ partframes[i].fr2 = &framebones[as[i].cur.fr2*numbones]; \ if(as[i].interp<1) \ { \ partframes[i].pfr1 = &framebones[as[i].prev.fr1*numbones]; \ partframes[i].pfr2 = &framebones[as[i].prev.fr2*numbones]; \ } \ } \ loopv(pitchdeps) \ { \ pitchdep &p = pitchdeps[i]; \ INTERPBONE(p.bone); \ d.normalize(); \ if(p.parent >= 0) p.pose.mul(pitchdeps[p.parent].pose, d); \ else p.pose = d; \ } \ calcpitchcorrects(pitch, axis, forward); \ loopi(numbones) if(bones[i].interpindex>=0) \ { \ INTERPBONE(i); \ const boneinfo &b = bones[i]; \ outbody; \ float angle; \ if(b.pitchscale) { angle = b.pitchscale*pitch + b.pitchoffset; if(b.pitchmin || b.pitchmax) angle = clamp(angle, b.pitchmin, b.pitchmax); } \ else if(b.correctindex >= 0) angle = pitchcorrects[b.correctindex].pitchangle; \ else continue; \ if(as->cur.anim&ANIM_NOPITCH || (as->interp < 1 && as->prev.anim&ANIM_NOPITCH)) \ angle *= (as->cur.anim&ANIM_NOPITCH ? 0 : as->interp) + (as->interp < 1 && as->prev.anim&ANIM_NOPITCH ? 0 : 1-as->interp); \ rotbody; \ } void interpmatbones(const animstate *as, float pitch, const vec &axis, const vec &forward, int numanimparts, const uchar *partmask, skelcacheentry &sc) { if(!sc.mdata) sc.mdata = new matrix3x4[numinterpbones]; if(lastsdata == sc.mdata) lastsdata = NULL; INTERPBONES( { matrix3x4 m(d); if(b.interpparent<0) sc.mdata[b.interpindex] = m; else sc.mdata[b.interpindex].mul(sc.mdata[b.interpparent], m); }, { sc.mdata[b.interpindex].mulorient(matrix3x3(angle*RAD, axis), b.base); }); } void interpbones(const animstate *as, float pitch, const vec &axis, const vec &forward, int numanimparts, const uchar *partmask, skelcacheentry &sc) { if(!sc.bdata) sc.bdata = new dualquat[numinterpbones]; if(lastsdata == sc.bdata) lastsdata = NULL; INTERPBONES( { d.normalize(); if(b.interpparent<0) sc.bdata[b.interpindex] = d; else sc.bdata[b.interpindex].mul(sc.bdata[b.interpparent], d); }, { sc.bdata[b.interpindex].mulorient(quat(axis, angle*RAD), b.base); }); loopv(antipodes) sc.bdata[antipodes[i].child].fixantipodal(sc.bdata[antipodes[i].parent]); } #define INITRAGDOLL(ptype, pdata, relbody) \ const ptype *pdata = sc.pdata; \ loopv(ragdoll->joints) \ { \ const ragdollskel::joint &j = ragdoll->joints[i]; \ const boneinfo &b = bones[j.bone]; \ const ptype &p = pdata[b.interpindex]; \ loopk(3) if(j.vert[k] >= 0) \ { \ ragdollskel::vert &v = ragdoll->verts[j.vert[k]]; \ ragdolldata::vert &dv = d.verts[j.vert[k]]; \ dv.pos.add(p.transform(v.pos).mul(v.weight)); \ } \ } \ if(ragdoll->animjoints) loopv(ragdoll->joints) \ { \ const ragdollskel::joint &j = ragdoll->joints[i]; \ const boneinfo &b = bones[j.bone]; \ const ptype &p = pdata[b.interpindex]; \ d.calcanimjoint(i, p); \ } \ loopv(ragdoll->verts) \ { \ ragdolldata::vert &dv = d.verts[i]; \ matrixstack[matrixpos].transform(vec(dv.pos).add(p->translate).mul(p->model->scale), dv.pos); \ } \ loopv(ragdoll->reljoints) \ { \ const ragdollskel::reljoint &r = ragdoll->reljoints[i]; \ const ragdollskel::joint &j = ragdoll->joints[r.parent]; \ const boneinfo &br = bones[r.bone], &bj = bones[j.bone]; \ relbody; \ } void initmatragdoll(ragdolldata &d, skelcacheentry &sc, part *p) { INITRAGDOLL(matrix3x4, mdata, { d.reljoints[i].transposemul(mdata[bj.interpindex], mdata[br.interpindex]); }); } void initragdoll(ragdolldata &d, skelcacheentry &sc, part *p) { INITRAGDOLL(dualquat, bdata, { dualquat q = bdata[bj.interpindex]; q.invert().mul(bdata[br.interpindex]); d.reljoints[i] = matrix3x4(q); }); } #define GENRAGDOLLBONES(outbody, relbody) \ sc.nextversion(); \ loopv(ragdoll->joints) \ { \ const ragdollskel::joint &j = ragdoll->joints[i]; \ const boneinfo &b = bones[j.bone]; \ vec pos(0, 0, 0); \ loopk(3) if(j.vert[k]>=0) pos.add(d.verts[j.vert[k]].pos); \ pos.mul(j.weight/p->model->scale).sub(p->translate); \ outbody; \ } \ loopv(ragdoll->reljoints) \ { \ const ragdollskel::reljoint &r = ragdoll->reljoints[i]; \ const ragdollskel::joint &j = ragdoll->joints[r.parent]; \ const boneinfo &br = bones[r.bone], &bj = bones[j.bone]; \ relbody; \ } void genmatragdollbones(ragdolldata &d, skelcacheentry &sc, part *p) { if(!sc.mdata) sc.mdata = new matrix3x4[numinterpbones]; if(lastsdata == sc.mdata) lastsdata = NULL; GENRAGDOLLBONES( { sc.mdata[b.interpindex].transposemul(d.tris[j.tri], pos, d.animjoints ? d.animjoints[i] : j.orient); }, { sc.mdata[br.interpindex].mul(sc.mdata[bj.interpindex], d.reljoints[i]); }); } void genragdollbones(ragdolldata &d, skelcacheentry &sc, part *p) { if(!sc.bdata) sc.bdata = new dualquat[numinterpbones]; if(lastsdata == sc.bdata) lastsdata = NULL; GENRAGDOLLBONES( { matrix3x4 m; m.transposemul(d.tris[j.tri], pos, d.animjoints ? d.animjoints[i] : j.orient); sc.bdata[b.interpindex] = dualquat(m); }, { sc.bdata[br.interpindex].mul(sc.bdata[bj.interpindex], dualquat(d.reljoints[i])); }); loopv(antipodes) sc.bdata[antipodes[i].child].fixantipodal(sc.bdata[antipodes[i].parent]); } void concattagtransform(part *p, int frame, int i, const matrix3x4 &m, matrix3x4 &n) { matrix3x4 t; t.mul(bones[tags[i].bone].base, tags[i].matrix); t.translate(vec(p->translate).mul(p->model->scale)); n.mul(m, t); } void calctags(part *p, skelcacheentry *sc = NULL) { loopv(p->links) { linkedpart &l = p->links[i]; tag &t = tags[l.tag]; matrix3x4 m; m.mul(bones[t.bone].base, t.matrix); if(sc) { int interpindex = bones[t.bone].interpindex; m.mul(usematskel ? sc->mdata[interpindex] : sc->bdata[interpindex], matrix3x4(m)); } l.matrix = m; l.matrix[12] = (l.matrix[12] + p->translate.x) * p->model->scale; l.matrix[13] = (l.matrix[13] + p->translate.y) * p->model->scale; l.matrix[14] = (l.matrix[14] + p->translate.z) * p->model->scale; } } void cleanup(bool full = true) { loopv(skelcache) { skelcacheentry &sc = skelcache[i]; loopj(MAXANIMPARTS) sc.as[j].cur.fr1 = -1; DELETEA(sc.bdata); DELETEA(sc.mdata); if(sc.ubuf) { glDeleteBuffers_(1, &sc.ubuf); sc.ubuf = 0; } } skelcache.setsize(0); lastsdata = lastbdata = NULL; if(full) loopv(users) users[i]->cleanup(); } skelcacheentry &checkskelcache(part *p, const animstate *as, float pitch, const vec &axis, const vec &forward, ragdolldata *rdata) { if(skelcache.empty()) { usegpuskel = gpuaccelerate(); usematskel = matskel!=0; } int numanimparts = ((skelpart *)as->owner)->numanimparts; uchar *partmask = ((skelpart *)as->owner)->partmask; skelcacheentry *sc = NULL; bool match = false; loopv(skelcache) { skelcacheentry &c = skelcache[i]; loopj(numanimparts) if(c.as[j]!=as[j]) goto mismatch; if(c.pitch != pitch || c.partmask != partmask || c.ragdoll != rdata || (rdata && c.millis < rdata->lastmove)) goto mismatch; match = true; sc = &c; break; mismatch: if(c.millis < lastmillis) { sc = &c; break; } } if(!sc) sc = &skelcache.add(); if(!match) { loopi(numanimparts) sc->as[i] = as[i]; sc->pitch = pitch; sc->partmask = partmask; sc->ragdoll = rdata; if(rdata) { if(matskel) genmatragdollbones(*rdata, *sc, p); else genragdollbones(*rdata, *sc, p); } else if(matskel) interpmatbones(as, pitch, axis, forward, numanimparts, partmask, *sc); else interpbones(as, pitch, axis, forward, numanimparts, partmask, *sc); } sc->millis = lastmillis; return *sc; } void setasmbones(skelcacheentry &sc, int count = 0) { if(sc.dirty) sc.dirty = false; else if((count ? lastbdata : lastsdata) == (usematskel ? (void *)sc.mdata : (void *)sc.bdata)) return; int offset = count ? numgpubones : 0; if(!offset) count = numgpubones; if(hasPP) { if(usematskel) glProgramEnvParameters4fv_(GL_VERTEX_PROGRAM_ARB, 10 + 3*offset, 3*count, sc.mdata[offset].a.v); else glProgramEnvParameters4fv_(GL_VERTEX_PROGRAM_ARB, 10 + 2*offset, 2*count, sc.bdata[offset].real.v); } else if(usematskel) loopi(count) { glProgramEnvParameter4fv_(GL_VERTEX_PROGRAM_ARB, 10 + 3*(offset+i), sc.mdata[offset+i].a.v); glProgramEnvParameter4fv_(GL_VERTEX_PROGRAM_ARB, 11 + 3*(offset+i), sc.mdata[offset+i].b.v); glProgramEnvParameter4fv_(GL_VERTEX_PROGRAM_ARB, 12 + 3*(offset+i), sc.mdata[offset+i].c.v); } else loopi(count) { glProgramEnvParameter4fv_(GL_VERTEX_PROGRAM_ARB, 10 + 2*(offset+i), sc.bdata[offset+i].real.v); glProgramEnvParameter4fv_(GL_VERTEX_PROGRAM_ARB, 11 + 2*(offset+i), sc.bdata[offset+i].dual.v); } if(offset) lastbdata = usematskel ? (void *)sc.mdata : (void *)sc.bdata; else lastsdata = usematskel ? (void *)sc.mdata : (void *)sc.bdata; } void bindubo(UniformLoc &u, skelcacheentry &sc, skelcacheentry &bc, int count) { if(hasUBO) { if(!lastsdata && lastbdata == &bc.ubuf && !bc.dirty) return; } else if(u.version == bc.version && u.data == &bc.ubuf) return; if(!bc.ubuf) { glGenBuffers_(1, &bc.ubuf); bc.dirty = true; } if(bc.dirty) { GLenum target = hasUBO ? GL_UNIFORM_BUFFER : GL_UNIFORM_BUFFER_EXT; glBindBuffer_(target, bc.ubuf); glBufferData_(target, u.size, NULL, GL_STREAM_DRAW_ARB); int bsize = usematskel ? sizeof(matrix3x4) : sizeof(dualquat), boffset = numgpubones*bsize; glBufferSubData_(target, u.offset, boffset, usematskel ? (void *)sc.mdata : (void *)sc.bdata); if(count > 0) glBufferSubData_(target, u.offset + boffset, count*bsize, usematskel ? (void *)&bc.mdata[numgpubones] : (void *)&bc.bdata[numgpubones]); glBindBuffer_(target, 0); bc.dirty = false; } if(hasUBO) { glBindBufferBase_(GL_UNIFORM_BUFFER, u.binding, bc.ubuf); lastsdata = NULL; lastbdata = &bc.ubuf; } else { glUniformBuffer_(Shader::lastshader->program, u.loc, bc.ubuf); u.version = bc.version; u.data = &bc.ubuf; } } void setglslbones(UniformLoc &u, skelcacheentry &sc, skelcacheentry &bc, int count) { if(u.version == bc.version && u.data == (usematskel ? (void *)bc.mdata : (void *)bc.bdata)) return; count += numgpubones; if(usematskel) { if(count > numgpubones && bc.dirty) { memcpy(bc.mdata, sc.mdata, numgpubones*sizeof(matrix3x4)); bc.dirty = false; } glUniform4fv_(u.loc, 3*count, bc.mdata[0].a.v); } else { if(count > numgpubones && bc.dirty) { memcpy(bc.bdata, sc.bdata, numgpubones*sizeof(dualquat)); bc.dirty = false; } glUniform4fv_(u.loc, 2*count, bc.bdata[0].real.v); } u.version = bc.version; u.data = usematskel ? (void *)bc.mdata : (void *)bc.bdata; } void setgpubones(skelcacheentry &sc, blendcacheentry *bc, int count) { if(!Shader::lastshader) return; if(Shader::lastshader->type & SHADER_GLSLANG) { if(Shader::lastshader->uniformlocs.length() < 1) return; UniformLoc &u = Shader::lastshader->uniformlocs[0]; if(u.size > 0 && (hasUBO || hasBUE)) bindubo(u, sc, bc ? *bc : sc, count); else setglslbones(u, sc, bc ? *bc : sc, count); } else { setasmbones(sc); if(bc) setasmbones(*bc, count); } } bool shouldcleanup() const { return numframes && (skelcache.empty() || gpuaccelerate()!=usegpuskel || (matskel!=0)!=usematskel); } }; struct skelmeshgroup : meshgroup { skeleton *skel; vector blendcombos; int numblends[4]; static const int MAXBLENDCACHE = 16; blendcacheentry blendcache[MAXBLENDCACHE]; static const int MAXVBOCACHE = 16; vbocacheentry vbocache[MAXVBOCACHE]; ushort *edata; GLuint ebuf; bool vnorms, vtangents; int vlen, vertsize, vblends, vweights; uchar *vdata; skelmeshgroup() : skel(NULL), edata(NULL), ebuf(0), vdata(NULL) { memset(numblends, 0, sizeof(numblends)); } virtual ~skelmeshgroup() { if(skel) { if(skel->shared) skel->users.removeobj(this); else DELETEP(skel); } if(ebuf) glDeleteBuffers_(1, &ebuf); loopi(MAXBLENDCACHE) { DELETEA(blendcache[i].bdata); DELETEA(blendcache[i].mdata); if(blendcache[i].ubuf) glDeleteBuffers_(1, &blendcache[i].ubuf); } loopi(MAXVBOCACHE) { DELETEA(vbocache[i].vdata); if(vbocache[i].vbuf) glDeleteBuffers_(1, &vbocache[i].vbuf); } DELETEA(vdata); } void shareskeleton(char *name) { if(!name) { skel = new skeleton; skel->users.add(this); return; } static hashtable skeletons; if(skeletons.access(name)) skel = skeletons[name]; else { skel = new skeleton; skel->name = newstring(name); skeletons[skel->name] = skel; } skel->users.add(this); skel->shared++; } int findtag(const char *name) { return skel->findtag(name); } int totalframes() const { return max(skel->numframes, 1); } virtual skelanimspec *loadanim(const char *filename) { return NULL; } void genvbo(bool norms, bool tangents, vbocacheentry &vc) { if(hasVBO) { if(!vc.vbuf) glGenBuffers_(1, &vc.vbuf); if(ebuf) return; } else if(edata) { #define ALLOCVDATA(vdata) \ do \ { \ DELETEA(vdata); \ vdata = new uchar[vlen*vertsize]; \ loopv(meshes) \ { \ skelmesh &m = *(skelmesh *)meshes[i]; \ m.filltc(vdata, vertsize); \ if(tangents) m.fillbump(vdata, vertsize); \ } \ } while(0) if(!vc.vdata) ALLOCVDATA(vc.vdata); return; } vector idxs; vnorms = norms; vtangents = tangents; vlen = 0; vblends = 0; if(skel->numframes && !skel->usegpuskel) { vweights = 1; loopv(blendcombos) { blendcombo &c = blendcombos[i]; c.interpindex = c.weights[1] ? skel->numinterpbones + vblends++ : -1; } vertsize = tangents ? sizeof(vvertbump) : (norms ? sizeof(vvertn) : sizeof(vvert)); loopv(meshes) vlen += ((skelmesh *)meshes[i])->genvbo(idxs, vlen); DELETEA(vdata); if(hasVBO) ALLOCVDATA(vdata); else ALLOCVDATA(vc.vdata); } else { if(skel->numframes) { vweights = 4; int availbones = skel->availgpubones() - skel->numgpubones; while(vweights > 1 && availbones >= numblends[vweights-1]) availbones -= numblends[--vweights]; loopv(blendcombos) { blendcombo &c = blendcombos[i]; c.interpindex = c.size() > vweights ? skel->numgpubones + vblends++ : -1; } } else { vweights = 0; loopv(blendcombos) blendcombos[i].interpindex = -1; } if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc.vbuf); #define GENVBO(type, args) \ do \ { \ vertsize = sizeof(type); \ vector vverts; \ loopv(meshes) vlen += ((skelmesh *)meshes[i])->genvbo args; \ if(hasVBO) glBufferData_(GL_ARRAY_BUFFER_ARB, vverts.length()*sizeof(type), vverts.getbuf(), GL_STATIC_DRAW_ARB); \ else \ { \ DELETEA(vc.vdata); \ vc.vdata = new uchar[vverts.length()*sizeof(type)]; \ memcpy(vc.vdata, vverts.getbuf(), vverts.length()*sizeof(type)); \ } \ } while(0) #define GENVBOANIM(type) GENVBO(type, (idxs, vlen, vverts)) #define GENVBOSTAT(type) GENVBO(type, (idxs, vlen, vverts, htdata, htlen)) if(skel->numframes) { if(tangents) GENVBOANIM(vvertbumpw); else GENVBOANIM(vvertw); } else { int numverts = 0, htlen = 128; loopv(meshes) numverts += ((skelmesh *)meshes[i])->numverts; while(htlen < numverts) htlen *= 2; if(numverts*4 > htlen*3) htlen *= 2; int *htdata = new int[htlen]; memset(htdata, -1, htlen*sizeof(int)); if(tangents) GENVBOSTAT(vvertbump); else if(norms) GENVBOSTAT(vvertn); else GENVBOSTAT(vvert); delete[] htdata; } if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); } if(hasVBO) { glGenBuffers_(1, &ebuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, ebuf); glBufferData_(GL_ELEMENT_ARRAY_BUFFER_ARB, idxs.length()*sizeof(ushort), idxs.getbuf(), GL_STATIC_DRAW_ARB); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } else { edata = new ushort[idxs.length()]; memcpy(edata, idxs.getbuf(), idxs.length()*sizeof(ushort)); } #undef GENVBO #undef GENVBOANIM #undef GENVBOSTAT #undef ALLOCVDATA } void bindvbo(const animstate *as, vbocacheentry &vc, skelcacheentry *sc = NULL, blendcacheentry *bc = NULL) { vvertn *vverts = hasVBO ? 0 : (vvertn *)vc.vdata; if(hasVBO && lastebuf!=ebuf) { glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, ebuf); lastebuf = ebuf; } if(lastvbuf != (hasVBO ? (void *)(size_t)vc.vbuf : vc.vdata)) { if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc.vbuf); if(!lastvbuf) glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, vertsize, &vverts->pos); lastvbuf = hasVBO ? (void *)(size_t)vc.vbuf : vc.vdata; } if(as->cur.anim&ANIM_NOSKIN) { if(enabletc) disabletc(); if(enablenormals) disablenormals(); } else { if(vnorms || vtangents) { if(!enablenormals) { glEnableClientState(GL_NORMAL_ARRAY); enablenormals = true; } if(lastnbuf!=lastvbuf) { glNormalPointer(GL_FLOAT, vertsize, &vverts->norm); lastnbuf = lastvbuf; } } else if(enablenormals) disablenormals(); if(!enabletc) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); enabletc = true; } if(lasttcbuf!=lastvbuf) { glTexCoordPointer(2, GL_FLOAT, vertsize, &vverts->u); lasttcbuf = lastnbuf; } } if(!sc || !skel->usegpuskel) { if(enablebones) disablebones(); return; } if(!enablebones) { glEnableVertexAttribArray_(6); glEnableVertexAttribArray_(7); enablebones = true; } if(lastbbuf!=lastvbuf) { glVertexAttribPointer_(6, 4, GL_UNSIGNED_BYTE, GL_TRUE, vertsize, &((vvertw *)vverts)->weights); glVertexAttribPointer_(7, 4, GL_UNSIGNED_BYTE, GL_FALSE, vertsize, &((vvertw *)vverts)->bones); lastbbuf = lastvbuf; } } void concattagtransform(part *p, int frame, int i, const matrix3x4 &m, matrix3x4 &n) { skel->concattagtransform(p, frame, i, m, n); } int addblendcombo(const blendcombo &c) { loopv(blendcombos) if(blendcombos[i]==c) { blendcombos[i].uses += c.uses; return i; } numblends[c.size()-1]++; blendcombo &a = blendcombos.add(c); return a.interpindex = blendcombos.length()-1; } void sortblendcombos() { blendcombos.sort(blendcombo::sortcmp); int *remap = new int[blendcombos.length()]; loopv(blendcombos) remap[blendcombos[i].interpindex] = i; loopv(meshes) { skelmesh *m = (skelmesh *)meshes[i]; loopj(m->numverts) { vert &v = m->verts[j]; v.blend = remap[v.blend]; } } delete[] remap; } int remapblend(int blend) { const blendcombo &c = blendcombos[blend]; return c.weights[1] ? c.interpindex : c.interpbones[0]; } template static inline void blendbones(B &d, const B *bdata, const blendcombo &c) { d = bdata[c.interpbones[0]]; d.mul(c.weights[0]); d.accumulate(bdata[c.interpbones[1]], c.weights[1]); if(c.weights[2]) { d.accumulate(bdata[c.interpbones[2]], c.weights[2]); if(c.weights[3]) d.accumulate(bdata[c.interpbones[3]], c.weights[3]); } } void blendmatbones(const skelcacheentry &sc, blendcacheentry &bc) { bc.nextversion(); if(!bc.mdata) bc.mdata = new matrix3x4[(skel->usegpuskel ? skel->numgpubones : 0) + vblends]; if(lastbdata == bc.mdata) lastbdata = NULL; matrix3x4 *dst = bc.mdata - (skel->usegpuskel ? 0 : skel->numinterpbones); loopv(blendcombos) { const blendcombo &c = blendcombos[i]; if(c.interpindex<0) break; blendbones(dst[c.interpindex], sc.mdata, c); } } void blendbones(const skelcacheentry &sc, blendcacheentry &bc) { bc.nextversion(); if(!bc.bdata) bc.bdata = new dualquat[(skel->usegpuskel ? skel->numgpubones : 0) + vblends]; if(lastbdata == bc.bdata) lastbdata = NULL; dualquat *dst = bc.bdata - (skel->usegpuskel ? 0 : skel->numinterpbones); bool normalize = !skel->usegpuskel || vweights<=1; loopv(blendcombos) { const blendcombo &c = blendcombos[i]; if(c.interpindex<0) break; dualquat &d = dst[c.interpindex]; blendbones(d, sc.bdata, c); if(normalize) d.normalize(); } } void cleanup() { loopi(MAXBLENDCACHE) { blendcacheentry &c = blendcache[i]; DELETEA(c.bdata); DELETEA(c.mdata); if(c.ubuf) { glDeleteBuffers_(1, &c.ubuf); c.ubuf = 0; } c.owner = -1; } loopi(MAXVBOCACHE) { vbocacheentry &c = vbocache[i]; if(c.vbuf) { glDeleteBuffers_(1, &c.vbuf); c.vbuf = 0; } DELETEA(c.vdata); c.owner = -1; } if(hasVBO) { if(ebuf) { glDeleteBuffers_(1, &ebuf); ebuf = 0; } } else DELETEA(vdata); if(skel) skel->cleanup(false); } #define SEARCHCACHE(cachesize, cacheentry, cache, reusecheck) \ loopi(cachesize) \ { \ cacheentry &c = cache[i]; \ if(c.owner==owner) \ { \ if(c==sc) return c; \ else c.owner = -1; \ break; \ } \ } \ loopi(cachesize-1) \ { \ cacheentry &c = cache[i]; \ if(reusecheck c.owner < 0 || c.millis < lastmillis) \ return c; \ } \ return cache[cachesize-1]; vbocacheentry &checkvbocache(skelcacheentry &sc, int owner) { SEARCHCACHE(MAXVBOCACHE, vbocacheentry, vbocache, (hasVBO ? !c.vbuf : !c.vdata) || ); } blendcacheentry &checkblendcache(skelcacheentry &sc, int owner) { SEARCHCACHE(MAXBLENDCACHE, blendcacheentry, blendcache, ) } void render(const animstate *as, float pitch, const vec &axis, const vec &forward, dynent *d, part *p) { bool norms = false, tangents = false; loopv(p->skins) { if(p->skins[i].normals()) norms = true; if(p->skins[i].tangents()) tangents = true; } if(skel->shouldcleanup()) { skel->cleanup(); disablevbo(); } else if(norms!=vnorms || tangents!=vtangents) { cleanup(); disablevbo(); } if(!skel->numframes) { if(!(as->cur.anim&ANIM_NORENDER)) { if(hasVBO ? !vbocache->vbuf : !vbocache->vdata) genvbo(norms, tangents, *vbocache); bindvbo(as, *vbocache); loopv(meshes) { skelmesh *m = (skelmesh *)meshes[i]; p->skins[i].bind(m, as); m->render(as, p->skins[i], *vbocache); } } skel->calctags(p); return; } skelcacheentry &sc = skel->checkskelcache(p, as, pitch, axis, forward, as->cur.anim&ANIM_RAGDOLL || !d || !d->ragdoll || d->ragdoll->skel != skel->ragdoll ? NULL : d->ragdoll); if(!(as->cur.anim&ANIM_NORENDER)) { int owner = &sc-&skel->skelcache[0]; vbocacheentry &vc = skel->usegpuskel ? *vbocache : checkvbocache(sc, owner); vc.millis = lastmillis; if(hasVBO ? !vc.vbuf : !vc.vdata) genvbo(norms, tangents, vc); blendcacheentry *bc = NULL; if(vblends) { bc = &checkblendcache(sc, owner); bc->millis = lastmillis; if(bc->owner!=owner) { bc->owner = owner; *(animcacheentry *)bc = sc; if(skel->usematskel) blendmatbones(sc, *bc); else blendbones(sc, *bc); } } if(!skel->usegpuskel && vc.owner!=owner) { vc.owner = owner; (animcacheentry &)vc = sc; loopv(meshes) { skelmesh &m = *(skelmesh *)meshes[i]; if(skel->usematskel) m.interpverts(sc.mdata, bc ? bc->mdata : NULL, norms, tangents, (hasVBO ? vdata : vc.vdata) + m.voffset*vertsize, p->skins[i]); else m.interpverts(sc.bdata, bc ? bc->bdata : NULL, norms, tangents, (hasVBO ? vdata : vc.vdata) + m.voffset*vertsize, p->skins[i]); } if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc.vbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, vlen*vertsize, vdata, GL_STREAM_DRAW_ARB); } } bindvbo(as, vc, &sc, bc); loopv(meshes) { skelmesh *m = (skelmesh *)meshes[i]; p->skins[i].bind(m, as); if(skel->usegpuskel) skel->setgpubones(sc, bc, vblends); m->render(as, p->skins[i], vc); } } skel->calctags(p, &sc); if(as->cur.anim&ANIM_RAGDOLL && skel->ragdoll && !d->ragdoll) { d->ragdoll = new ragdolldata(skel->ragdoll, p->model->scale); if(matskel) skel->initmatragdoll(*d->ragdoll, sc, p); else skel->initragdoll(*d->ragdoll, sc, p); d->ragdoll->init(d); } } }; struct animpartmask { animpartmask *next; int numbones; uchar bones[1]; }; struct skelpart : part { animpartmask *buildingpartmask; uchar *partmask; skelpart() : buildingpartmask(NULL), partmask(NULL) { } virtual ~skelpart() { DELETEA(buildingpartmask); } uchar *sharepartmask(animpartmask *o) { static animpartmask *partmasks = NULL; animpartmask *p = partmasks; for(; p; p = p->next) if(p->numbones==o->numbones && !memcmp(p->bones, o->bones, p->numbones)) { delete[] (uchar *)o; return p->bones; } o->next = p; partmasks = o; return o->bones; } animpartmask *newpartmask() { animpartmask *p = (animpartmask *)new uchar[sizeof(animpartmask) + ((skelmeshgroup *)meshes)->skel->numbones-1]; p->numbones = ((skelmeshgroup *)meshes)->skel->numbones; memset(p->bones, 0, p->numbones); return p; } void initanimparts() { DELETEA(buildingpartmask); buildingpartmask = newpartmask(); } bool addanimpart(ushort *bonemask) { if(!buildingpartmask || numanimparts>=MAXANIMPARTS) return false; ((skelmeshgroup *)meshes)->skel->applybonemask(bonemask, buildingpartmask->bones, numanimparts); numanimparts++; return true; } void endanimparts() { if(buildingpartmask) { partmask = sharepartmask(buildingpartmask); buildingpartmask = NULL; } ((skelmeshgroup *)meshes)->skel->optimize(); } }; skelmodel(const char *name) : animmodel(name) { } int linktype(animmodel *m) const { return type()==m->type() && ((skelmeshgroup *)parts[0]->meshes)->skel == ((skelmeshgroup *)m->parts[0]->meshes)->skel ? LINK_REUSE : LINK_TAG; } bool skeletal() const { return true; } }; struct skeladjustment { float yaw, pitch, roll; vec translate; skeladjustment(float yaw, float pitch, float roll, const vec &translate) : yaw(yaw), pitch(pitch), roll(roll), translate(translate) {} void adjust(dualquat &dq) { if(yaw) dq.mulorient(quat(vec(0, 0, 1), yaw*RAD)); if(pitch) dq.mulorient(quat(vec(0, -1, 0), pitch*RAD)); if(roll) dq.mulorient(quat(vec(-1, 0, 0), roll*RAD)); if(!translate.iszero()) dq.translate(translate); } }; template struct skelloader : modelloader { static vector adjustments; }; template vector skelloader::adjustments; template struct skelcommands : modelcommands { typedef struct MDL::skeleton skeleton; typedef struct MDL::skelmeshgroup meshgroup; typedef struct MDL::skelpart part; typedef struct MDL::skin skin; typedef struct MDL::boneinfo boneinfo; typedef struct MDL::skelanimspec animspec; typedef struct MDL::pitchdep pitchdep; typedef struct MDL::pitchtarget pitchtarget; typedef struct MDL::pitchcorrect pitchcorrect; static void loadpart(char *meshfile, char *skelname, float *smooth) { if(!MDL::loading) { conoutf("not loading an %s", MDL::formatname()); return; } defformatstring(filename)("%s/%s", MDL::dir, meshfile); part &mdl = *new part; MDL::loading->parts.add(&mdl); mdl.model = MDL::loading; mdl.index = MDL::loading->parts.length()-1; mdl.pitchscale = mdl.pitchoffset = mdl.pitchmin = mdl.pitchmax = 0; MDL::adjustments.setsize(0); mdl.meshes = MDL::loading->sharemeshes(path(filename), skelname[0] ? skelname : NULL, double(*smooth > 0 ? cos(clamp(*smooth, 0.0f, 180.0f)*RAD) : 2)); if(!mdl.meshes) conoutf("could not load %s", filename); else { mdl.initanimparts(); mdl.initskins(); } } static void settag(char *name, char *tagname, float *tx, float *ty, float *tz, float *rx, float *ry, float *rz) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } part &mdl = *(part *)MDL::loading->parts.last(); int i = mdl.meshes ? ((meshgroup *)mdl.meshes)->skel->findbone(name) : -1; if(i >= 0) { float cx = *rx ? cosf(*rx/2*RAD) : 1, sx = *rx ? sinf(*rx/2*RAD) : 0, cy = *ry ? cosf(*ry/2*RAD) : 1, sy = *ry ? sinf(*ry/2*RAD) : 0, cz = *rz ? cosf(*rz/2*RAD) : 1, sz = *rz ? sinf(*rz/2*RAD) : 0; matrix3x4 m(matrix3x3(quat(sx*cy*cz - cx*sy*sz, cx*sy*cz + sx*cy*sz, cx*cy*sz - sx*sy*cz, cx*cy*cz + sx*sy*sz)), vec(*tx, *ty, *tz)); ((meshgroup *)mdl.meshes)->skel->addtag(tagname, i, m); return; } conoutf("could not find bone %s for tag %s", name, tagname); } static void setpitch(char *name, float *pitchscale, float *pitchoffset, float *pitchmin, float *pitchmax) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } part &mdl = *(part *)MDL::loading->parts.last(); if(name[0]) { int i = mdl.meshes ? ((meshgroup *)mdl.meshes)->skel->findbone(name) : -1; if(i>=0) { boneinfo &b = ((meshgroup *)mdl.meshes)->skel->bones[i]; b.pitchscale = *pitchscale; b.pitchoffset = *pitchoffset; if(*pitchmin || *pitchmax) { b.pitchmin = *pitchmin; b.pitchmax = *pitchmax; } else { b.pitchmin = -360*fabs(b.pitchscale) + b.pitchoffset; b.pitchmax = 360*fabs(b.pitchscale) + b.pitchoffset; } return; } conoutf("could not find bone %s to pitch", name); return; } mdl.pitchscale = *pitchscale; mdl.pitchoffset = *pitchoffset; if(*pitchmin || *pitchmax) { mdl.pitchmin = *pitchmin; mdl.pitchmax = *pitchmax; } else { mdl.pitchmin = -360*fabs(mdl.pitchscale) + mdl.pitchoffset; mdl.pitchmax = 360*fabs(mdl.pitchscale) + mdl.pitchoffset; } } static void setpitchtarget(char *name, char *animfile, int *frameoffset, float *pitchmin, float *pitchmax) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("\frnot loading an %s", MDL::formatname()); return; } part &mdl = *(part *)MDL::loading->parts.last(); if(!mdl.meshes) return; defformatstring(filename)("%s/%s", MDL::dir, animfile); animspec *sa = ((meshgroup *)mdl.meshes)->loadanim(path(filename)); if(!sa) { conoutf("\frcould not load %s anim file %s", MDL::formatname(), filename); return; } skeleton *skel = ((meshgroup *)mdl.meshes)->skel; int bone = skel ? skel->findbone(name) : -1; if(bone < 0) { conoutf("\frcould not find bone %s to pitch target", name); return; } loopv(skel->pitchtargets) if(skel->pitchtargets[i].bone == bone) return; pitchtarget &t = skel->pitchtargets.add(); t.bone = bone; t.frame = sa->frame + clamp(*frameoffset, 0, sa->range-1); t.pitchmin = *pitchmin; t.pitchmax = *pitchmax; } static void setpitchcorrect(char *name, char *targetname, float *scale, float *pitchmin, float *pitchmax) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("\frnot loading an %s", MDL::formatname()); return; } part &mdl = *(part *)MDL::loading->parts.last(); if(!mdl.meshes) return; skeleton *skel = ((meshgroup *)mdl.meshes)->skel; int bone = skel ? skel->findbone(name) : -1; if(bone < 0) { conoutf("\frcould not find bone %s to pitch correct", name); return; } if(skel->findpitchcorrect(bone) >= 0) return; int targetbone = skel->findbone(targetname), target = -1; if(targetbone >= 0) loopv(skel->pitchtargets) if(skel->pitchtargets[i].bone == targetbone) { target = i; break; } if(target < 0) { conoutf("\frcould not find pitch target %s to pitch correct %s", targetname, name); return; } pitchcorrect c; c.bone = bone; c.target = target; c.pitchmin = *pitchmin; c.pitchmax = *pitchmax; c.pitchscale = *scale; int pos = skel->pitchcorrects.length(); loopv(skel->pitchcorrects) if(bone <= skel->pitchcorrects[i].bone) { pos = i; break; break; } skel->pitchcorrects.insert(pos, c); } static void setanim(char *anim, char *animfile, float *speed, int *priority, int *startoffset, int *endoffset) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } vector anims; findanims(anim, anims); if(anims.empty()) conoutf("could not find animation %s", anim); else { part *p = (part *)MDL::loading->parts.last(); if(!p->meshes) return; defformatstring(filename)("%s/%s", MDL::dir, animfile); animspec *sa = ((meshgroup *)p->meshes)->loadanim(path(filename)); if(!sa) conoutf("could not load %s anim file %s", MDL::formatname(), filename); else loopv(anims) { int start = sa->frame, end = sa->range; if(*startoffset > 0) start += min(*startoffset, end-1); else if(*startoffset < 0) start += max(end + *startoffset, 0); end -= start - sa->frame; if(*endoffset > 0) end = min(end, *endoffset); else if(*endoffset < 0) end = max(end + *endoffset, 1); MDL::loading->parts.last()->setanim(p->numanimparts-1, anims[i], start, end, *speed, *priority); } } } static void setanimpart(char *maskstr) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } part *p = (part *)MDL::loading->parts.last(); vector bonestrs; explodelist(maskstr, bonestrs); vector bonemask; loopv(bonestrs) { char *bonestr = bonestrs[i]; int bone = p->meshes ? ((meshgroup *)p->meshes)->skel->findbone(bonestr[0]=='!' ? bonestr+1 : bonestr) : -1; if(bone<0) { conoutf("could not find bone %s for anim part mask [%s]", bonestr, maskstr); bonestrs.deletearrays(); return; } bonemask.add(bone | (bonestr[0]=='!' ? BONEMASK_NOT : 0)); } bonestrs.deletearrays(); bonemask.sort(); if(bonemask.length()) bonemask.add(BONEMASK_END); if(!p->addanimpart(bonemask.getbuf())) conoutf("too many animation parts"); } static void setadjust(char *name, float *yaw, float *pitch, float *roll, float *tx, float *ty, float *tz) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } part &mdl = *(part *)MDL::loading->parts.last(); if(!name[0]) return; int i = mdl.meshes ? ((meshgroup *)mdl.meshes)->skel->findbone(name) : -1; if(i < 0) { conoutf("could not find bone %s to adjust", name); return; } while(!MDL::adjustments.inrange(i)) MDL::adjustments.add(skeladjustment(0, 0, 0, vec(0, 0, 0))); MDL::adjustments[i] = skeladjustment(*yaw, *pitch, *roll, vec(*tx/4, *ty/4, *tz/4)); } skelcommands() { if(MDL::multiparted()) modelcommand(loadpart, "load", "ssf"); modelcommand(settag, "tag", "ssffffff"); modelcommand(setpitch, "pitch", "sffff"); modelcommand(setpitchtarget, "pitchtarget", "ssiff"); modelcommand(setpitchcorrect, "pitchcorrect", "ssfff"); if(MDL::animated()) { modelcommand(setanim, "anim", "ssfiii"); modelcommand(setanimpart, "animpart", "s"); modelcommand(setadjust, "adjust", "sffffff"); } } }; sandboxgamemaker-2.7.1+dfsg/src/engine/mpr.h0000664000175000017500000005021211544613352020661 0ustar showardshoward// This code is based off the Minkowski Portal Refinement algorithm by Gary Snethen in XenoCollide & Game Programming Gems 7. namespace mpr { struct CubePlanes { const clipplanes &p; CubePlanes(const clipplanes &p) : p(p) {} vec center() const { return p.o; } vec supportpoint(const vec &n) const { int besti = 7; float bestd = n.dot(p.v[7]); loopi(7) { float d = n.dot(p.v[i]); if(d > bestd) { besti = i; bestd = d; } } return p.v[besti]; } }; struct SolidCube { vec o; int size; SolidCube(float x, float y, float z, int size) : o(x, y, z), size(size) {} SolidCube(const vec &o, int size) : o(o), size(size) {} SolidCube(const ivec &o, int size) : o(o.tovec()), size(size) {} vec center() const { return vec(o).add(size/2); } vec supportpoint(const vec &n) const { vec p(o); if(n.x > 0) p.x += size; if(n.y > 0) p.y += size; if(n.z > 0) p.z += size; return p; } }; struct EntAABB { physent *ent; EntAABB(physent *ent) : ent(ent) {} vec center() const { vec o(ent->o); o.z += (ent->aboveeye - ent->eyeheight)/2; return o; } vec contactface(const vec &n, const vec &dir) const { vec an(n.x*dir.x < 0 ? fabs(n.x)/ent->xradius : 0, n.y*dir.y < 0 ? fabs(n.y)/ent->yradius : 0, n.z*dir.z < 0 ? fabs(n.z)*2/(ent->aboveeye + ent->eyeheight) : 0), fn(0, 0, 0); if(an.x > an.y) { if(an.x > an.z) fn.x = n.x > 0 ? 1 : -1; else if(an.z > 0) fn.z = n.z > 0 ? 1 : -1; } else if(an.y > an.z) fn.y = n.y > 0 ? 1 : -1; else if(an.z > 0) fn.z = n.z > 0 ? 1 : -1; return fn; } vec supportpoint(const vec &n) const { vec p(ent->o); if(n.x > 0) p.x += ent->xradius; else p.x -= ent->xradius; if(n.y > 0) p.y += ent->yradius; else p.y -= ent->yradius; if(n.z > 0) p.z += ent->aboveeye; else p.z -= ent->eyeheight; return p; } }; struct EntOBB { physent *ent; quat orient; float zmargin; EntOBB(physent *ent, float zmargin = 0) : ent(ent), orient(vec(0, 0, 1), ent->yaw*RAD), zmargin(zmargin) {} vec center() const { vec o(ent->o); o.z += (ent->aboveeye - ent->eyeheight - zmargin)/2; return o; } vec contactface(const vec &wn, const vec &wdir) const { vec n = orient.invertedrotate(wn).div(vec(ent->xradius, ent->yradius, (ent->aboveeye + ent->eyeheight + zmargin)/2)), dir = orient.invertedrotate(wdir), an(fabs(n.x), fabs(n.y), dir.z ? fabs(n.z) : 0), fn(0, 0, 0); if(an.x > an.y) { if(an.x > an.z) fn.x = n.x*dir.x < 0 ? (n.x > 0 ? 1 : -1) : 0; else if(an.z > 0) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; } else if(an.y > an.z) fn.y = n.y*dir.y < 0 ? (n.y > 0 ? 1 : -1) : 0; else if(an.z > 0) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; return orient.rotate(fn); } vec supportpoint(const vec &n) const { vec ln = orient.invertedrotate(n), p(0, 0, 0); if(ln.x > 0) p.x += ent->xradius; else p.x -= ent->xradius; if(ln.y > 0) p.y += ent->yradius; else p.y -= ent->yradius; if(ln.z > 0) p.z += ent->aboveeye; else p.z -= ent->eyeheight + zmargin; return orient.rotate(p).add(ent->o); } }; struct EntCylinder { physent *ent; float zmargin; EntCylinder(physent *ent, float zmargin = 0) : ent(ent), zmargin(zmargin) {} vec center() const { vec o(ent->o); o.z += (ent->aboveeye - ent->eyeheight - zmargin)/2; return o; } vec contactface(const vec &n, const vec &dir) const { float dxy = n.dot2(n)/(ent->radius*ent->radius), dz = n.z*n.z*4/(ent->aboveeye + ent->eyeheight + zmargin); vec fn(0, 0, 0); if(dz > dxy && dir.z) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; else if(n.dot2(dir) < 0) { fn.x = n.x; fn.y = n.y; fn.normalize(); } return fn; } vec supportpoint(const vec &n) const { vec p(ent->o); if(n.z > 0) p.z += ent->aboveeye; else p.z -= ent->eyeheight + zmargin; if(n.x || n.y) { float r = ent->radius / n.magnitude2(); p.x += n.x*r; p.y += n.y*r; } return p; } }; struct EntCapsule { physent *ent; EntCapsule(physent *ent) : ent(ent) {} vec center() const { vec o(ent->o); o.z += (ent->aboveeye - ent->eyeheight)/2; return o; } vec supportpoint(const vec &n) const { vec p(ent->o); if(n.z > 0) p.z += ent->aboveeye - ent->radius; else p.z -= ent->eyeheight - ent->radius; p.add(vec(n).mul(ent->radius / n.magnitude())); return p; } }; struct EntEllipsoid { physent *ent; EntEllipsoid(physent *ent) : ent(ent) {} vec center() const { vec o(ent->o); o.z += (ent->aboveeye - ent->eyeheight)/2; return o; } vec supportpoint(const vec &dir) const { vec p(ent->o), n = vec(dir).normalize(); p.x += ent->radius*n.x; p.y += ent->radius*n.y; p.z += (ent->aboveeye + ent->eyeheight)/2*(1 + n.z) - ent->eyeheight; return p; } }; struct ModelOBB { vec o, radius; quat orient; ModelOBB(const vec &ent, const vec ¢er, const vec &radius, float yaw) : o(ent), radius(radius), orient(vec(0, 0, 1), yaw*RAD) { o.add(orient.rotate(center)); } vec center() const { return o; } vec contactface(const vec &wn, const vec &wdir) const { vec n = orient.invertedrotate(wn).div(radius), dir = orient.invertedrotate(wdir), an(fabs(n.x), fabs(n.y), dir.z ? fabs(n.z) : 0), fn(0, 0, 0); if(an.x > an.y) { if(an.x > an.z) fn.x = n.x*dir.x < 0 ? (n.x > 0 ? 1 : -1) : 0; else if(an.z > 0) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; } else if(an.y > an.z) fn.y = n.y*dir.y < 0 ? (n.y > 0 ? 1 : -1) : 0; else if(an.z > 0) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; return orient.rotate(fn); } vec supportpoint(const vec &n) const { vec ln = orient.invertedrotate(n), p(0, 0, 0); if(ln.x > 0) p.x += radius.x; else p.x -= radius.x; if(ln.y > 0) p.y += radius.y; else p.y -= radius.y; if(ln.z > 0) p.z += radius.z; else p.z -= radius.z; return orient.rotate(p).add(o); } }; struct ModelEllipse { vec o, radius; quat orient; ModelEllipse(const vec &ent, const vec ¢er, const vec &radius, float yaw) : o(ent), radius(radius), orient(vec(0, 0, 1), yaw*RAD) { o.add(orient.rotate(center)); } vec center() const { return o; } vec contactface(const vec &wn, const vec &wdir) const { vec n = orient.invertedrotate(wn).div(radius), dir = orient.invertedrotate(wdir); float dxy = n.dot2(n), dz = n.z*n.z; vec fn(0, 0, 0); if(dz > dxy && dir.z) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; else if(n.dot2(dir) < 0) { fn.x = n.x*radius.x; fn.y = n.y*radius.y; fn.normalize(); } return orient.rotate(fn); } vec supportpoint(const vec &n) const { vec ln = orient.invertedrotate(n), p(0, 0, 0); if(ln.z > 0) p.z += radius.z; else p.z -= radius.z; if(ln.x || ln.y) { float r = n.magnitude2(); p.x += ln.x*radius.x/r; p.y += ln.y*radius.y/r; } return orient.rotate(p).add(o); } }; const float boundarytolerance = 1e-3f; template bool collide(const T &p1, const U &p2) { // v0 = center of Minkowski difference vec v0 = p2.center().sub(p1.center()); if(v0.iszero()) return true; // v0 and origin overlap ==> hit // v1 = support in direction of origin vec n = vec(v0).neg(); vec v1 = p2.supportpoint(n).sub(p1.supportpoint(vec(n).neg())); if(v1.dot(n) <= 0) return false; // origin outside v1 support plane ==> miss // v2 = support perpendicular to plane containing origin, v0 and v1 n.cross(v1, v0); if(n.iszero()) return true; // v0, v1 and origin colinear (and origin inside v1 support plane) == > hit vec v2 = p2.supportpoint(n).sub(p1.supportpoint(vec(n).neg())); if(v2.dot(n) <= 0) return false; // origin outside v2 support plane ==> miss // v3 = support perpendicular to plane containing v0, v1 and v2 n.cross(v0, v1, v2); // If the origin is on the - side of the plane, reverse the direction of the plane if(n.dot(v0) > 0) { swap(v1, v2); n.neg(); } /// // Phase One: Find a valid portal loopi(100) { // Obtain the next support point vec v3 = p2.supportpoint(n).sub(p1.supportpoint(vec(n).neg())); if(v3.dot(n) <= 0) return false; // origin outside v3 support plane ==> miss // If origin is outside (v1,v0,v3), then portal is invalid -- eliminate v2 and find new support outside face vec v3xv0; v3xv0.cross(v3, v0); if(v1.dot(v3xv0) < 0) { v2 = v3; n.cross(v0, v1, v3); continue; } // If origin is outside (v3,v0,v2), then portal is invalid -- eliminate v1 and find new support outside face if(v2.dot(v3xv0) > 0) { v1 = v3; n.cross(v0, v3, v2); continue; } /// // Phase Two: Refine the portal for(int j = 0;; j++) { // Compute outward facing normal of the portal n.cross(v1, v2, v3); // If the origin is inside the portal, we have a hit if(n.dot(v1) >= 0) return true; n.normalize(); // Find the support point in the direction of the portal's normal vec v4 = p2.supportpoint(n).sub(p1.supportpoint(vec(n).neg())); // If the origin is outside the support plane or the boundary is thin enough, we have a miss if(v4.dot(n) <= 0 || vec(v4).sub(v3).dot(n) <= boundarytolerance || j > 100) return false; // Test origin against the three planes that separate the new portal candidates: (v1,v4,v0) (v2,v4,v0) (v3,v4,v0) // Note: We're taking advantage of the triple product identities here as an optimization // (v1 % v4) * v0 == v1 * (v4 % v0) > 0 if origin inside (v1, v4, v0) // (v2 % v4) * v0 == v2 * (v4 % v0) > 0 if origin inside (v2, v4, v0) // (v3 % v4) * v0 == v3 * (v4 % v0) > 0 if origin inside (v3, v4, v0) vec v4xv0; v4xv0.cross(v4, v0); if(v1.dot(v4xv0) > 0) { if(v2.dot(v4xv0) > 0) v1 = v4; // Inside v1 & inside v2 ==> eliminate v1 else v3 = v4; // Inside v1 & outside v2 ==> eliminate v3 } else { if(v3.dot(v4xv0) > 0) v2 = v4; // Outside v1 & inside v3 ==> eliminate v2 else v1 = v4; // Outside v1 & outside v3 ==> eliminate v1 } } } return false; } template bool collide(const T &p1, const U &p2, vec *contactnormal, vec *contactpoint1, vec *contactpoint2) { // v0 = center of Minkowski sum vec v01 = p1.center(); vec v02 = p2.center(); vec v0 = vec(v02).sub(v01); // Avoid case where centers overlap -- any direction is fine in this case if(v0.iszero()) v0 = vec(0, 0, 1e-5f); // v1 = support in direction of origin vec n = vec(v0).neg(); vec v11 = p1.supportpoint(vec(n).neg()); vec v12 = p2.supportpoint(n); vec v1 = vec(v12).sub(v11); if(v1.dot(n) <= 0) { if(contactnormal) *contactnormal = n; return false; } // v2 - support perpendicular to v1,v0 n.cross(v1, v0); if(n.iszero()) { n = vec(v1).sub(v0); n.normalize(); if(contactnormal) *contactnormal = n; if(contactpoint1) *contactpoint1 = v11; if(contactpoint2) *contactpoint2 = v12; return true; } vec v21 = p1.supportpoint(vec(n).neg()); vec v22 = p2.supportpoint(n); vec v2 = vec(v22).sub(v21); if(v2.dot(n) <= 0) { if(contactnormal) *contactnormal = n; return false; } // Determine whether origin is on + or - side of plane (v1,v0,v2) n.cross(v0, v1, v2); ASSERT( !n.iszero() ); // If the origin is on the - side of the plane, reverse the direction of the plane if(n.dot(v0) > 0) { swap(v1, v2); swap(v11, v21); swap(v12, v22); n.neg(); } /// // Phase One: Identify a portal loopi(100) { // Obtain the support point in a direction perpendicular to the existing plane // Note: This point is guaranteed to lie off the plane vec v31 = p1.supportpoint(vec(n).neg()); vec v32 = p2.supportpoint(n); vec v3 = vec(v32).sub(v31); if(v3.dot(n) <= 0) { if(contactnormal) *contactnormal = n; return false; } // If origin is outside (v1,v0,v3), then eliminate v2 and loop vec v3xv0; v3xv0.cross(v3, v0); if(v1.dot(v3xv0) < 0) { v2 = v3; v21 = v31; v22 = v32; n.cross(v0, v1, v3); continue; } // If origin is outside (v3,v0,v2), then eliminate v1 and loop if(v2.dot(v3xv0) > 0) { v1 = v3; v11 = v31; v12 = v32; n.cross(v0, v3, v2); continue; } bool hit = false; /// // Phase Two: Refine the portal // We are now inside of a wedge... for(int j = 0;; j++) { // Compute normal of the wedge face n.cross(v1, v2, v3); // Can this happen??? Can it be handled more cleanly? if(n.iszero()) { ASSERT(0); return true; } n.normalize(); // If the origin is inside the wedge, we have a hit if(n.dot(v1) >= 0 && !hit) { if(contactnormal) *contactnormal = n; // Compute the barycentric coordinates of the origin if(contactpoint1 || contactpoint2) { float b0 = v3.scalartriple(v1, v2), b1 = v0.scalartriple(v3, v2), b2 = v3.scalartriple(v0, v1), b3 = v0.scalartriple(v2, v1), sum = b0 + b1 + b2 + b3; if(sum <= 0) { b0 = 0; b1 = n.scalartriple(v2, v3); b2 = n.scalartriple(v3, v1); b3 = n.scalartriple(v1, v2); sum = b1 + b2 + b3; } if(contactpoint1) *contactpoint1 = (vec(v01).mul(b0).add(vec(v11).mul(b1)).add(vec(v21).mul(b2)).add(vec(v31).mul(b3))).mul(1.0f/sum); if(contactpoint2) *contactpoint2 = (vec(v02).mul(b0).add(vec(v12).mul(b1)).add(vec(v22).mul(b2)).add(vec(v32).mul(b3))).mul(1.0f/sum); } // HIT!!! hit = true; } // Find the support point in the direction of the wedge face vec v41 = p1.supportpoint(vec(n).neg()); vec v42 = p2.supportpoint(n); vec v4 = vec(v42).sub(v41); // If the boundary is thin enough or the origin is outside the support plane for the newly discovered vertex, then we can terminate if(v4.dot(n) <= 0 || vec(v4).sub(v3).dot(n) <= boundarytolerance || j > 100) { if(contactnormal) *contactnormal = n; return hit; } // Test origin against the three planes that separate the new portal candidates: (v1,v4,v0) (v2,v4,v0) (v3,v4,v0) // Note: We're taking advantage of the triple product identities here as an optimization // (v1 % v4) * v0 == v1 * (v4 % v0) > 0 if origin inside (v1, v4, v0) // (v2 % v4) * v0 == v2 * (v4 % v0) > 0 if origin inside (v2, v4, v0) // (v3 % v4) * v0 == v3 * (v4 % v0) > 0 if origin inside (v3, v4, v0) vec v4xv0; v4xv0.cross(v4, v0); if(v1.dot(v4xv0) > 0) // Compute the tetrahedron dividing face d1 = (v4,v0,v1) { if(v2.dot(v4xv0) > 0) // Compute the tetrahedron dividing face d2 = (v4,v0,v2) { // Inside d1 & inside d2 ==> eliminate v1 v1 = v4; v11 = v41; v12 = v42; } else { // Inside d1 & outside d2 ==> eliminate v3 v3 = v4; v31 = v41; v32 = v42; } } else { if(v3.dot(v4xv0) > 0) // Compute the tetrahedron dividing face d3 = (v4,v0,v3) { // Outside d1 & inside d3 ==> eliminate v2 v2 = v4; v21 = v41; v22 = v42; } else { // Outside d1 & outside d3 ==> eliminate v1 v1 = v4; v11 = v41; v12 = v42; } } } } return false; } } sandboxgamemaker-2.7.1+dfsg/src/engine/explosion.h0000664000175000017500000004233311460063014022077 0ustar showardshoward//cache our unit hemisphere static GLushort *hemiindices = NULL; static vec *hemiverts = NULL; static int heminumverts = 0, heminumindices = 0; static GLuint hemivbuf = 0, hemiebuf = 0; static void subdivide(int depth, int face); static void genface(int depth, int i1, int i2, int i3) { int face = heminumindices; heminumindices += 3; hemiindices[face] = i1; hemiindices[face+1] = i2; hemiindices[face+2] = i3; subdivide(depth, face); } static void subdivide(int depth, int face) { if(depth-- <= 0) return; int idx[6]; loopi(3) idx[i] = hemiindices[face+i]; loopi(3) { int vert = heminumverts++; hemiverts[vert] = vec(hemiverts[idx[i]]).add(hemiverts[idx[(i+1)%3]]).normalize(); //push on to unit sphere idx[3+i] = vert; hemiindices[face+i] = vert; } subdivide(depth, face); loopi(3) genface(depth, idx[i], idx[3+i], idx[3+(i+2)%3]); } //subdiv version wobble much more nicely than a lat/longitude version static void inithemisphere(int hres, int depth) { const int tris = hres << (2*depth); heminumverts = heminumindices = 0; DELETEA(hemiverts); DELETEA(hemiindices); hemiverts = new vec[tris+1]; hemiindices = new GLushort[tris*3]; hemiverts[heminumverts++] = vec(0.0f, 0.0f, 1.0f); //build initial 'hres' sided pyramid loopi(hres) { float a = PI2*float(i)/hres; hemiverts[heminumverts++] = vec(cosf(a), sinf(a), 0.0f); } loopi(hres) genface(depth, 0, i+1, 1+(i+1)%hres); if(hasVBO) { if(renderpath!=R_FIXEDFUNCTION) { if(!hemivbuf) glGenBuffers_(1, &hemivbuf); glBindBuffer_(GL_ARRAY_BUFFER_ARB, hemivbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, heminumverts*sizeof(vec), hemiverts, GL_STATIC_DRAW_ARB); DELETEA(hemiverts); } if(!hemiebuf) glGenBuffers_(1, &hemiebuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, hemiebuf); glBufferData_(GL_ELEMENT_ARRAY_BUFFER_ARB, heminumindices*sizeof(GLushort), hemiindices, GL_STATIC_DRAW_ARB); DELETEA(hemiindices); } } static GLuint expmodtex[2] = {0, 0}; static GLuint lastexpmodtex = 0; static GLuint createexpmodtex(int size, float minval) { uchar *data = new uchar[size*size], *dst = data; loop(y, size) loop(x, size) { float dx = 2*float(x)/(size-1) - 1, dy = 2*float(y)/(size-1) - 1; float z = max(0.0f, 1.0f - dx*dx - dy*dy); if(minval) z = sqrtf(z); else loopk(2) z *= z; *dst++ = uchar(max(z, minval)*255); } GLuint tex = 0; glGenTextures(1, &tex); createtexture(tex, size, size, data, 3, 2, GL_ALPHA); delete[] data; return tex; } static struct expvert { vec pos; float u, v, s, t; } *expverts = NULL; static GLuint expvbuf = 0; static void animateexplosion() { static int lastexpmillis = 0; if(expverts && lastexpmillis == lastmillis) { if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, expvbuf); return; } lastexpmillis = lastmillis; vec center = vec(13.0f, 2.3f, 7.1f); //only update once per frame! - so use the same center for all... if(!expverts) expverts = new expvert[heminumverts]; loopi(heminumverts) { expvert &e = expverts[i]; vec &v = hemiverts[i]; //texgen - scrolling billboard e.u = v.x*0.5f + 0.0004f*lastmillis; e.v = v.y*0.5f + 0.0004f*lastmillis; //ensure the mod texture is wobbled e.s = v.x*0.5f + 0.5f; e.t = v.y*0.5f + 0.5f; //wobble - similar to shader code float wobble = v.dot(center) + 0.002f*lastmillis; wobble -= floor(wobble); wobble = 1.0f + fabs(wobble - 0.5f)*0.5f; e.pos = vec(v).mul(wobble); } if(hasVBO) { if(!expvbuf) glGenBuffers_(1, &expvbuf); glBindBuffer_(GL_ARRAY_BUFFER_ARB, expvbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, heminumverts*sizeof(expvert), expverts, GL_STREAM_DRAW_ARB); } } static struct spherevert { vec pos; float s, t; } *sphereverts = NULL; static GLushort *sphereindices = NULL; static int spherenumverts = 0, spherenumindices = 0; static GLuint spherevbuf = 0, sphereebuf = 0; static void initsphere(int slices, int stacks) { DELETEA(sphereverts); spherenumverts = (stacks+1)*(slices+1); sphereverts = new spherevert[spherenumverts]; float ds = 1.0f/slices, dt = 1.0f/stacks, t = 1.0f; loopi(stacks+1) { float rho = M_PI*(1-t), s = 0.0f; loopj(slices+1) { float theta = j==slices ? 0 : 2*M_PI*s; spherevert &v = sphereverts[i*(slices+1) + j]; v.pos = vec(-sin(theta)*sin(rho), cos(theta)*sin(rho), cos(rho)); v.s = s; v.t = t; s += ds; } t -= dt; } DELETEA(sphereindices); spherenumindices = stacks*slices*3*2; sphereindices = new ushort[spherenumindices]; GLushort *curindex = sphereindices; loopi(stacks) { loopk(slices) { int j = i%2 ? slices-k-1 : k; *curindex++ = i*(slices+1)+j; *curindex++ = (i+1)*(slices+1)+j; *curindex++ = i*(slices+1)+j+1; *curindex++ = i*(slices+1)+j+1; *curindex++ = (i+1)*(slices+1)+j; *curindex++ = (i+1)*(slices+1)+j+1; } } if(hasVBO) { if(!spherevbuf) glGenBuffers_(1, &spherevbuf); glBindBuffer_(GL_ARRAY_BUFFER_ARB, spherevbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, spherenumverts*sizeof(spherevert), sphereverts, GL_STATIC_DRAW_ARB); DELETEA(sphereverts); if(!sphereebuf) glGenBuffers_(1, &sphereebuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, sphereebuf); glBufferData_(GL_ELEMENT_ARRAY_BUFFER_ARB, spherenumindices*sizeof(GLushort), sphereindices, GL_STATIC_DRAW_ARB); DELETEA(sphereindices); } } VARP(explosion2d, 0, 0, 1); static void setupexplosion() { if(renderpath!=R_FIXEDFUNCTION || maxtmus>=2) { if(!expmodtex[0]) expmodtex[0] = createexpmodtex(64, 0); if(!expmodtex[1]) expmodtex[1] = createexpmodtex(64, 0.25f); lastexpmodtex = 0; } if(renderpath!=R_FIXEDFUNCTION) { if(glaring) { if(explosion2d) SETSHADER(explosion2dglare); else SETSHADER(explosion3dglare); } else if(!reflecting && !refracting && depthfx && depthfxtex.rendertex && numdepthfxranges>0) { if(depthfxtex.target==GL_TEXTURE_RECTANGLE_ARB) { if(!depthfxtex.highprecision()) { if(explosion2d) SETSHADER(explosion2dsoft8rect); else SETSHADER(explosion3dsoft8rect); } else if(explosion2d) SETSHADER(explosion2dsoftrect); else SETSHADER(explosion3dsoftrect); } else { if(!depthfxtex.highprecision()) { if(explosion2d) SETSHADER(explosion2dsoft8); else SETSHADER(explosion3dsoft8); } else if(explosion2d) SETSHADER(explosion2dsoft); else SETSHADER(explosion3dsoft); } } else if(explosion2d) SETSHADER(explosion2d); else SETSHADER(explosion3d); } if(renderpath==R_FIXEDFUNCTION || explosion2d) { if(!hemiverts && !hemivbuf) inithemisphere(5, 2); if(renderpath==R_FIXEDFUNCTION) animateexplosion(); if(hasVBO) { if(renderpath!=R_FIXEDFUNCTION) glBindBuffer_(GL_ARRAY_BUFFER_ARB, hemivbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, hemiebuf); } expvert *verts = renderpath==R_FIXEDFUNCTION ? (hasVBO ? 0 : expverts) : (expvert *)hemiverts; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, renderpath==R_FIXEDFUNCTION ? sizeof(expvert) : sizeof(vec), verts); if(renderpath==R_FIXEDFUNCTION) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(expvert), &verts->u); if(maxtmus>=2) { setuptmu(0, "C * T", "= Ca"); glActiveTexture_(GL_TEXTURE1_ARB); glClientActiveTexture_(GL_TEXTURE1_ARB); glEnable(GL_TEXTURE_2D); setuptmu(1, "P * Ta x 4", "Pa * Ta x 4"); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(expvert), &verts->s); glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); } } } else { if(!sphereverts && !spherevbuf) initsphere(12, 6); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, spherevbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, sphereebuf); } glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(spherevert), &sphereverts->pos); glTexCoordPointer(2, GL_FLOAT, sizeof(spherevert), &sphereverts->s); } } static void drawexpverts(int numverts, int numindices, GLushort *indices) { if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, 0, numverts-1, numindices, GL_UNSIGNED_SHORT, indices); else glDrawElements(GL_TRIANGLES, numindices, GL_UNSIGNED_SHORT, indices); xtraverts += numindices; glde++; } static void drawexplosion(bool inside, uchar r, uchar g, uchar b, uchar a) { if((renderpath!=R_FIXEDFUNCTION || maxtmus>=2) && lastexpmodtex != expmodtex[inside ? 1 : 0]) { glActiveTexture_(GL_TEXTURE1_ARB); lastexpmodtex = expmodtex[inside ? 1 :0]; glBindTexture(GL_TEXTURE_2D, lastexpmodtex); glActiveTexture_(GL_TEXTURE0_ARB); } int passes = !reflecting && !refracting && inside ? 2 : 1; if(renderpath!=R_FIXEDFUNCTION && !explosion2d) { if(inside) glScalef(1, 1, -1); loopi(passes) { glColor4ub(r, g, b, i ? a/2 : a); if(i) glDepthFunc(GL_GEQUAL); drawexpverts(spherenumverts, spherenumindices, sphereindices); if(i) glDepthFunc(GL_LESS); } return; } loopi(passes) { glColor4ub(r, g, b, i ? a/2 : a); if(i) { glScalef(1, 1, -1); glDepthFunc(GL_GEQUAL); } if(inside) { if(passes >= 2) { glCullFace(GL_FRONT); drawexpverts(heminumverts, heminumindices, hemiindices); glCullFace(GL_BACK); } glScalef(1, 1, -1); } drawexpverts(heminumverts, heminumindices, hemiindices); if(i) glDepthFunc(GL_LESS); } } static void cleanupexplosion() { glDisableClientState(GL_VERTEX_ARRAY); if(renderpath==R_FIXEDFUNCTION) { glDisableClientState(GL_TEXTURE_COORD_ARRAY); if(maxtmus>=2) { resettmu(0); glActiveTexture_(GL_TEXTURE1_ARB); glClientActiveTexture_(GL_TEXTURE1_ARB); glDisable(GL_TEXTURE_2D); resettmu(1); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); } } else { if(!explosion2d) glDisableClientState(GL_TEXTURE_COORD_ARRAY); } if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } } static void deleteexplosions() { loopi(2) if(expmodtex[i]) { glDeleteTextures(1, &expmodtex[i]); expmodtex[i] = 0; } if(hemivbuf) { glDeleteBuffers_(1, &hemivbuf); hemivbuf = 0; } if(hemiebuf) { glDeleteBuffers_(1, &hemiebuf); hemiebuf = 0; } DELETEA(hemiverts); DELETEA(hemiindices); if(expvbuf) { glDeleteBuffers_(1, &expvbuf); expvbuf = 0; } DELETEA(expverts); if(spherevbuf) { glDeleteBuffers_(1, &spherevbuf); spherevbuf = 0; } if(sphereebuf) { glDeleteBuffers_(1, &sphereebuf); sphereebuf = 0; } DELETEA(sphereverts); DELETEA(sphereindices); } static const float WOBBLE = 1.25f; struct fireballrenderer : listrenderer { fireballrenderer(const char *texname) : listrenderer(texname, 0, PT_FIREBALL|PT_GLARE) {} void startrender() { setupexplosion(); } void endrender() { cleanupexplosion(); particleshader->set(); } void cleanup() { deleteexplosions(); } int finddepthfxranges(void **owners, float *ranges, int numranges, int maxranges, vec &bbmin, vec &bbmax) { static struct fireballent : physent { fireballent() { type = ENT_CAMERA; collidetype = COLLIDE_AABB; } } e; for(listparticle *p = list; p; p = p->next) { int ts = p->fade <= 5 ? 1 : lastmillis-p->millis; float pmax = p->val, size = p->fade ? float(ts)/p->fade : 1, psize = (p->size + pmax * size)*WOBBLE; if(2*(p->size + pmax)*WOBBLE < depthfxblend || (!depthfxtex.highprecision() && !depthfxtex.emulatehighprecision() && psize > depthfxscale - depthfxbias) || isfoggedsphere(psize, p->o)) continue; e.o = p->o; e.radius = e.xradius = e.yradius = e.eyeheight = e.aboveeye = psize; if(::collide(&e, vec(0, 0, 0), 0, false)) continue; if(depthfxscissor==2 && !depthfxtex.addscissorbox(p->o, psize)) continue; vec dir = camera1->o; dir.sub(p->o); float dist = dir.magnitude(); dir.mul(psize/dist).add(p->o); float depth = depthfxtex.eyedepth(dir); loopk(3) { bbmin[k] = min(bbmin[k], p->o[k] - psize); bbmax[k] = max(bbmax[k], p->o[k] + psize); } int pos = numranges; loopi(numranges) if(depth < ranges[i]) { pos = i; break; } if(pos >= maxranges) continue; if(numranges > pos) { int moved = min(numranges-pos, maxranges-(pos+1)); memmove(&ranges[pos+1], &ranges[pos], moved*sizeof(float)); memmove(&owners[pos+1], &owners[pos], moved*sizeof(void *)); } if(numranges < maxranges) numranges++; ranges[pos] = depth; owners[pos] = p; } return numranges; } void seedemitter(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int gravity) { pe.maxfade = max(pe.maxfade, fade); pe.extendbb(o, (size+1+pe.ent->attr[1])*WOBBLE); } void renderpart(listparticle *p, const vec &o, const vec &d, int blend, int ts, uchar *color) { float pmax = p->val, size = p->fade ? float(ts)/p->fade : 1, psize = p->size + pmax * size; if(isfoggedsphere(psize*WOBBLE, p->o)) return; glPushMatrix(); glTranslatef(o.x, o.y, o.z); bool inside = o.dist(camera1->o) <= psize*WOBBLE; vec oc(o); oc.sub(camera1->o); if(reflecting) oc.z = o.z - reflectz; float yaw = inside ? camera1->yaw : atan2(oc.y, oc.x)/RAD - 90, pitch = (inside ? camera1->pitch : asin(oc.z/oc.magnitude())/RAD) - 90; vec rotdir; if(renderpath==R_FIXEDFUNCTION || explosion2d) { glRotatef(yaw, 0, 0, 1); glRotatef(pitch, 1, 0, 0); rotdir = vec(0, 0, 1); } else { vec s(1, 0, 0), t(0, 1, 0); s.rotate(pitch*RAD, vec(-1, 0, 0)); s.rotate(yaw*RAD, vec(0, 0, -1)); t.rotate(pitch*RAD, vec(-1, 0, 0)); t.rotate(yaw*RAD, vec(0, 0, -1)); rotdir = vec(-1, 1, -1).normalize(); s.rotate(-lastmillis/7.0f*RAD, rotdir); t.rotate(-lastmillis/7.0f*RAD, rotdir); setlocalparamf("texgenS", SHPARAM_VERTEX, 2, 0.5f*s.x, 0.5f*s.y, 0.5f*s.z, 0.5f); setlocalparamf("texgenT", SHPARAM_VERTEX, 3, 0.5f*t.x, 0.5f*t.y, 0.5f*t.z, 0.5f); } if(renderpath!=R_FIXEDFUNCTION) { setlocalparamf("center", SHPARAM_VERTEX, 0, o.x, o.y, o.z); setlocalparamf("animstate", SHPARAM_VERTEX, 1, size, psize, pmax, float(lastmillis)); binddepthfxparams(depthfxblend, inside ? blend/(2*255.0f) : 0, 2*(p->size + pmax)*WOBBLE >= depthfxblend, p); } glRotatef(lastmillis/7.0f, -rotdir.x, rotdir.y, -rotdir.z); glScalef(-psize, psize, -psize); drawexplosion(inside, color[0], color[1], color[2], blend); glPopMatrix(); } }; static fireballrenderer fireballs("packages/particles/explosion"), bluefireballs("packages/particles/explosion"); sandboxgamemaker-2.7.1+dfsg/src/engine/ragdoll.h0000664000175000017500000003605611425020070021504 0ustar showardshowardstruct ragdollskel { struct vert { vec pos; float radius, weight; }; struct tri { int vert[3]; bool shareverts(const tri &t) const { loopi(3) loopj(3) if(vert[i] == t.vert[j]) return true; return false; } }; struct distlimit { int vert[2]; float mindist, maxdist; }; struct rotlimit { int tri[2]; float maxangle; matrix3x3 middle; }; struct rotfriction { int tri[2]; matrix3x3 middle; }; struct joint { int bone, tri, vert[3]; float weight; matrix3x4 orient; }; struct reljoint { int bone, parent; }; bool loaded, animjoints; int eye; vector verts; vector tris; vector distlimits; vector rotlimits; vector rotfrictions; vector joints; vector reljoints; ragdollskel() : loaded(false), animjoints(false), eye(-1) {} void setupjoints() { loopv(verts) verts[i].weight = 0; loopv(joints) { joint &j = joints[i]; j.weight = 0; vec pos(0, 0, 0); loopk(3) if(j.vert[k]>=0) { pos.add(verts[j.vert[k]].pos); j.weight++; verts[j.vert[k]].weight++; } if(j.weight) j.weight = 1/j.weight; pos.mul(j.weight); tri &t = tris[j.tri]; matrix3x3 m; const vec &v1 = verts[t.vert[0]].pos, &v2 = verts[t.vert[1]].pos, &v3 = verts[t.vert[2]].pos; m.a = vec(v2).sub(v1).normalize(); m.c.cross(m.a, vec(v3).sub(v1)).normalize(); m.b.cross(m.c, m.a); j.orient = matrix3x4(m, m.transform(pos).neg()); } loopv(verts) if(verts[i].weight) verts[i].weight = 1/verts[i].weight; reljoints.shrink(0); } void setuprotfrictions() { rotfrictions.shrink(0); loopv(tris) for(int j = i+1; j < tris.length(); j++) if(tris[i].shareverts(tris[j])) { rotfriction &r = rotfrictions.add(); r.tri[0] = i; r.tri[1] = j; } } void setup() { setupjoints(); setuprotfrictions(); loaded = true; } void addreljoint(int bone, int parent) { reljoint &r = reljoints.add(); r.bone = bone; r.parent = parent; } }; struct ragdolldata { struct vert { vec oldpos, pos, newpos; float weight; bool collided; vert() : pos(0, 0, 0), newpos(0, 0, 0), weight(0), collided(false) {} }; ragdollskel *skel; int millis, collidemillis, collisions, floating, lastmove; vec offset, center; float radius, timestep, scale; vert *verts; matrix3x3 *tris; matrix3x4 *animjoints, *reljoints; ragdolldata(ragdollskel *skel, float scale = 1) : skel(skel), millis(lastmillis), collidemillis(0), collisions(0), floating(0), lastmove(lastmillis), timestep(0), scale(scale), verts(new vert[skel->verts.length()]), tris(new matrix3x3[skel->tris.length()]), animjoints(!skel->animjoints || skel->joints.empty() ? NULL : new matrix3x4[skel->joints.length()]), reljoints(skel->reljoints.empty() ? NULL : new matrix3x4[skel->reljoints.length()]) { } ~ragdolldata() { delete[] verts; delete[] tris; if(animjoints) delete[] animjoints; if(reljoints) delete[] reljoints; } void calcanimjoint(int i, const matrix3x4 &anim) { if(!animjoints) return; ragdollskel::joint &j = skel->joints[i]; vec pos(0, 0, 0); loopk(3) if(j.vert[k]>=0) pos.add(verts[j.vert[k]].pos); pos.mul(j.weight); ragdollskel::tri &t = skel->tris[j.tri]; matrix3x3 m; const vec &v1 = verts[t.vert[0]].pos, &v2 = verts[t.vert[1]].pos, &v3 = verts[t.vert[2]].pos; m.a = vec(v2).sub(v1).normalize(); m.c.cross(m.a, vec(v3).sub(v1)).normalize(); m.b.cross(m.c, m.a); animjoints[i].mul(m, m.transform(pos).neg(), anim); } void calctris() { loopv(skel->tris) { ragdollskel::tri &t = skel->tris[i]; matrix3x3 &m = tris[i]; const vec &v1 = verts[t.vert[0]].pos, &v2 = verts[t.vert[1]].pos, &v3 = verts[t.vert[2]].pos; m.a = vec(v2).sub(v1).normalize(); m.c.cross(m.a, vec(v3).sub(v1)).normalize(); m.b.cross(m.c, m.a); } } void calcboundsphere() { center = vec(0, 0, 0); loopv(skel->verts) center.add(verts[i].pos); center.div(skel->verts.length()); radius = 0; loopv(skel->verts) radius = max(radius, verts[i].pos.dist(center)); } void init(dynent *d) { extern int ragdolltimestepmin; float ts = ragdolltimestepmin/1000.0f; loopv(skel->verts) (verts[i].oldpos = verts[i].pos).sub(vec(d->vel).add(d->falling).mul(ts)); timestep = ts; calctris(); calcboundsphere(); offset = d->o; offset.sub(skel->eye >= 0 ? verts[skel->eye].pos : center); offset.z += (d->eyeheight + d->aboveeye)/2; } void move(dynent *pl, float ts); void updatepos(); void constrain(); void constraindist(); void applyrotlimit(ragdollskel::tri &t1, ragdollskel::tri &t2, float angle, const vec &axis); void constrainrot(); void calcrotfriction(); void applyrotfriction(float ts); static inline bool collidevert(const vec &pos, const vec &dir, float radius) { static struct vertent : physent { vertent() { type = ENT_BOUNCE; collidetype = COLLIDE_AABB; radius = xradius = yradius = eyeheight = aboveeye = 1; } } v; v.o = pos; if(v.radius != radius) v.radius = v.xradius = v.yradius = v.eyeheight = v.aboveeye = radius; return collide(&v, dir, 0, false); } }; /* seed particle position = avg(modelview * base2anim * spherepos) mapped transform = invert(curtri) * origtrig parented transform = parent{invert(curtri) * origtrig} * (invert(parent{base2anim}) * base2anim) */ void ragdolldata::constraindist() { float invscale = 1.0f/scale; loopv(skel->distlimits) { ragdollskel::distlimit &d = skel->distlimits[i]; vert &v1 = verts[d.vert[0]], &v2 = verts[d.vert[1]]; vec dir = vec(v2.pos).sub(v1.pos); float dist = dir.magnitude()*invscale, cdist; if(dist < d.mindist) cdist = d.mindist; else if(dist > d.maxdist) cdist = d.maxdist; else continue; if(dist > 1e-4f) dir.mul(cdist*0.5f/dist); else dir = vec(0, 0, cdist*0.5f/invscale); vec center = vec(v1.pos).add(v2.pos).mul(0.5f); v1.newpos.add(vec(center).sub(dir)); v1.weight++; v2.newpos.add(vec(center).add(dir)); v2.weight++; } } inline void ragdolldata::applyrotlimit(ragdollskel::tri &t1, ragdollskel::tri &t2, float angle, const vec &axis) { vert &v1a = verts[t1.vert[0]], &v1b = verts[t1.vert[1]], &v1c = verts[t1.vert[2]], &v2a = verts[t2.vert[0]], &v2b = verts[t2.vert[1]], &v2c = verts[t2.vert[2]]; vec m1 = vec(v1a.pos).add(v1b.pos).add(v1c.pos).div(3), m2 = vec(v2a.pos).add(v2b.pos).add(v2c.pos).div(3), q1a, q1b, q1c, q2a, q2b, q2c; float w1 = q1a.cross(axis, vec(v1a.pos).sub(m1)).magnitude() + q1b.cross(axis, vec(v1b.pos).sub(m1)).magnitude() + q1c.cross(axis, vec(v1c.pos).sub(m1)).magnitude(), w2 = q2a.cross(axis, vec(v2a.pos).sub(m2)).magnitude() + q2b.cross(axis, vec(v2b.pos).sub(m2)).magnitude() + q2c.cross(axis, vec(v2c.pos).sub(m2)).magnitude(); angle /= w1 + w2 + 1e-9f; float a1 = angle*w2, a2 = -angle*w1, s1 = sinf(a1), s2 = sinf(a2); vec c1 = vec(axis).mul(1 - cosf(a1)), c2 = vec(axis).mul(1 - cosf(a2)); v1a.newpos.add(vec().cross(c1, q1a).add(vec(q1a).mul(s1)).add(v1a.pos)); v1a.weight++; v1b.newpos.add(vec().cross(c1, q1b).add(vec(q1b).mul(s1)).add(v1b.pos)); v1b.weight++; v1c.newpos.add(vec().cross(c1, q1c).add(vec(q1c).mul(s1)).add(v1c.pos)); v1c.weight++; v2a.newpos.add(vec().cross(c2, q2a).add(vec(q2a).mul(s2)).add(v2a.pos)); v2a.weight++; v2b.newpos.add(vec().cross(c2, q2b).add(vec(q2b).mul(s2)).add(v2b.pos)); v2b.weight++; v2c.newpos.add(vec().cross(c2, q2c).add(vec(q2c).mul(s2)).add(v2c.pos)); v2c.weight++; } void ragdolldata::constrainrot() { loopv(skel->rotlimits) { ragdollskel::rotlimit &r = skel->rotlimits[i]; matrix3x3 rot; rot.transposemul(tris[r.tri[0]], r.middle); rot.mul(tris[r.tri[1]]); vec axis; float angle; if(!rot.calcangleaxis(angle, axis)) continue; angle = r.maxangle - fabs(angle); if(angle >= 0) continue; angle += 1e-3f; applyrotlimit(skel->tris[r.tri[0]], skel->tris[r.tri[1]], angle, axis); } } VAR(ragdolltimestepmin, 1, 5, 50); VAR(ragdolltimestepmax, 1, 10, 50); FVAR(ragdollrotfric, 0, 0.85f, 1); FVAR(ragdollrotfricstop, 0, 0.1f, 1); void ragdolldata::calcrotfriction() { loopv(skel->rotfrictions) { ragdollskel::rotfriction &r = skel->rotfrictions[i]; r.middle.multranspose(tris[r.tri[0]], tris[r.tri[1]]); } } void ragdolldata::applyrotfriction(float ts) { calctris(); float stopangle = 2*M_PI*ts*ragdollrotfricstop, rotfric = 1.0f - pow(ragdollrotfric, ts*1000.0f/ragdolltimestepmin); loopv(skel->rotfrictions) { ragdollskel::rotfriction &r = skel->rotfrictions[i]; matrix3x3 rot; rot.transposemul(tris[r.tri[0]], r.middle); rot.mul(tris[r.tri[1]]); vec axis; float angle; if(rot.calcangleaxis(angle, axis)) { angle *= -(fabs(angle) >= stopangle ? rotfric : 1.0f); applyrotlimit(skel->tris[r.tri[0]], skel->tris[r.tri[1]], angle, axis); } } loopv(skel->verts) { vert &v = verts[i]; if(v.weight) v.pos = v.newpos.div(v.weight); v.newpos = vec(0, 0, 0); v.weight = 0; } } extern vec wall; void ragdolldata::updatepos() { loopv(skel->verts) { vert &v = verts[i]; if(v.weight) { v.newpos.div(v.weight); if(collidevert(v.newpos, vec(v.newpos).sub(v.pos), skel->verts[i].radius)) v.pos = v.newpos; else { vec dir = vec(v.newpos).sub(v.oldpos); if(dir.dot(wall) < 0) v.oldpos = vec(v.pos).sub(dir.reflect(wall)); v.collided = true; } } v.newpos = vec(0, 0, 0); v.weight = 0; } } VAR(ragdollconstrain, 1, 5, 100); void ragdolldata::constrain() { loopi(ragdollconstrain) { constraindist(); updatepos(); calctris(); constrainrot(); updatepos(); } } FVAR(ragdollbodyfric, 0, 0.95f, 1); FVAR(ragdollbodyfricscale, 0, 2, 10); FVAR(ragdollwaterfric, 0, 0.85f, 1); FVAR(ragdollgroundfric, 0, 0.8f, 1); FVAR(ragdollairfric, 0, 0.996f, 1); VAR(ragdollexpireoffset, 0, 1500, 30000); VAR(ragdollwaterexpireoffset, 0, 3000, 30000); void ragdolldata::move(dynent *pl, float ts) { extern float gravity; if(collidemillis && lastmillis > collidemillis) return; int material = lookupmaterial(vec(center.x, center.y, center.z + radius/2)); bool water = isliquid(material&MATF_VOLUME); if(!pl->inwater && water) game::physicstrigger(pl, true, 0, -1, material&MATF_VOLUME); else if(pl->inwater && !water) { material = lookupmaterial(center); water = isliquid(material&MATF_VOLUME); if(!water) game::physicstrigger(pl, true, 0, 1, pl->inwater); } pl->inwater = water ? material&MATF_VOLUME : MAT_AIR; calcrotfriction(); float tsfric = timestep ? ts/timestep : 1, airfric = ragdollairfric + min((ragdollbodyfricscale*collisions)/skel->verts.length(), 1.0f)*(ragdollbodyfric - ragdollairfric); collisions = 0; loopv(skel->verts) { vert &v = verts[i]; vec dpos = vec(v.pos).sub(v.oldpos); dpos.z -= gravity*ts*ts; if(water) dpos.z += 0.25f*sinf(detrnd(size_t(this)+i, 360)*RAD + lastmillis/10000.0f*M_PI)*ts; dpos.mul(pow((water ? ragdollwaterfric : 1.0f) * (v.collided ? ragdollgroundfric : airfric), ts*1000.0f/ragdolltimestepmin)*tsfric); v.oldpos = v.pos; v.pos.add(dpos); } applyrotfriction(ts); loopv(skel->verts) { vert &v = verts[i]; if(v.pos.z < 0) { v.pos.z = 0; v.oldpos = v.pos; collisions++; } vec dir = vec(v.pos).sub(v.oldpos); v.collided = !collidevert(v.pos, dir, skel->verts[i].radius); if(v.collided) { v.pos = v.oldpos; v.oldpos.sub(dir.reflect(wall)); collisions++; } } timestep = ts; if(collisions) { floating = 0; if(!collidemillis) collidemillis = lastmillis + (water ? ragdollwaterexpireoffset : ragdollexpireoffset); } else if(++floating > 1 && lastmillis < collidemillis) collidemillis = 0; constrain(); calctris(); calcboundsphere(); } FVAR(ragdolleyesmooth, 0, 0.5f, 1); VAR(ragdolleyesmoothmillis, 1, 250, 10000); void moveragdoll(dynent *d) { if(!curtime || !d->ragdoll) return; if(!d->ragdoll->collidemillis || lastmillis < d->ragdoll->collidemillis) { int lastmove = d->ragdoll->lastmove; while(d->ragdoll->lastmove + (lastmove == d->ragdoll->lastmove ? ragdolltimestepmin : ragdolltimestepmax) <= lastmillis) { int timestep = min(ragdolltimestepmax, lastmillis - d->ragdoll->lastmove); d->ragdoll->move(d, timestep/1000.0f); d->ragdoll->lastmove += timestep; } } vec eye = d->ragdoll->skel->eye >= 0 ? d->ragdoll->verts[d->ragdoll->skel->eye].pos : d->ragdoll->center; eye.add(d->ragdoll->offset); float k = pow(ragdolleyesmooth, float(curtime)/ragdolleyesmoothmillis); d->o.mul(k).add(eye.mul(1-k)); } void ragdolladdvel(dynent *d, vec &vel) { if(!d->ragdoll) return; loopv(d->ragdoll->skel->verts) { d->ragdoll->verts[i].oldpos.sub(vel); d->ragdoll->collidemillis = d->ragdoll->lastmove = lastmillis; } } void cleanragdoll(dynent *d) { DELETEP(d->ragdoll); } sandboxgamemaker-2.7.1+dfsg/src/engine/md5.h0000664000175000017500000004040511460063014020542 0ustar showardshowardstruct md5; struct md5joint { vec pos; quat orient; }; struct md5weight { int joint; float bias; vec pos; }; struct md5vert { float u, v; ushort start, count; }; struct md5hierarchy { string name; int parent, flags, start; }; struct md5 : skelmodel, skelloader { md5(const char *name) : skelmodel(name) {} static const char *formatname() { return "md5"; } int type() const { return MDL_MD5; } struct md5mesh : skelmesh { md5weight *weightinfo; int numweights; md5vert *vertinfo; md5mesh() : weightinfo(NULL), numweights(0), vertinfo(NULL) { } ~md5mesh() { cleanup(); } void cleanup() { DELETEA(weightinfo); DELETEA(vertinfo); } void buildverts(vector &joints) { loopi(numverts) { md5vert &v = vertinfo[i]; vec pos(0, 0, 0); loopk(v.count) { md5weight &w = weightinfo[v.start+k]; md5joint &j = joints[w.joint]; pos.add(j.orient.rotate(w.pos).add(j.pos).mul(w.bias)); } vert &vv = verts[i]; vv.pos = pos; vv.u = v.u; vv.v = v.v; blendcombo c; int sorted = 0; loopj(v.count) { md5weight &w = weightinfo[v.start+j]; sorted = c.addweight(sorted, w.bias, w.joint); } c.finalize(sorted); vv.blend = addblendcombo(c); } } void load(stream *f, char *buf, size_t bufsize) { md5weight w; md5vert v; tri t; int index; while(f->getline(buf, bufsize) && buf[0]!='}') { if(strstr(buf, "// meshes:")) { char *start = strchr(buf, ':')+1; if(*start==' ') start++; char *end = start + strlen(start)-1; while(end >= start && isspace(*end)) end--; name = newstring(start, end+1-start); } else if(strstr(buf, "shader")) { char *start = strchr(buf, '"'), *end = start ? strchr(start+1, '"') : NULL; if(start && end) { char *texname = newstring(start+1, end-(start+1)); part *p = loading->parts.last(); p->initskins(notexture, notexture, group->meshes.length()); skin &s = p->skins.last(); s.tex = textureload(makerelpath(dir, texname), 0, true, false); delete[] texname; } } else if(sscanf(buf, " numverts %d", &numverts)==1) { numverts = max(numverts, 0); if(numverts) { vertinfo = new md5vert[numverts]; verts = new vert[numverts]; } } else if(sscanf(buf, " numtris %d", &numtris)==1) { numtris = max(numtris, 0); if(numtris) tris = new tri[numtris]; } else if(sscanf(buf, " numweights %d", &numweights)==1) { numweights = max(numweights, 0); if(numweights) weightinfo = new md5weight[numweights]; } else if(sscanf(buf, " vert %d ( %f %f ) %hu %hu", &index, &v.u, &v.v, &v.start, &v.count)==5) { if(index>=0 && index=0 && index=0 && index basejoints; while(f->getline(buf, sizeof(buf))) { int tmp; if(sscanf(buf, " MD5Version %d", &tmp)==1) { if(tmp!=10) { delete f; return false; } } else if(sscanf(buf, " numJoints %d", &tmp)==1) { if(tmp<1) { delete f; return false; } if(skel->numbones>0) continue; skel->numbones = tmp; skel->bones = new boneinfo[skel->numbones]; } else if(sscanf(buf, " numMeshes %d", &tmp)==1) { if(tmp<1) { delete f; return false; } } else if(strstr(buf, "joints {")) { string name; int parent; md5joint j; while(f->getline(buf, sizeof(buf)) && buf[0]!='}') { char *curbuf = buf, *curname = name; bool allowspace = false; while(*curbuf && isspace(*curbuf)) curbuf++; if(*curbuf == '"') { curbuf++; allowspace = true; } while(*curbuf && curname < &name[sizeof(name)-1]) { char c = *curbuf++; if(c == '"') break; if(isspace(c) && !allowspace) break; *curname++ = c; } *curname = '\0'; if(sscanf(curbuf, " %d ( %f %f %f ) ( %f %f %f )", &parent, &j.pos.x, &j.pos.y, &j.pos.z, &j.orient.x, &j.orient.y, &j.orient.z)==7) { j.pos.y = -j.pos.y; j.orient.x = -j.orient.x; j.orient.z = -j.orient.z; if(basejoints.length()numbones) { if(!skel->bones[basejoints.length()].name) skel->bones[basejoints.length()].name = newstring(name); skel->bones[basejoints.length()].parent = parent; } j.orient.restorew(); basejoints.add(j); } } if(basejoints.length()!=skel->numbones) { delete f; return false; } } else if(strstr(buf, "mesh {")) { md5mesh *m = new md5mesh; m->group = this; meshes.add(m); m->load(f, buf, sizeof(buf)); if(!m->numtris || !m->numverts) { conoutf("empty mesh in %s", filename); meshes.removeobj(m); delete m; } } } if(skel->shared <= 1) { skel->linkchildren(); loopv(basejoints) { boneinfo &b = skel->bones[i]; b.base = dualquat(basejoints[i].orient, basejoints[i].pos); (b.invbase = b.base).invert(); } } loopv(meshes) { md5mesh &m = *(md5mesh *)meshes[i]; m.buildverts(basejoints); if(smooth <= 1) m.smoothnorms(smooth); else m.buildnorms(); m.cleanup(); } sortblendcombos(); delete f; return true; } skelanimspec *loadanim(const char *filename) { skelanimspec *sa = skel->findskelanim(filename); if(sa) return sa; stream *f = openfile(filename, "r"); if(!f) return NULL; vector hierarchy; vector basejoints; int animdatalen = 0, animframes = 0; float *animdata = NULL; dualquat *animbones = NULL; char buf[512]; while(f->getline(buf, sizeof(buf))) { int tmp; if(sscanf(buf, " MD5Version %d", &tmp)==1) { if(tmp!=10) { delete f; return NULL; } } else if(sscanf(buf, " numJoints %d", &tmp)==1) { if(tmp!=skel->numbones) { delete f; return NULL; } } else if(sscanf(buf, " numFrames %d", &animframes)==1) { if(animframes<1) { delete f; return NULL; } } else if(sscanf(buf, " frameRate %d", &tmp)==1); else if(sscanf(buf, " numAnimatedComponents %d", &animdatalen)==1) { if(animdatalen>0) animdata = new float[animdatalen]; } else if(strstr(buf, "bounds {")) { while(f->getline(buf, sizeof(buf)) && buf[0]!='}'); } else if(strstr(buf, "hierarchy {")) { while(f->getline(buf, sizeof(buf)) && buf[0]!='}') { md5hierarchy h; if(sscanf(buf, " %s %d %d %d", h.name, &h.parent, &h.flags, &h.start)==4) hierarchy.add(h); } } else if(strstr(buf, "baseframe {")) { while(f->getline(buf, sizeof(buf)) && buf[0]!='}') { md5joint j; if(sscanf(buf, " ( %f %f %f ) ( %f %f %f )", &j.pos.x, &j.pos.y, &j.pos.z, &j.orient.x, &j.orient.y, &j.orient.z)==6) { j.pos.y = -j.pos.y; j.orient.x = -j.orient.x; j.orient.z = -j.orient.z; j.orient.restorew(); basejoints.add(j); } } if(basejoints.length()!=skel->numbones) { delete f; return NULL; } animbones = new dualquat[(skel->numframes+animframes)*skel->numbones]; if(skel->framebones) { memcpy(animbones, skel->framebones, skel->numframes*skel->numbones*sizeof(dualquat)); delete[] skel->framebones; } skel->framebones = animbones; animbones += skel->numframes*skel->numbones; sa = &skel->addskelanim(filename); sa->frame = skel->numframes; sa->range = animframes; skel->numframes += animframes; } else if(sscanf(buf, " frame %d", &tmp)==1) { for(int numdata = 0; f->getline(buf, sizeof(buf)) && buf[0]!='}';) { for(char *src = buf, *next = src; numdata < animdatalen; numdata++, src = next) { animdata[numdata] = strtod(src, &next); if(next <= src) break; } } dualquat *frame = &animbones[tmp*skel->numbones]; loopv(basejoints) { md5hierarchy &h = hierarchy[i]; md5joint j = basejoints[i]; if(h.start < animdatalen && h.flags) { float *jdata = &animdata[h.start]; if(h.flags&1) j.pos.x = *jdata++; if(h.flags&2) j.pos.y = -*jdata++; if(h.flags&4) j.pos.z = *jdata++; if(h.flags&8) j.orient.x = -*jdata++; if(h.flags&16) j.orient.y = *jdata++; if(h.flags&32) j.orient.z = -*jdata++; j.orient.restorew(); } frame[i] = dualquat(j.orient, j.pos); if(adjustments.inrange(i)) adjustments[i].adjust(frame[i]); frame[i].mul(skel->bones[i].invbase); if(h.parent >= 0) frame[i].mul(skel->bones[h.parent].base, dualquat(frame[i])); frame[i].fixantipodal(skel->framebones[i]); } } } DELETEA(animdata); delete f; return sa; } bool load(const char *meshfile, float smooth) { name = newstring(meshfile); if(!loadmesh(meshfile, smooth)) return false; return true; } }; meshgroup *loadmeshes(char *name, va_list args) { md5meshgroup *group = new md5meshgroup; group->shareskeleton(va_arg(args, char *)); if(!group->load(name, va_arg(args, double))) { delete group; return NULL; } return group; } bool loaddefaultparts() { skelpart &mdl = *new skelpart; parts.add(&mdl); mdl.model = this; mdl.index = 0; mdl.pitchscale = mdl.pitchoffset = mdl.pitchmin = mdl.pitchmax = 0; adjustments.setsize(0); const char *fname = loadname + strlen(loadname); do --fname; while(fname >= loadname && *fname!='/' && *fname!='\\'); fname++; defformatstring(meshname)("packages/models/%s/%s.md5mesh", loadname, fname); mdl.meshes = sharemeshes(path(meshname), NULL, 2.0); if(!mdl.meshes) return false; mdl.initanimparts(); mdl.initskins(); defformatstring(animname)("packages/models/%s/%s.md5anim", loadname, fname); ((md5meshgroup *)mdl.meshes)->loadanim(path(animname)); return true; } bool load() { if(loaded) return true; formatstring(dir)("packages/models/%s", loadname); defformatstring(cfgname)("packages/models/%s/md5.cfg", loadname); loading = this; identflags &= ~IDF_PERSIST; if(execfile(cfgname, false) && parts.length()) // configured md5, will call the md5* commands below { identflags |= IDF_PERSIST; loading = NULL; loopv(parts) if(!parts[i]->meshes) return false; } else // md5 without configuration, try default tris and skin { identflags |= IDF_PERSIST; if(!loaddefaultparts()) { loading = NULL; return false; } loading = NULL; } scale /= 4; parts[0]->translate = translate; loopv(parts) { skelpart *p = (skelpart *)parts[i]; p->endanimparts(); p->meshes->shared++; } preloadshaders(); return loaded = true; } }; skelcommands md5commands; sandboxgamemaker-2.7.1+dfsg/src/engine/blob.cpp0000664000175000017500000004751411642642476021357 0ustar showardshoward#include "engine.h" VARNP(blobs, showblobs, 0, 1, 1); VARFP(blobintensity, 0, 60, 100, resetblobs()); VARFP(blobheight, 1, 32, 128, resetblobs()); VARFP(blobfadelow, 1, 8, 32, resetblobs()); VARFP(blobfadehigh, 1, 8, 32, resetblobs()); VARFP(blobmargin, 0, 1, 16, resetblobs()); VAR(dbgblob, 0, 0, 1); struct blobinfo { vec o; float radius; int millis; uint startindex, endindex; ushort startvert, endvert; }; struct blobvert { vec pos; float u, v; bvec color; uchar alpha; }; struct blobrenderer { const char *texname; Texture *tex; blobinfo **cache; int cachesize; blobinfo *blobs; int maxblobs, startblob, endblob; blobvert *verts; int maxverts, startvert, endvert, availverts; ushort *indexes; int maxindexes, startindex, endindex, availindexes; blobinfo *lastblob, *flushblob; vec blobmin, blobmax; ivec bborigin, bbsize; float blobalphalow, blobalphahigh; uchar blobalpha; blobrenderer(const char *texname) : texname(texname), tex(NULL), cache(NULL), cachesize(0), blobs(NULL), maxblobs(0), startblob(0), endblob(0), verts(NULL), maxverts(0), startvert(0), endvert(0), availverts(0), indexes(NULL), maxindexes(0), startindex(0), endindex(0), availindexes(0), lastblob(NULL) {} void init(int tris) { if(cache) { DELETEA(cache); cachesize = 0; } if(blobs) { DELETEA(blobs); maxblobs = startblob = endblob = 0; } if(verts) { DELETEA(verts); maxverts = startvert = endvert = availverts = 0; } if(indexes) { DELETEA(indexes); maxindexes = startindex = endindex = availindexes = 0; } if(!tris) return; tex = textureload(texname, 3); cachesize = tris/2; cache = new blobinfo *[cachesize]; memset(cache, 0, cachesize * sizeof(blobinfo *)); maxblobs = tris/2; blobs = new blobinfo[maxblobs]; memset(blobs, 0, maxblobs * sizeof(blobinfo)); maxindexes = tris*3 + 3; availindexes = maxindexes - 3; indexes = new ushort[maxindexes]; maxverts = min(tris*3/2 + 1, (1<<16)-1); availverts = maxverts - 1; verts = new blobvert[maxverts]; } bool freeblob() { blobinfo &b = blobs[startblob]; if(&b == lastblob) return false; startblob++; if(startblob >= maxblobs) startblob = 0; startvert = b.endvert; if(startvert>=maxverts) startvert = 0; availverts += b.endvert - b.startvert; startindex = b.endindex; if(startindex>=maxindexes) startindex = 0; availindexes += b.endindex - b.startindex; b.millis = 0; return true; } blobinfo &newblob(const vec &o, float radius) { blobinfo &b = blobs[endblob]; int next = endblob + 1; if(next>=maxblobs) next = 0; if(next==startblob) { lastblob = &b; freeblob(); } endblob = next; b.o = o; b.radius = radius; b.millis = totalmillis; b.startindex = b.endindex = endindex; b.startvert = b.endvert = endvert; lastblob = &b; return b; } void clearblobs() { startblob = endblob = 0; startvert = endvert = 0; availverts = maxverts - 1; startindex = endindex = 0; availindexes = maxindexes - 3; } template static int split(const vec *in, int numin, float below, float above, vec *out) { int numout = 0; const vec *p = &in[numin-1]; float pc = (*p)[C]; loopi(numin) { const vec &v = in[i]; float c = v[C]; if(c < below) { if(pc > above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); if(pc > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(c > above) { if(pc < below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); if(pc < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); } else if(pc < below) { if(c > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(pc > above && c < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); out[numout++] = v; p = &v; pc = c; } return numout; } template static int clip(const vec *in, int numin, float below, float above, vec *out) { int numout = 0; const vec *p = &in[numin-1]; float pc = (*p)[C]; loopi(numin) { const vec &v = in[i]; float c = v[C]; if(c < below) { if(pc > above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); if(pc > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(c > above) { if(pc < below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); if(pc < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); } else { if(pc < below) { if(c > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(pc > above && c < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); out[numout++] = v; } p = &v; pc = c; } return numout; } void dupblob() { if(lastblob->startvert >= lastblob->endvert) { lastblob->startindex = lastblob->endindex = endindex; lastblob->startvert = lastblob->endvert = endvert; return; } blobinfo &b = newblob(lastblob->o, lastblob->radius); b.millis = -1; } inline int addvert(const vec &pos) { blobvert &v = verts[endvert]; v.pos = pos; v.u = (pos.x - blobmin.x) / (blobmax.x - blobmin.x); v.v = (pos.y - blobmin.y) / (blobmax.y - blobmin.y); v.color = bvec(255, 255, 255); if(pos.z < blobmin.z + blobfadelow) v.alpha = uchar(blobalphalow * (pos.z - blobmin.z)); else if(pos.z > blobmax.z - blobfadehigh) v.alpha = uchar(blobalphahigh * (blobmax.z - pos.z)); else v.alpha = blobalpha; return endvert++; } void addtris(const vec *v, int numv) { if(endvert != int(lastblob->endvert) || endindex != int(lastblob->endindex)) dupblob(); for(const vec *cur = &v[2], *end = &v[numv];;) { int limit = maxverts - endvert - 2; if(limit <= 0) { while(availverts < limit+2) if(!freeblob()) return; availverts -= limit+2; lastblob->endvert = maxverts; endvert = 0; dupblob(); limit = maxverts - 2; } limit = min(int(end - cur), min(limit, (maxindexes - endindex)/3)); while(availverts < limit+2) if(!freeblob()) return; while(availindexes < limit*3) if(!freeblob()) return; int i1 = addvert(v[0]), i2 = addvert(cur[-1]); loopk(limit) { indexes[endindex++] = i1; indexes[endindex++] = i2; i2 = addvert(*cur++); indexes[endindex++] = i2; } availverts -= endvert - lastblob->endvert; availindexes -= endindex - lastblob->endindex; lastblob->endvert = endvert; lastblob->endindex = endindex; if(endvert >= maxverts) endvert = 0; if(endindex >= maxindexes) endindex = 0; if(cur >= end) break; dupblob(); } } void gentris(cube &cu, int orient, const ivec &o, int size, materialsurface *mat = NULL) { vec pos[MAXFACEVERTS+8]; int dim = dimension(orient), numverts = 0, numplanes = 1, flat = -1; if(mat) { int dc = dimcoord(orient), c = C[dim], r = R[dim]; vec vo = o.tovec(), vscale; vo[dim] += dc ? -0.1f : 0.1f; vscale[c] = mat->csize/8.0f; vscale[r] = mat->rsize/8.0f; vscale[dim] = 0; loopk(4) pos[numverts++] = facecoords[orient][k].tovec().mul(vscale).add(vo); flat = dim; } else if(cu.texture[orient] == DEFAULT_SKY) return; else if(cu.ext && (numverts = cu.ext->surfaces[orient].numverts&MAXFACEVERTS)) { vertinfo *verts = cu.ext->verts() + cu.ext->surfaces[orient].verts; ivec vo = ivec(o).mask(~0xFFF).shl(3); loopj(numverts) pos[j] = verts[j].getxyz().add(vo).tovec().mul(1/8.0f); if(numverts >= 4 && !(cu.merged&(1<= 0) { float offset = pos[0][dim]; if(offset < blobmin[dim] || offset > blobmax[dim]) return; flat = dim; } vec vmin = pos[0], vmax = pos[0]; for(int i = 1; i < numverts; i++) { vmin.min(pos[i]); vmax.max(pos[i]); } if(vmax.x < blobmin.x || vmin.x > blobmax.x || vmax.y < blobmin.y || vmin.y > blobmax.y || vmax.z < blobmin.z || vmin.z > blobmax.z) return; vec v1[MAXFACEVERTS+6+4], v2[MAXFACEVERTS+6+4]; loopl(numplanes) { vec *v = pos; int numv = numverts; if(numplanes >= 2) { if(l) { pos[1] = pos[2]; pos[2] = pos[3]; } numv = 3; } #define CLIPSIDE(clip, below, above) \ { \ vec *in = v; \ v = in==v1 ? v2 : v1; \ numv = clip(in, numv, below, above, v); \ if(numv < 3) continue; \ } if(flat!=0) CLIPSIDE(clip<0>, blobmin.x, blobmax.x); if(flat!=1) CLIPSIDE(clip<1>, blobmin.y, blobmax.y); if(flat!=2) { CLIPSIDE(clip<2>, blobmin.z, blobmax.z); CLIPSIDE(split<2>, blobmin.z + blobfadelow, blobmax.z - blobfadehigh); } addtris(v, numv); } } void findmaterials(vtxarray *va) { materialsurface *matbuf = va->matbuf; int matsurfs = va->matsurfs; loopi(matsurfs) { materialsurface &m = matbuf[i]; if(!isclipped(m.material&MATF_VOLUME) || m.orient == O_BOTTOM) { i += m.skip; continue; } int dim = dimension(m.orient), c = C[dim], r = R[dim]; for(;;) { materialsurface &m = matbuf[i]; if(m.o[dim] >= blobmin[dim] && m.o[dim] <= blobmax[dim] && m.o[c] + m.csize >= blobmin[c] && m.o[c] <= blobmax[c] && m.o[r] + m.rsize >= blobmin[r] && m.o[r] <= blobmax[r]) { static cube dummy; gentris(dummy, m.orient, m.o, max(m.csize, m.rsize), &m); } if(i+1 >= matsurfs) break; materialsurface &n = matbuf[i+1]; if(n.material != m.material || n.orient != m.orient) break; i++; } } } void findescaped(cube *cu, const ivec &o, int size, int escaped) { loopi(8) { if(escaped&(1<>1, cu[i].escaped); else { int vismask = cu[i].escaped&cu[i].merged; if(vismask) loopj(6) if(vismask&(1<va && cu[i].ext->va->matsurfs) findmaterials(cu[i].ext->va); if(cu[i].children) gentris(cu[i].children, co, size>>1, cu[i].escaped); else { int vismask = cu[i].visible|cu[i].merged; if(vismask) loopj(6) if(vismask&(1<>1, cu[i].escaped); else { int vismask = cu[i].escaped&cu[i].merged; if(vismask) loopj(6) if(vismask&(1<>1); return b.millis >= 0 ? &b : NULL; } static void setuprenderstate() { foggedshader->set(); enablepolygonoffset(GL_POLYGON_OFFSET_FILL); glDepthMask(GL_FALSE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(!dbgblob) glEnable(GL_BLEND); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); } static void cleanuprenderstate() { glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDepthMask(GL_TRUE); glDisable(GL_BLEND); disablepolygonoffset(GL_POLYGON_OFFSET_FILL); } static int lastreset; static void reset() { lastreset = totalmillis; } static blobrenderer *lastrender; void fadeblob(blobinfo *b, float fade) { float minz = b->o.z - (blobheight + blobfadelow), maxz = b->o.z + blobfadehigh, scale = fade*blobintensity*255/100.0f, scalelow = scale / blobfadelow, scalehigh = scale / blobfadehigh; uchar alpha = uchar(scale); b->millis = totalmillis; do { if(b->endvert - b->startvert >= 3) for(blobvert *v = &verts[b->startvert], *end = &verts[b->endvert]; v < end; v++) { float z = v->pos.z; if(z < minz + blobfadelow) v->alpha = uchar(scalelow * (z - minz)); else if(z > maxz - blobfadehigh) v->alpha = uchar(scalehigh * (maxz - z)); else v->alpha = alpha; } int offset = b - &blobs[0] + 1; if(offset >= maxblobs) offset = 0; if(offset < endblob ? offset > startblob || startblob > endblob : offset > startblob) b = &blobs[offset]; else break; } while(b->millis < 0); } void renderblob(const vec &o, float radius, float fade) { if(lastrender != this) { if(!lastrender) { if(!blobs) initblobs(); setuprenderstate(); } glVertexPointer(3, GL_FLOAT, sizeof(blobvert), &verts->pos); glTexCoordPointer(2, GL_FLOAT, sizeof(blobvert), &verts->u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(blobvert), &verts->color); if(!lastrender || lastrender->tex != tex) glBindTexture(GL_TEXTURE_2D, tex->id); lastrender = this; } union { int i; float f; } ox, oy; ox.f = o.x; oy.f = o.y; uint hash = uint(ox.i^~oy.i^(INT_MAX-oy.i)^uint(radius)); hash %= cachesize; blobinfo *b = cache[hash]; if(!b || b->millis <= lastreset || b->o!=o || b->radius!=radius) { b = addblob(o, radius, fade); cache[hash] = b; if(!b) return; } else if(fade < 1 && b->millis < totalmillis) fadeblob(b, fade); do { if(b->endvert - b->startvert >= 3) { if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, b->startvert, b->endvert-1, b->endindex - b->startindex, GL_UNSIGNED_SHORT, &indexes[b->startindex]); else glDrawElements(GL_TRIANGLES, b->endindex - b->startindex, GL_UNSIGNED_SHORT, &indexes[b->startindex]); xtravertsva += b->endvert - b->startvert; } int offset = b - &blobs[0] + 1; if(offset >= maxblobs) offset = 0; if(offset < endblob ? offset > startblob || startblob > endblob : offset > startblob) b = &blobs[offset]; else break; } while(b->millis < 0); } }; int blobrenderer::lastreset = 0; blobrenderer *blobrenderer::lastrender = NULL; VARFP(blobstattris, 128, 4096, 1<<16, initblobs(BLOB_STATIC)); VARFP(blobdyntris, 128, 4096, 1<<16, initblobs(BLOB_DYNAMIC)); static blobrenderer blobs[] = { blobrenderer("packages/particles/blob"), blobrenderer("packages/particles/blob") }; void initblobs(int type) { if(type < 0 || (type==BLOB_STATIC && blobs[BLOB_STATIC].blobs)) blobs[BLOB_STATIC].init(showblobs ? blobstattris : 0); if(type < 0 || (type==BLOB_DYNAMIC && blobs[BLOB_DYNAMIC].blobs)) blobs[BLOB_DYNAMIC].init(showblobs ? blobdyntris : 0); } void resetblobs() { blobrenderer::lastreset = totalmillis; } void renderblob(int type, const vec &o, float radius, float fade) { if(!showblobs) return; if(refracting < 0 && o.z - blobheight - blobfadelow >= reflectz) return; blobs[type].renderblob(o, radius + blobmargin, fade); } void flushblobs() { if(blobrenderer::lastrender) blobrenderer::cleanuprenderstate(); blobrenderer::lastrender = NULL; } sandboxgamemaker-2.7.1+dfsg/src/engine/glare.cpp0000664000175000017500000000246511400572336021514 0ustar showardshoward#include "engine.h" #include "rendertarget.h" static struct glaretexture : rendertarget { bool dorender() { extern void drawglare(); drawglare(); return true; } } glaretex; void cleanupglare() { glaretex.cleanup(true); } VARFP(glaresize, 6, 8, 10, cleanupglare()); VARP(glare, 0, 0, 1); VARP(blurglare, 0, 4, 7); VARP(blurglaresigma, 1, 50, 200); VAR(debugglare, 0, 0, 1); void viewglaretex() { if(!glare) return; glaretex.debug(); } bool glaring = false; void drawglaretex() { if(!glare || renderpath==R_FIXEDFUNCTION) return; glaretex.render(1< grassverts; struct grassgroup { const grasstri *tri; float dist; int tex, lmtex, offset, numquads; }; static vector grassgroups; #define NUMGRASSOFFSETS 32 static float grassoffsets[NUMGRASSOFFSETS] = { -1 }, grassanimoffsets[NUMGRASSOFFSETS]; static int lastgrassanim = -1; VARR(grassanimmillis, 0, 3000, 60000); FVARR(grassanimscale, 0, 0.03f, 1); static void animategrass() { loopi(NUMGRASSOFFSETS) grassanimoffsets[i] = grassanimscale*sinf(2*M_PI*(grassoffsets[i] + lastmillis/float(grassanimmillis))); lastgrassanim = lastmillis; } VARR(grassscale, 1, 2, 64); bvec grasscolor(255, 255, 255); HVARFR(grasscolour, 0, 0xFFFFFF, 0xFFFFFF, { if(!grasscolour) grasscolour = 0xFFFFFF; grasscolor = bvec((grasscolour>>16)&0xFF, (grasscolour>>8)&0xFF, grasscolour&0xFF); }); FVARR(grassalpha, 0, 1, 1); static void gengrassquads(grassgroup *&group, const grasswedge &w, const grasstri &g, Texture *tex) { float t = camera1->o.dot(w.dir); int tstep = int(ceil(t/grassstep)); float tstart = tstep*grassstep, t0 = w.dir.dot(g.v[0]), t1 = w.dir.dot(g.v[1]), t2 = w.dir.dot(g.v[2]), t3 = w.dir.dot(g.v[3]), tmin = min(min(t0, t1), min(t2, t3)), tmax = max(max(t0, t1), max(t2, t3)); if(tmax < tstart || tmin > t + grassdist) return; int minstep = max(int(ceil(tmin/grassstep)) - tstep, 1), maxstep = int(floor(min(tmax, t + grassdist)/grassstep)) - tstep, numsteps = maxstep - minstep + 1; float texscale = (grassscale*tex->ys)/float(grassheight*tex->xs), animscale = grassheight*texscale; vec tc; tc.cross(g.surface, w.dir).mul(texscale); int color = tstep + maxstep; if(color < 0) color = NUMGRASSOFFSETS - (-color)%NUMGRASSOFFSETS; color += numsteps + NUMGRASSOFFSETS - numsteps%NUMGRASSOFFSETS; float leftdist = t0; const vec *leftv = &g.v[0]; if(t1 > leftdist) { leftv = &g.v[1]; leftdist = t1; } if(t2 > leftdist) { leftv = &g.v[2]; leftdist = t2; } if(t3 > leftdist) { leftv = &g.v[3]; leftdist = t3; } float rightdist = leftdist; const vec *rightv = leftv; vec across(w.across.x, w.across.y, g.surface.zdelta(w.across)), leftdir(0, 0, 0), rightdir(0, 0, 0), leftp = *leftv, rightp = *rightv; float taperdist = grassdist*grasstaper, taperscale = 1.0f / (grassdist - taperdist), dist = maxstep*grassstep + tstart, leftb = 0, rightb = 0, leftdb = 0, rightdb = 0; for(int i = maxstep; i >= minstep; i--, color--, leftp.add(leftdir), rightp.add(rightdir), leftb += leftdb, rightb += rightdb, dist -= grassstep) { if(dist <= leftdist) { const vec *prev = leftv; float prevdist = leftdist; if(--leftv < g.v) leftv += g.numv; leftdist = leftv->dot(w.dir); if(dist <= leftdist) { prev = leftv; prevdist = leftdist; if(--leftv < g.v) leftv += g.numv; leftdist = leftv->dot(w.dir); } leftdir = vec(*leftv).sub(*prev); leftdir.mul(grassstep/-w.dir.dot(leftdir)); leftp = vec(leftdir).mul((prevdist - dist)/grassstep).add(*prev); leftb = w.bound1.dist(leftp); leftdb = w.bound1.dot(leftdir); } if(dist <= rightdist) { const vec *prev = rightv; float prevdist = rightdist; if(++rightv >= &g.v[g.numv]) rightv = g.v; rightdist = rightv->dot(w.dir); if(dist <= rightdist) { prev = rightv; prevdist = rightdist; if(++rightv >= &g.v[g.numv]) rightv = g.v; rightdist = rightv->dot(w.dir); } rightdir = vec(*rightv).sub(*prev); rightdir.mul(grassstep/-w.dir.dot(rightdir)); rightp = vec(rightdir).mul((prevdist - dist)/grassstep).add(*prev); rightb = w.bound2.dist(rightp); rightdb = w.bound2.dot(rightdir); } vec p1 = leftp, p2 = rightp; if(leftb > 0) { if(w.bound1.dist(p2) >= 0) continue; p1.add(vec(across).mul(leftb)); } if(rightb > 0) { if(w.bound2.dist(p1) >= 0) continue; p2.sub(vec(across).mul(rightb)); } if(!group) { group = &grassgroups.add(); group->tri = &g; group->tex = tex->id; group->lmtex = lightmaptexs.inrange(g.lmid) ? lightmaptexs[g.lmid].id : notexture->id; group->offset = grassverts.length(); group->numquads = 0; if(lastgrassanim!=lastmillis) animategrass(); } group->numquads++; float offset = grassoffsets[color%NUMGRASSOFFSETS], animoffset = animscale*grassanimoffsets[color%NUMGRASSOFFSETS], tc1 = tc.dot(p1) + offset, tc2 = tc.dot(p2) + offset, lm1u = g.tcu.dot(p1), lm1v = g.tcv.dot(p1), lm2u = g.tcu.dot(p2), lm2v = g.tcv.dot(p2), fade = dist - t > taperdist ? (grassdist - (dist - t))*taperscale : 1, height = grassheight * fade; uchar color[4] = { grasscolor.x, grasscolor.y, grasscolor.z, uchar(fade*grassalpha*255) }; #define GRASSVERT(n, tcv, modify) { \ grassvert &gv = grassverts.add(); \ gv.pos = p##n; \ memcpy(gv.color, color, sizeof(color)); \ gv.u = tc##n; gv.v = tcv; \ gv.lmu = lm##n##u; gv.lmv = lm##n##v; \ modify; \ } GRASSVERT(2, 0, { gv.pos.z += height; gv.u += animoffset; }); GRASSVERT(1, 0, { gv.pos.z += height; gv.u += animoffset; }); GRASSVERT(1, 1, ); GRASSVERT(2, 1, ); } } static void gengrassquads(vtxarray *va) { loopv(va->grasstris) { grasstri &g = va->grasstris[i]; if(isfoggedsphere(g.radius, g.center)) continue; float dist = g.center.dist(camera1->o); if(dist - g.radius > grassdist) continue; Slot &s = *lookupvslot(g.texture, false).slot; if(!s.grasstex) { if(!s.autograss) continue; s.grasstex = textureload(s.autograss, 2); } grassgroup *group = NULL; loopi(NUMGRASSWEDGES) { grasswedge &w = grasswedges[i]; if(w.bound1.dist(g.center) > g.radius || w.bound2.dist(g.center) > g.radius) continue; gengrassquads(group, w, g, s.grasstex); } if(group) group->dist = dist; } } static inline bool comparegrassgroups(const grassgroup &x, const grassgroup &y) { return x.dist > y.dist; } void generategrass() { if(!grass || !grassdist) return; grassgroups.setsize(0); grassverts.setsize(0); if(grassoffsets[0] < 0) loopi(NUMGRASSOFFSETS) grassoffsets[i] = rnd(0x1000000)/float(0x1000000); loopi(NUMGRASSWEDGES) { grasswedge &w = grasswedges[i]; w.bound1.offset = -camera1->o.dot(w.bound1); w.bound2.offset = -camera1->o.dot(w.bound2); } extern vtxarray *visibleva; for(vtxarray *va = visibleva; va; va = va->next) { if(va->grasstris.empty() || va->occluded >= OCCLUDE_GEOM) continue; if(va->distance > grassdist) continue; if(reflecting || refracting>0 ? va->o.z+va->sizeo.z>=reflectz) continue; gengrassquads(va); } grassgroups.sort(comparegrassgroups); } void rendergrass() { if(!grass || !grassdist || grassgroups.empty() || dbggrass) return; glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(renderpath==R_FIXEDFUNCTION ? GL_SRC_ALPHA : GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(GL_FALSE); SETSHADER(grass); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(grassvert), grassverts[0].pos.v); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(grassvert), grassverts[0].color); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(grassvert), &grassverts[0].u); if(renderpath!=R_FIXEDFUNCTION || maxtmus>=2) { glActiveTexture_(GL_TEXTURE1_ARB); glClientActiveTexture_(GL_TEXTURE1_ARB); glEnable(GL_TEXTURE_2D); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(grassvert), &grassverts[0].lmu); if(renderpath==R_FIXEDFUNCTION) setuptmu(1, "P * T x 2"); glClientActiveTexture_(GL_TEXTURE0_ARB); glActiveTexture_(GL_TEXTURE0_ARB); } int texid = -1, lmtexid = -1; loopv(grassgroups) { grassgroup &g = grassgroups[i]; if(reflecting || refracting) { if(refracting < 0 ? g.tri->minz > reflectz : g.tri->maxz + grassheight < reflectz) continue; if(isfoggedsphere(g.tri->radius, g.tri->center)) continue; } if(texid != g.tex) { glBindTexture(GL_TEXTURE_2D, g.tex); texid = g.tex; } if(lmtexid != g.lmtex) { if(renderpath!=R_FIXEDFUNCTION || maxtmus>=2) { glActiveTexture_(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, g.lmtex); glActiveTexture_(GL_TEXTURE0_ARB); } lmtexid = g.lmtex; } glDrawArrays(GL_QUADS, g.offset, 4*g.numquads); xtravertsva += 4*g.numquads; } glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); if(renderpath!=R_FIXEDFUNCTION || maxtmus>=2) { glActiveTexture_(GL_TEXTURE1_ARB); glClientActiveTexture_(GL_TEXTURE1_ARB); if(renderpath==R_FIXEDFUNCTION) resettmu(1); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_2D); glClientActiveTexture_(GL_TEXTURE0_ARB); glActiveTexture_(GL_TEXTURE0_ARB); } glDisable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_CULL_FACE); } sandboxgamemaker-2.7.1+dfsg/src/engine/renderparticles.cpp0000664000175000017500000016253111460063014023603 0ustar showardshoward// renderparticles.cpp #include "engine.h" #include "rendertarget.h" Shader *particleshader = NULL, *particlenotextureshader = NULL; VARP(particlesize, 20, 100, 500); // Check emit_particles() to limit the rate that paricles can be emitted for models/sparklies // Automatically stops particles being emitted when paused or in reflective drawing VARP(emitmillis, 1, 17, 1000); static int lastemitframe = 0, emitoffset = 0; static bool canemit = false, regenemitters = false, canstep = false; static bool emit_particles() { if(reflecting || refracting) return false; return canemit || emitoffset; } VAR(dbgpseed, 0, 0, 1); struct particleemitter { extentity *ent; vec bbmin, bbmax; vec center; float radius; ivec bborigin, bbsize; int maxfade, lastemit, lastcull; particleemitter(extentity *ent) : ent(ent), bbmin(ent->o), bbmax(ent->o), maxfade(-1), lastemit(0), lastcull(0) {} void finalize() { center = vec(bbmin).add(bbmax).mul(0.5f); radius = bbmin.dist(bbmax)/2; bborigin = ivec(int(floor(bbmin.x)), int(floor(bbmin.y)), int(floor(bbmin.z))); bbsize = ivec(int(ceil(bbmax.x)), int(ceil(bbmax.y)), int(ceil(bbmax.z))).sub(bborigin); if(dbgpseed) conoutf(CON_DEBUG, "radius: %f, maxfade: %d", radius, maxfade); } void extendbb(const vec &o, float size = 0) { bbmin.x = min(bbmin.x, o.x - size); bbmin.y = min(bbmin.y, o.y - size); bbmin.z = min(bbmin.z, o.z - size); bbmax.x = max(bbmax.x, o.x + size); bbmax.y = max(bbmax.y, o.y + size); bbmax.z = max(bbmax.z, o.z + size); } void extendbb(float z, float size = 0) { bbmin.z = min(bbmin.z, z - size); bbmax.z = max(bbmax.z, z + size); } }; static vector emitters; static particleemitter *seedemitter = NULL; void clearparticleemitters() { emitters.shrink(0); regenemitters = true; } void addparticleemitters() { emitters.shrink(0); const vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; if(e.type != ET_PARTICLES) continue; emitters.add(particleemitter(&e)); } regenemitters = false; } enum { PT_PART = 0, PT_TAPE, PT_TRAIL, PT_TEXT, PT_TEXTUP, PT_METER, PT_METERVS, PT_FIREBALL, PT_LIGHTNING, PT_FLARE, PT_MOD = 1<<8, PT_RND4 = 1<<9, PT_LERP = 1<<10, // use very sparingly - order of blending issues PT_TRACK = 1<<11, PT_GLARE = 1<<12, PT_SOFT = 1<<13, PT_HFLIP = 1<<14, PT_VFLIP = 1<<15, PT_ROT = 1<<16, PT_CULL = 1<<17, PT_ICON = 1<<18, PT_FLIP = PT_HFLIP | PT_VFLIP | PT_ROT }; const char *partnames[] = { "part", "tape", "trail", "text", "textup", "meter", "metervs", "fireball", "lightning", "flare" }; struct particle { vec o, d; int gravity, fade, millis; bvec color; uchar flags; float size; union { const char *text; // will call delete[] on this only if it starts with an @ float val; physent *owner; struct { uchar color2[3]; uchar progress; }; }; }; struct partvert { vec pos; float u, v; bvec color; uchar alpha; }; #define COLLIDERADIUS 8.0f #define COLLIDEERROR 1.0f struct partrenderer { Texture *tex; const char *texname; int texclamp; uint type; int collide; partrenderer(const char *texname, int texclamp, int type, int collide = 0) : tex(NULL), texname(texname), texclamp(texclamp), type(type), collide(collide) { } partrenderer(int type, int collide = 0) : tex(NULL), texname(NULL), texclamp(0), type(type), collide(collide) { } virtual ~partrenderer() { } virtual void init(int n) { } virtual void reset() = 0; virtual void resettracked(physent *owner) { } virtual particle *addpart(const vec &o, const vec &d, int fade, int color, float size, int gravity = 0) = 0; virtual int adddepthfx(vec &bbmin, vec &bbmax) { return 0; } virtual void update() { } virtual void render() = 0; virtual bool haswork() = 0; virtual int count() = 0; //for debug virtual bool usesvertexarray() { return false; } virtual void cleanup() {} virtual void seedemitter(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int gravity) { } //blend = 0 => remove it void calc(particle *p, int &blend, int &ts, vec &o, vec &d, bool step = true) { o = p->o; d = p->d; if(type&PT_TRACK && p->owner) game::particletrack(p->owner, o, d); if(p->fade <= 5) { ts = 1; blend = 255; } else { ts = lastmillis-p->millis; blend = max(255 - (ts<<8)/p->fade, 0); if(p->gravity) { if(ts > p->fade) ts = p->fade; float t = ts; o.add(vec(d).mul(t/5000.0f)); o.z -= t*t/(2.0f * 5000.0f * p->gravity); } if(collide && o.z < p->val && step) { vec surface; float floorz = rayfloor(vec(o.x, o.y, p->val), surface, RAY_CLIPMAT, COLLIDERADIUS); float collidez = floorz<0 ? o.z-COLLIDERADIUS : p->val - rayfloor(vec(o.x, o.y, p->val), surface, RAY_CLIPMAT, COLLIDERADIUS); if(o.z >= collidez+COLLIDEERROR) p->val = collidez+COLLIDEERROR; else { adddecal(collide, vec(o.x, o.y, collidez), vec(p->o).sub(o).normalize(), 2*p->size, p->color, type&PT_RND4 ? (p->flags>>5)&3 : 0); blend = 0; } } } } }; struct listparticle : particle { listparticle *next; }; VARP(outlinemeters, 0, 0, 1); struct listrenderer : partrenderer { static listparticle *parempty; listparticle *list; listrenderer(const char *texname, int texclamp, int type, int collide = 0) : partrenderer(texname, texclamp, type, collide), list(NULL) { } listrenderer(int type, int collide = 0) : partrenderer(type, collide), list(NULL) { } virtual ~listrenderer() { } virtual void cleanup(listparticle *p) { } void reset() { if(!list) return; listparticle *p = list; for(;;) { cleanup(p); if(p->next) p = p->next; else break; } p->next = parempty; parempty = list; list = NULL; } void resettracked(physent *owner) { if(!(type&PT_TRACK)) return; for(listparticle **prev = &list, *cur = list; cur; cur = *prev) { if(!owner || cur->owner==owner) { *prev = cur->next; cur->next = parempty; parempty = cur; } else prev = &cur->next; } } particle *addpart(const vec &o, const vec &d, int fade, int color, float size, int gravity) { if(!parempty) { listparticle *ps = new listparticle[256]; loopi(255) ps[i].next = &ps[i+1]; ps[255].next = parempty; parempty = ps; } listparticle *p = parempty; parempty = p->next; p->next = list; list = p; p->o = o; p->d = d; p->gravity = gravity; p->fade = fade; p->millis = lastmillis + emitoffset; p->color = bvec(color>>16, (color>>8)&0xFF, color&0xFF); p->size = size; p->owner = NULL; p->flags = 0; return p; } int count() { int num = 0; listparticle *lp; for(lp = list; lp; lp = lp->next) num++; return num; } bool haswork() { return (list != NULL); } virtual void startrender() = 0; virtual void endrender() = 0; virtual void renderpart(listparticle *p, const vec &o, const vec &d, int blend, int ts, uchar *color) = 0; void render() { startrender(); if(texname) { if(!tex) tex = textureload(texname, texclamp); glBindTexture(GL_TEXTURE_2D, tex->id); } for(listparticle **prev = &list, *p = list; p; p = *prev) { vec o, d; int blend, ts; calc(p, blend, ts, o, d, canstep); if(blend > 0) { renderpart(p, o, d, blend, ts, p->color.v); if(p->fade > 5 || !canstep) { prev = &p->next; continue; } } //remove *prev = p->next; p->next = parempty; cleanup(p); parempty = p; } endrender(); } }; listparticle *listrenderer::parempty = NULL; struct meterrenderer : listrenderer { meterrenderer(int type) : listrenderer(type) {} void startrender() { glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); particlenotextureshader->set(); } void endrender() { glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); particleshader->set(); } void renderpart(listparticle *p, const vec &o, const vec &d, int blend, int ts, uchar *color) { int basetype = type&0xFF; glPushMatrix(); glTranslatef(o.x, o.y, o.z); glRotatef(camera1->yaw, 0, 0, 1); glRotatef(camera1->pitch-90, 1, 0, 0); float scale = p->size/80.0f; glScalef(-scale, scale, -scale); float right = 8*FONTH, left = p->progress/100.0f*right; glTranslatef(-right/2.0f, 0, 0); if(outlinemeters) { glColor3f(0, 0.8f, 0); glBegin(GL_TRIANGLE_STRIP); loopk(10) { float c = (0.5f + 0.1f)*sinf(k/9.0f*M_PI), s = 0.5f - (0.5f + 0.1f)*cosf(k/9.0f*M_PI); glVertex2f(-c*FONTH, s*FONTH); glVertex2f(right + c*FONTH, s*FONTH); } glEnd(); } if(basetype==PT_METERVS) glColor3ubv(p->color2); else glColor3f(0, 0, 0); glBegin(GL_TRIANGLE_STRIP); loopk(10) { float c = 0.5f*sinf(k/9.0f*M_PI), s = 0.5f - 0.5f*cosf(k/9.0f*M_PI); glVertex2f(left + c*FONTH, s*FONTH); glVertex2f(right + c*FONTH, s*FONTH); } glEnd(); if(outlinemeters) { glColor3f(0, 0.8f, 0); glBegin(GL_TRIANGLE_FAN); loopk(10) { float c = (0.5f + 0.1f)*sinf(k/9.0f*M_PI), s = 0.5f - (0.5f + 0.1f)*cosf(k/9.0f*M_PI); glVertex2f(left + c*FONTH, s*FONTH); } glEnd(); } glColor3ubv(color); glBegin(GL_TRIANGLE_STRIP); loopk(10) { float c = 0.5f*sinf(k/9.0f*M_PI), s = 0.5f - 0.5f*cosf(k/9.0f*M_PI); glVertex2f(-c*FONTH, s*FONTH); glVertex2f(left + c*FONTH, s*FONTH); } glEnd(); glPopMatrix(); } }; static meterrenderer meters(PT_METER|PT_LERP), metervs(PT_METERVS|PT_LERP); struct textrenderer : listrenderer { textrenderer(int type) : listrenderer(type) {} void startrender() { } void endrender() { } void cleanup(listparticle *p) { if(p->text && p->flags&1) delete[] p->text; } void renderpart(listparticle *p, const vec &o, const vec &d, int blend, int ts, uchar *color) { glPushMatrix(); glTranslatef(o.x, o.y, o.z); glRotatef(camera1->yaw, 0, 0, 1); glRotatef(camera1->pitch-90, 1, 0, 0); float scale = p->size/80.0f; glScalef(-scale, scale, -scale); float xoff = -text_width(p->text)/2; float yoff = 0; if((type&0xFF)==PT_TEXTUP) { xoff += detrnd((size_t)p, 100)-50; yoff -= detrnd((size_t)p, 101); } //@TODO instead in worldspace beforehand? glTranslatef(xoff, yoff, 50); draw_text(p->text, 0, 0, color[0], color[1], color[2], blend); glPopMatrix(); } }; static textrenderer texts(PT_TEXT|PT_LERP); template static inline void modifyblend(const vec &o, int &blend) { blend = min(blend<<2, 255); } template<> inline void modifyblend(const vec &o, int &blend) { } template static inline void genpos(const vec &o, const vec &d, float size, int grav, int ts, partvert *vs) { vec udir = vec(camup).sub(camright).mul(size); vec vdir = vec(camup).add(camright).mul(size); vs[0].pos = vec(o.x + udir.x, o.y + udir.y, o.z + udir.z); vs[1].pos = vec(o.x + vdir.x, o.y + vdir.y, o.z + vdir.z); vs[2].pos = vec(o.x - udir.x, o.y - udir.y, o.z - udir.z); vs[3].pos = vec(o.x - vdir.x, o.y - vdir.y, o.z - vdir.z); } template<> inline void genpos(const vec &o, const vec &d, float size, int ts, int grav, partvert *vs) { vec dir1 = d, dir2 = d, c; dir1.sub(o); dir2.sub(camera1->o); c.cross(dir2, dir1).normalize().mul(size); vs[0].pos = vec(d.x-c.x, d.y-c.y, d.z-c.z); vs[1].pos = vec(o.x-c.x, o.y-c.y, o.z-c.z); vs[2].pos = vec(o.x+c.x, o.y+c.y, o.z+c.z); vs[3].pos = vec(d.x+c.x, d.y+c.y, d.z+c.z); } template<> inline void genpos(const vec &o, const vec &d, float size, int ts, int grav, partvert *vs) { vec e = d; if(grav) e.z -= float(ts)/grav; e.div(-75.0f).add(o); genpos(o, e, size, ts, grav, vs); } template static inline void genrotpos(const vec &o, const vec &d, float size, int grav, int ts, partvert *vs, int rot) { genpos(o, d, size, grav, ts, vs); } #define ROTCOEFFS(n) { \ vec(-1, 1, 0).rotate_around_z(n*2*M_PI/32.0f), \ vec( 1, 1, 0).rotate_around_z(n*2*M_PI/32.0f), \ vec( 1, -1, 0).rotate_around_z(n*2*M_PI/32.0f), \ vec(-1, -1, 0).rotate_around_z(n*2*M_PI/32.0f) \ } static const vec rotcoeffs[32][4] = { ROTCOEFFS(0), ROTCOEFFS(1), ROTCOEFFS(2), ROTCOEFFS(3), ROTCOEFFS(4), ROTCOEFFS(5), ROTCOEFFS(6), ROTCOEFFS(7), ROTCOEFFS(8), ROTCOEFFS(9), ROTCOEFFS(10), ROTCOEFFS(11), ROTCOEFFS(12), ROTCOEFFS(13), ROTCOEFFS(14), ROTCOEFFS(15), ROTCOEFFS(16), ROTCOEFFS(17), ROTCOEFFS(18), ROTCOEFFS(19), ROTCOEFFS(20), ROTCOEFFS(21), ROTCOEFFS(22), ROTCOEFFS(7), ROTCOEFFS(24), ROTCOEFFS(25), ROTCOEFFS(26), ROTCOEFFS(27), ROTCOEFFS(28), ROTCOEFFS(29), ROTCOEFFS(30), ROTCOEFFS(31), }; template<> inline void genrotpos(const vec &o, const vec &d, float size, int grav, int ts, partvert *vs, int rot) { const vec *coeffs = rotcoeffs[rot]; (vs[0].pos = o).add(vec(camright).mul(coeffs[0].x*size)).add(vec(camup).mul(coeffs[0].y*size)); (vs[1].pos = o).add(vec(camright).mul(coeffs[1].x*size)).add(vec(camup).mul(coeffs[1].y*size)); (vs[2].pos = o).add(vec(camright).mul(coeffs[2].x*size)).add(vec(camup).mul(coeffs[2].y*size)); (vs[3].pos = o).add(vec(camright).mul(coeffs[3].x*size)).add(vec(camup).mul(coeffs[3].y*size)); } template static inline void seedpos(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int grav) { if(grav) { vec end(o); float t = fade; end.add(vec(d).mul(t/5000.0f)); end.z -= t*t/(2.0f * 5000.0f * grav); pe.extendbb(end, size); float tpeak = d.z*grav; if(tpeak > 0 && tpeak < fade) pe.extendbb(o.z + 1.5f*d.z*tpeak/5000.0f, size); } } template<> inline void seedpos(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int grav) { pe.extendbb(d, size); } template<> inline void seedpos(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int grav) { vec e = d; if(grav) e.z -= float(fade)/grav; e.div(-75.0f).add(o); pe.extendbb(e, size); } template struct varenderer : partrenderer { partvert *verts; particle *parts; int maxparts, numparts, lastupdate, rndmask; varenderer(const char *texname, int type, int collide = 0) : partrenderer(texname, 3, type, collide), verts(NULL), parts(NULL), maxparts(0), numparts(0), lastupdate(-1), rndmask(0) { if(type & PT_HFLIP) rndmask |= 0x01; if(type & PT_VFLIP) rndmask |= 0x02; if(type & PT_ROT) rndmask |= 0x1F<<2; if(type & PT_RND4) rndmask |= 0x03<<5; } void init(int n) { DELETEA(parts); DELETEA(verts); parts = new particle[n]; verts = new partvert[n*4]; maxparts = n; numparts = 0; lastupdate = -1; } void reset() { numparts = 0; lastupdate = -1; } void resettracked(physent *owner) { if(!(type&PT_TRACK)) return; loopi(numparts) { particle *p = parts+i; if(!owner || (p->owner == owner)) p->fade = -1; } lastupdate = -1; } int count() { return numparts; } bool haswork() { return (numparts > 0); } bool usesvertexarray() { return true; } particle *addpart(const vec &o, const vec &d, int fade, int color, float size, int gravity) { particle *p = parts + (numparts < maxparts ? numparts++ : rnd(maxparts)); //next free slot, or kill a random kitten p->o = o; p->d = d; p->gravity = gravity; p->fade = fade; p->millis = lastmillis + emitoffset; p->color = bvec(color>>16, (color>>8)&0xFF, color&0xFF); p->size = size; p->owner = NULL; p->flags = 0x80 | (rndmask ? rnd(0x80) & rndmask : 0); lastupdate = -1; return p; } void seedemitter(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int gravity) { pe.maxfade = max(pe.maxfade, fade); size *= SQRT2; pe.extendbb(o, size); seedpos(pe, o, d, fade, size, gravity); if(!gravity) return; vec end(o); float t = fade; end.add(vec(d).mul(t/5000.0f)); end.z -= t*t/(2.0f * 5000.0f * gravity); pe.extendbb(end, size); float tpeak = d.z*gravity; if(tpeak > 0 && tpeak < fade) pe.extendbb(o.z + 1.5f*d.z*tpeak/5000.0f, size); } void genverts(particle *p, partvert *vs, bool regen) { vec o, d; int blend, ts; calc(p, blend, ts, o, d); if(blend <= 1 || p->fade <= 5) p->fade = -1; //mark to remove on next pass (i.e. after render) modifyblend(o, blend); if(regen) { p->flags &= ~0x80; #define SETTEXCOORDS(u1c, u2c, v1c, v2c, body) \ { \ float u1 = u1c, u2 = u2c, v1 = v1c, v2 = v2c; \ body; \ vs[0].u = u1; \ vs[0].v = v1; \ vs[1].u = u2; \ vs[1].v = v1; \ vs[2].u = u2; \ vs[2].v = v2; \ vs[3].u = u1; \ vs[3].v = v2; \ } if(type&PT_RND4) { float tx = 0.5f*((p->flags>>5)&1), ty = 0.5f*((p->flags>>6)&1); SETTEXCOORDS(tx, tx + 0.5f, ty, ty + 0.5f, { if(p->flags&0x01) swap(u1, u2); if(p->flags&0x02) swap(v1, v2); }); } else if(type&PT_ICON) { float tx = 0.25f*(p->flags&3), ty = 0.25f*((p->flags>>2)&3); SETTEXCOORDS(tx, tx + 0.25f, ty, ty + 0.25f, {}); } else SETTEXCOORDS(0, 1, 0, 1, {}); #define SETCOLOR(r, g, b, a) \ do { \ uchar col[4] = { r, g, b, a }; \ loopi(4) memcpy(vs[i].color.v, col, sizeof(col)); \ } while(0) #define SETMODCOLOR SETCOLOR((p->color[0]*blend)>>8, (p->color[1]*blend)>>8, (p->color[2]*blend)>>8, 255) if(type&PT_MOD) SETMODCOLOR; else SETCOLOR(p->color[0], p->color[1], p->color[2], blend); } else if(type&PT_MOD) SETMODCOLOR; else loopi(4) vs[i].alpha = blend; if(type&PT_ROT) genrotpos(o, d, p->size, ts, p->gravity, vs, (p->flags>>2)&0x1F); else genpos(o, d, p->size, ts, p->gravity, vs); } void update() { if(lastmillis == lastupdate) return; lastupdate = lastmillis; loopi(numparts) { particle *p = &parts[i]; partvert *vs = &verts[i*4]; if(p->fade < 0) { do { --numparts; if(numparts <= i) return; } while(parts[numparts].fade < 0); *p = parts[numparts]; genverts(p, vs, true); } else genverts(p, vs, (p->flags&0x80)!=0); } } void render() { if(!tex) tex = textureload(texname, texclamp); glBindTexture(GL_TEXTURE_2D, tex->id); glVertexPointer(3, GL_FLOAT, sizeof(partvert), &verts->pos); glTexCoordPointer(2, GL_FLOAT, sizeof(partvert), &verts->u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(partvert), &verts->color); glDrawArrays(GL_QUADS, 0, numparts*4); } }; typedef varenderer quadrenderer; typedef varenderer taperenderer; typedef varenderer trailrenderer; #include "depthfx.h" #include "explosion.h" #include "lensflare.h" #include "lightning.h" struct softquadrenderer : quadrenderer { softquadrenderer(const char *texname, int type, int collide = 0) : quadrenderer(texname, type|PT_SOFT, collide) { } int adddepthfx(vec &bbmin, vec &bbmax) { if(!depthfxtex.highprecision() && !depthfxtex.emulatehighprecision()) return 0; int numsoft = 0; loopi(numparts) { particle &p = parts[i]; float radius = p.size*SQRT2; vec o, d; int blend, ts; calc(&p, blend, ts, o, d, false); if(!isfoggedsphere(radius, p.o) && (depthfxscissor!=2 || depthfxtex.addscissorbox(p.o, radius))) { numsoft++; loopk(3) { bbmin[k] = min(bbmin[k], o[k] - radius); bbmax[k] = max(bbmax[k], o[k] + radius); } } } return numsoft; } }; static partrenderer *parts[] = { new quadrenderer("data/items", PT_PART|PT_FLIP|PT_MOD|PT_RND4, 1), // blood spats (note: rgb is inverted) new trailrenderer("packages/particles/base", PT_TRAIL|PT_LERP, DECAL_RIPPLE), // water, entity new quadrenderer("packages/particles/smoke", PT_PART|PT_FLIP|PT_LERP), // smoke new quadrenderer("packages/particles/steam", PT_PART|PT_FLIP), // steam new quadrenderer("packages/particles/flames", PT_PART|PT_HFLIP|PT_RND4|PT_GLARE), // flames new quadrenderer("packages/particles/ball1", PT_PART|PT_GLARE), // fireball1 new quadrenderer("packages/particles/ball2", PT_PART|PT_GLARE), // fireball2 new quadrenderer("packages/particles/ball3", PT_PART|PT_GLARE), // fireball3 new taperenderer("packages/particles/flare", PT_TAPE|PT_GLARE), // streak &lightnings, // lightning &fireballs, // explosion fireball &bluefireballs, // bluish explosion fireball new quadrenderer("packages/particles/spark", PT_PART|PT_FLIP|PT_GLARE), // sparks new quadrenderer("packages/particles/base", PT_PART|PT_FLIP|PT_GLARE), // edit mode entities new quadrenderer("packages/particles/muzzleflash1", PT_PART|PT_FLIP|PT_GLARE|PT_TRACK), // muzzle flash new quadrenderer("packages/particles/muzzleflash2", PT_PART|PT_FLIP|PT_GLARE|PT_TRACK), // muzzle flash new quadrenderer("packages/particles/muzzleflash3", PT_PART|PT_FLIP|PT_GLARE|PT_TRACK), // muzzle flash new quadrenderer("data/items.png", PT_PART|PT_ICON), // hud icon new quadrenderer("data/items.png", PT_PART|PT_ICON), // grey hud icon &texts, // text &meters, // meter &metervs, // meter vs new quadrenderer("packages/particles/snow", PT_PART|PT_GLARE|PT_RND4|PT_FLIP, DECAL_STAIN), // snow new quadrenderer("packages/particles/leaves", PT_PART|PT_RND4|PT_FLIP|PT_LERP, DECAL_LEAVES), //leaves &flares // must be done last }; void finddepthfxranges() { depthfxmin = vec(1e16f, 1e16f, 1e16f); depthfxmax = vec(0, 0, 0); numdepthfxranges = fireballs.finddepthfxranges(depthfxowners, depthfxranges, 0, MAXDFXRANGES, depthfxmin, depthfxmax); numdepthfxranges = bluefireballs.finddepthfxranges(depthfxowners, depthfxranges, numdepthfxranges, MAXDFXRANGES, depthfxmin, depthfxmax); loopk(3) { depthfxmin[k] -= depthfxmargin; depthfxmax[k] += depthfxmargin; } if(depthfxparts) { loopi(sizeof(parts)/sizeof(parts[0])) { partrenderer *p = parts[i]; if(p->type&PT_SOFT && p->adddepthfx(depthfxmin, depthfxmax)) { if(!numdepthfxranges) { numdepthfxranges = 1; depthfxowners[0] = NULL; depthfxranges[0] = 0; } } } } if(depthfxscissor<2 && numdepthfxranges>0) depthfxtex.addscissorbox(depthfxmin, depthfxmax); } VARFP(maxparticles, 10, 8000, 40000, particleinit()); void particleinit() { if(!particleshader) particleshader = lookupshaderbyname("particle"); if(!particlenotextureshader) particlenotextureshader = lookupshaderbyname("particlenotexture"); loopi(sizeof(parts)/sizeof(parts[0])) parts[i]->init(maxparticles); } void clearparticles() { loopi(sizeof(parts)/sizeof(parts[0])) parts[i]->reset(); clearparticleemitters(); } void cleanupparticles() { loopi(sizeof(parts)/sizeof(parts[0])) parts[i]->cleanup(); } void removetrackedparticles(physent *owner) { loopi(sizeof(parts)/sizeof(parts[0])) parts[i]->resettracked(owner); } VARP(particleglare, 0, 2, 100); VAR(debugparticles, 0, 0, 1); void renderparticles(bool mainpass) { canstep = mainpass; //want to debug BEFORE the lastpass render (that would delete particles) if(debugparticles && !glaring && !reflecting && !refracting) { int n = sizeof(parts)/sizeof(parts[0]); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, FONTH*n*2*screen->w/float(screen->h), FONTH*n*2, 0, -1, 1); //squeeze into top-left corner glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); defaultshader->set(); loopi(n) { int type = parts[i]->type; const char *title = parts[i]->texname ? strrchr(parts[i]->texname, '/')+1 : NULL; string info = ""; if(type&PT_GLARE) concatstring(info, "g,"); if(type&PT_LERP) concatstring(info, "l,"); if(type&PT_MOD) concatstring(info, "m,"); if(type&PT_RND4) concatstring(info, "r,"); if(type&PT_TRACK) concatstring(info, "t,"); if(type&PT_FLIP) concatstring(info, "f,"); if(parts[i]->collide) concatstring(info, "c,"); if(info[0]) info[strlen(info)-1] = '\0'; defformatstring(ds)("%d\t%s(%s) %s", parts[i]->count(), partnames[type&0xFF], info, title ? title : ""); draw_text(ds, FONTH, (i+n/2)*FONTH); } glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } if(glaring && !particleglare) return; loopi(sizeof(parts)/sizeof(parts[0])) { if(glaring && !(parts[i]->type&PT_GLARE)) continue; parts[i]->update(); } static float zerofog[4] = { 0, 0, 0, 1 }; float oldfogc[4]; bool rendered = false; uint lastflags = PT_LERP, flagmask = PT_LERP|PT_MOD; if(binddepthfxtex()) flagmask |= PT_SOFT; loopi(sizeof(parts)/sizeof(parts[0])) { partrenderer *p = parts[i]; if(glaring && !(p->type&PT_GLARE)) continue; if(!p->haswork()) continue; if(!rendered) { rendered = true; glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(glaring) setenvparamf("colorscale", SHPARAM_VERTEX, 4, particleglare, particleglare, particleglare, 1); else setenvparamf("colorscale", SHPARAM_VERTEX, 4, 1, 1, 1, 1); particleshader->set(); glGetFloatv(GL_FOG_COLOR, oldfogc); } uint flags = p->type & flagmask; if(p->usesvertexarray()) flags |= 0x01; //0x01 = VA marker uint changedbits = (flags ^ lastflags); if(changedbits != 0x0000) { if(changedbits&0x01) { if(flags&0x01) { glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); } else { glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } } if(changedbits&PT_LERP) glFogfv(GL_FOG_COLOR, (flags&PT_LERP) ? oldfogc : zerofog); if(changedbits&(PT_LERP|PT_MOD)) { if(flags&PT_LERP) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); else if(flags&PT_MOD) glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); else glBlendFunc(GL_SRC_ALPHA, GL_ONE); } if(changedbits&PT_SOFT) { if(flags&PT_SOFT) { if(depthfxtex.target==GL_TEXTURE_RECTANGLE_ARB) { if(!depthfxtex.highprecision()) SETSHADER(particlesoft8rect); else SETSHADER(particlesoftrect); } else { if(!depthfxtex.highprecision()) SETSHADER(particlesoft8); else SETSHADER(particlesoft); } binddepthfxparams(depthfxpartblend); } else particleshader->set(); } lastflags = flags; } p->render(); } if(rendered) { if(lastflags&(PT_LERP|PT_MOD)) glBlendFunc(GL_SRC_ALPHA, GL_ONE); if(!(lastflags&PT_LERP)) glFogfv(GL_FOG_COLOR, oldfogc); if(lastflags&0x01) { glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } glDisable(GL_BLEND); glDepthMask(GL_TRUE); } } static int addedparticles = 0; static inline particle *newparticle(const vec &o, const vec &d, int fade, int type, int color, float size, int gravity = 0) { static particle dummy; if(seedemitter) { parts[type]->seedemitter(*seedemitter, o, d, fade, size, gravity); return &dummy; } if(fade + emitoffset < 0) return &dummy; addedparticles++; return parts[type]->addpart(o, d, fade, color, size, gravity); } VARP(maxparticledistance, 256, 1024, 4096); static void splash(int type, int color, int radius, int num, int fade, const vec &p, float size, int gravity) { if(camera1->o.dist(p) > maxparticledistance && !seedemitter) return; float collidez = parts[type]->collide ? p.z - raycube(p, vec(0, 0, -1), COLLIDERADIUS, RAY_CLIPMAT) + COLLIDEERROR : -1; int fmin = 1; int fmax = fade*3; loopi(num) { int x, y, z; do { x = rnd(radius*2)-radius; y = rnd(radius*2)-radius; z = rnd(radius*2)-radius; } while(x*x+y*y+z*z>radius*radius); vec tmp = vec((float)x, (float)y, (float)z); int f = (num < 10) ? (fmin + rnd(fmax)) : (fmax - (i*(fmax-fmin))/(num-1)); //help deallocater by using fade distribution rather than random newparticle(p, tmp, f, type, color, size, gravity)->val = collidez; } } static void regularsplash(int type, int color, int radius, int num, int fade, const vec &p, float size, int gravity, int delay = 0) { if(!emit_particles() || (delay > 0 && rnd(delay) != 0)) return; splash(type, color, radius, num, fade, p, size, gravity); } bool canaddparticles() { return !renderedgame && !shadowmapping; } void regular_particle_splash(int type, int num, int fade, const vec &p, int color, float size, int radius, int gravity, int delay) { if(!canaddparticles()) return; regularsplash(type, color, radius, num, fade, p, size, gravity, delay); } void particle_splash(int type, int num, int fade, const vec &p, int color, float size, int radius, int gravity) { if(!canaddparticles()) return; splash(type, color, radius, num, fade, p, size, gravity); } VARP(maxtrail, 1, 500, 10000); void particle_trail(int type, int fade, const vec &s, const vec &e, int color, float size, int gravity) { if(!canaddparticles()) return; vec v; float d = e.dist(s, v); int steps = clamp(int(d*2), 1, maxtrail); v.div(steps); vec p = s; loopi(steps) { p.add(v); vec tmp = vec(float(rnd(11)-5), float(rnd(11)-5), float(rnd(11)-5)); newparticle(p, tmp, rnd(fade)+fade, type, color, size, gravity); } } VARP(particletext, 0, 1, 1); VARP(maxparticletextdistance, 0, 256, 10000); void particle_text(const vec &s, const char *t, int type, int fade, int color, float size, int gravity) { if(!canaddparticles()) return; if(!particletext || camera1->o.dist(s) > maxparticledistance) return; particle *p = newparticle(s, vec(0, 0, 1), fade, type, color, size, gravity); p->text = t; } void partent_text(const vec &s, const char *t, int colour, int size) { if(!canaddparticles()) return; if(!particletext) return; particle * p = newparticle(s, vec(0, 0, 1), 1, PART_TEXT, colour, size/100.0f, 0); if(t[0]=='@') {p->text = newstring(t+1); p->flags = 1;} else p->text = t; } void particle_textcopy(const vec &s, const char *t, int type, int fade, int color, float size, int gravity) { if(!canaddparticles()) return; if(!particletext || camera1->o.dist(s) > maxparticledistance) return; particle *p = newparticle(s, vec(0, 0, 1), fade, type, color, size, gravity); p->text = newstring(t); p->flags = 1; } void particle_icon(const vec &s, int ix, int iy, int type, int fade, int color, float size, int gravity) { if(!canaddparticles()) return; particle *p = newparticle(s, vec(0, 0, 1), fade, type, color, size, gravity); p->flags |= ix | (iy<<2); } void particle_meter(const vec &s, float val, int type, int fade, int color, int color2, float size) { if(!canaddparticles()) return; particle *p = newparticle(s, vec(0, 0, 1), fade, type, color, size); p->color2[0] = color2>>16; p->color2[1] = (color2>>8)&0xFF; p->color2[2] = color2&0xFF; p->progress = clamp(int(val*100), 0, 100); } void particle_flare(const vec &p, const vec &dest, int fade, int type, int color, float size, physent *owner) { if(!canaddparticles()) return; newparticle(p, dest, fade, type, color, size)->owner = owner; } void particle_fireball(const vec &dest, float maxsize, int type, int fade, int color, float size) { if(!canaddparticles()) return; float growth = maxsize - size; if(fade < 0) fade = int(growth*25); newparticle(dest, vec(0, 0, 1), fade, type, color, size)->val = growth; } //dir = 0..6 where 0=up static inline vec offsetvec(vec o, int dir, int dist) { vec v = vec(o); v[(2+dir)%3] += (dir>2)?(-dist):dist; return v; } /* Experiments in shapes... * dir: (where dir%3 is similar to offsetvec with 0=up) * 0..2 circle * 3.. 5 cylinder shell * 6..11 cone shell * 12..14 plane volume * 15..20 line volume, i.e. wall * 21 sphere * +32 to inverse direction */ void regularshape(int type, int radius, int color, int dir, int num, int fade, const vec &p, float size, float vel, int gravity) { if(!emit_particles()) return; int basetype = parts[type]->type&0xFF; bool flare = (basetype == PT_TAPE) || (basetype == PT_LIGHTNING), inv = (dir&0x20)!=0, taper = (dir&0x40)!=0 && !seedemitter; dir &= 0x1F; loopi(num) { vec to, from; if(dir < 12) { float a = PI2*float(rnd(1000))/1000.0; to[dir%3] = sinf(a)*radius; to[(dir+1)%3] = cosf(a)*radius; to[(dir+2)%3] = 0.0; to.add(p); if(dir < 3) //circle from = p; else if(dir < 6) //cylinder { from = to; to[(dir+2)%3] += radius; from[(dir+2)%3] -= radius; } else //cone { from = p; to[(dir+2)%3] += (dir < 9)?radius:(-radius); } } else if(dir < 15) //plane { to[dir%3] = float(rnd(radius<<4)-(radius<<3))/8.0; to[(dir+1)%3] = float(rnd(radius<<4)-(radius<<3))/8.0; to[(dir+2)%3] = radius; to.add(p); from = to; from[(dir+2)%3] -= 2*radius; } else if(dir < 21) //line { if(dir < 18) { to[dir%3] = float(rnd(radius<<4)-(radius<<3))/8.0; to[(dir+1)%3] = 0.0; } else { to[dir%3] = 0.0; to[(dir+1)%3] = float(rnd(radius<<4)-(radius<<3))/8.0; } to[(dir+2)%3] = 0.0; to.add(p); from = to; to[(dir+2)%3] += radius; } else //sphere { to = vec(PI2*float(rnd(1000))/1000.0, PI*float(rnd(1000)-500)/1000.0).mul(radius); to.add(p); from = p; } if(taper) { vec o = inv ? to : from; o.sub(camera1->o); float dist = clamp(sqrtf(o.x*o.x + o.y*o.y)/maxparticledistance, 0.0f, 1.0f); if(dist > 0.2f) { dist = 1 - (dist - 0.2f)/0.8f; if(rnd(0x10000) > dist*dist*0xFFFF) continue; } } if(flare) newparticle(inv?to:from, inv?from:to, rnd(fade*3)+1, type, color, size, gravity); else { vec d(to); d.sub(from); d.normalize().mul(inv ? -vel : vel); //velocity particle *np = newparticle(inv?to:from, d, rnd(abs(fade)*3)+1, type, color, size, gravity); if(fade < 0 && parts[type]->collide) np->val = (inv ? to.z : from.z) - raycube(inv ? to : from, vec(0, 0, -1), COLLIDERADIUS, RAY_CLIPMAT) + COLLIDEERROR; } } } static void regularflame(int type, const vec &p, float radius, float height, int color, int density = 3, float scale = 2.0f, float speed = 200.0f, float fade = 600.0f, int gravity = -15) { if(!emit_particles()) return; float size = scale * min(radius, height); vec v(0, 0, min(1.0f, height)*speed); loopi(density) { vec s = p; s.x += rndscale(radius*2.0f)-radius; s.y += rndscale(radius*2.0f)-radius; newparticle(s, v, rnd(max(int(fade*height), 1))+1, type, color, size, gravity); } } void regular_particle_flame(int type, const vec &p, float radius, float height, int color, int density, float scale, float speed, float fade, int gravity) { if(!canaddparticles()) return; regularflame(type, p, radius, height, color, density, scale, speed, fade, gravity); } void regularlensflare(vec o, uchar r, uchar g, uchar b, bool sun, bool sparkle, int sizemod) { flares.addflare(o, r, g, b, sun, sparkle, sizemod); } VARP(showentities, 0, 1, 2); static void makeparticles(entity &e) { switch(e.attr[0]) { case 0: //fire and smoke - - 0 values default to compat for old maps { float radius = e.attr[1] ? float(e.attr[1])/100.0f : 1.5f, height = e.attr[2] ? float(e.attr[2])/100.0f : radius/3; regularflame(PART_FLAME, e.o, radius, height, e.attr[3] ? e.attr[3] & 0xFFFFFF : 0x903020, 3, e.attr[4] ? 0.01f * abs(e.attr[4]) : 2.0f, e.attr[5] ? 0.02f * abs(e.attr[5]): 200.0f, e.attr[6] ? abs(e.attr[6]) : 600.0f, e.attr[7] ? e.attr[7]: -15.0f); regularflame(PART_SMOKE, vec(e.o.x, e.o.y, e.o.z + 4.0f*min(radius, height)), radius, height, 0x303020, 1, e.attr[4] ? .02f * abs(e.attr[4]) : 4.0f, e.attr[5] ? 0.01f * abs(e.attr[5]) : 100.0f, e.attr[6] ? abs(e.attr[6]) + 1400: 2000.0f, e.attr[7] ? e.attr[7] - 5 : -20.0f); break; } case 1: // flame - radius=100, height=100 is the classic size regularflame(PART_FLAME, e.o, float(e.attr[1])/100.0f, float(e.attr[2])/100.0f, e.attr[3] & 0xFFFFFF, 3, e.attr[4] ? 0.01f * abs(e.attr[4]) : 2.0f, e.attr[5] ? 0.02f * abs(e.attr[5]): 200.0f, e.attr[6] ? abs(e.attr[6]) : 600.0f, e.attr[7] ? e.attr[7]: -15.0f); break; case 2: // smoke plume regularflame(PART_SMOKE, e.o, float(e.attr[1])/100.0f, float(e.attr[2])/100.0f, e.attr[3] & 0xFFFFFF, 1, e.attr[4] ? .02f * abs(e.attr[4]) : 4.0f, e.attr[5] ? 0.01f * abs(e.attr[5]) : 100.0f, e.attr[6] ? abs(e.attr[6]): 2000.0f, e.attr[7] ? e.attr[7]: -20.0f); break; case 3: //steam vent - regularsplash(PART_STEAM, 0x897661, e.attr[2] ? abs(e.attr[2]) : 50, 1, e.attr[3] ? abs(e.attr[3]) : 200, offsetvec(e.o, e.attr[1], rnd(10)), e.attr[4] ? abs(e.attr[4]) *.01f : 2.4f, e.attr[5] ? e.attr[5] : -20); break; case 4: //water fountain - { int color = (int(waterfallcolor[0])<<16) | (int(waterfallcolor[1])<<8) | int(waterfallcolor[2]); if(!color) color = (int(watercolor[0])<<16) | (int(watercolor[1])<<8) | int(watercolor[2]); regularsplash(PART_WATER, color, e.attr[2] ? abs(e.attr[2]) : 150, 4, e.attr[3] ? abs(e.attr[3]) : 200, offsetvec(e.o, e.attr[1], rnd(10)), e.attr[4] ? abs(e.attr[4]) *.01f : 0.6f, e.attr[5] ? e.attr[5] : 2); break; } case 5: //fire ball - newparticle(e.o, vec(0, 0, 1), 1, PART_EXPLOSION, e.attr[2] & 0xFFFFFF, 4.0f)->val = 1+e.attr[1]; break; case 6: //meter, metervs - case 7: { particle *p = newparticle(e.o, vec(0, 0, 1), 1, e.attr[0]==6 ? PART_METER : PART_METER_VS, e.attr[2] & 0xFFFFFF, 2.0f); int color2 = e.attr[3] & 0xFFFFFF; p->color2[0] = color2>>16; p->color2[1] = (color2>>8)&0xFF; p->color2[2] = color2&0xFF; p->progress = clamp(int(e.attr[1]), 0, 100); break; } case 8: if(editmode || (game::showenthelpers() && showentities >= 1) || showentities==2) break; defformatstring(aliasname)("part_text_%d", e.attr[1]); defformatstring(word)("@%s", identexists(aliasname) ? getalias(aliasname) : "Nothing"); partent_text(e.o, word, e.attr[2] & 0xFFFFFF, e.attr[3] > 0 ? e.attr[3] : 200); break; case 9: //tape - case 10: //lightning case 11: //ball1 case 12: //steam case 13: //water case 14: //snow case 15: //leaves { const int typemap[] = { PART_STREAK, PART_LIGHTNING, PART_FIREBALL1, PART_STEAM, PART_WATER, PART_SNOW, PART_LEAVES }; const float sizemap[] = { 0.28, 1.0, 4.8, 2.4, 0.60, 0.5, 1 }; const float velmap[] = { 200, 200, 200, 200, 200, 40, 100 }; const int gravmap[] = { 0, 0, 20, -20, 2, 200, 40 }; int type = typemap[e.attr[0]-9], gravity = e.attr[7] ? e.attr[7] : gravmap[e.attr[0]-9]; float size = e.attr[5] ? abs(e.attr[5]) * .01f : sizemap[e.attr[0]-9], vel = e.attr[6] ? e.attr[6] * .1f : velmap[e.attr[0]-9]; if(e.attr[1] >= 256) regularshape(type, max(1+e.attr[2], 1), e.attr[3] & 0xFFFFFF, e.attr[1]-256, 5, e.attr[4] != 0 ? e.attr[4] : 200, e.o, size*particlesize/100.0, vel, gravity); else newparticle(e.o, offsetvec(e.o, e.attr[1], max(1+e.attr[2], 1)), 1, type, e.attr[3] & 0xFFFFFF, size, gravity); break; } case 32: //lens flares - plain/sparkle/sun/sparklesun case 33: case 34: case 35: flares.addflare(e.o, e.attr[1], e.attr[2], e.attr[3], (e.attr[0]&0x02)!=0, (e.attr[0]&0x01)!=0, e.attr[4]); break; default: if(editmode) return; defformatstring(ds)("@particles %d?", e.attr[0]); particle_text(e.o, ds, PART_TEXT, 1, 0x6496FF, 2.0f); break; } } bool printparticles(extentity &e, char *buf) { switch(e.attr[0]) { case 0: case 1: case 2: case 9: case 10: case 11: case 12: case 13: case 14: case 15: { defformatstring(ds)("%d %d %d 0x%.6X %d %d %d %d", e.attr[0], e.attr[1], e.attr[2], e.attr[3], e.attr[4], e.attr[5], e.attr[6], e.attr[7]); concatstring(buf, ds); return true; } case 5: case 8: { defformatstring(ds)("%d %d 0x%.6X %d %d %d %d %d", e.attr[0], e.attr[1], e.attr[2], e.attr[3], e.attr[4], e.attr[5], e.attr[6], e.attr[7]); concatstring(buf, ds); return true; } case 6: case 7: { defformatstring(ds)("%d %d 0x%.6X 0x%.6X %d %d %d %d", e.attr[0], e.attr[1], e.attr[2], e.attr[3], e.attr[4], e.attr[5], e.attr[6], e.attr[7]); concatstring(buf, ds); return true; } } return false; } VARP(showenttext, 0, 1, 1); void renderentinfo(int i) { if(!entities::getents().inrange(i)) return; extentity &e = *entities::getents()[i]; vec pos = e.o; string ds, tmp; extern void printent(extentity &e, char *buf); int colour = 0xFFB600; pos.z += 1.5; if(!showenttext) { printent(e, ds); particle_text(pos, ds, PART_TEXT, 1, colour, 2.0f); return; } else tmp[0] = ds[0] = '\0'; //prevents weird visual artefacts /* the format of the show ent stuff is like this formatstring(ds)("long line of descriptions, newlines etc", first level, second level, third level, fourth level, fifth level, sixth level, seventh level ); */ switch(e.type) { case ET_LIGHT: pos.z += 6; formatstring(tmp)("Radius %i\n\fs\fRRed: %i\n\fJGreen: %i\n\fDBlue: %i\fr", e.attr[0], e.attr[1], e.attr[2], e.attr[3] ); break; case ET_MAPMODEL: pos.z += 9.0; formatstring(tmp)("Yaw: %i\nModel: %s (%i)\nTrigger Type: %i\nTag: level_trigger_%i\nRadius: %i\nColour: \fs\fR%i \fJ%i \fD%i\fr", e.attr[0], mapmodelname(e.attr[1]), e.attr[1], e.attr[2], e.attr[3], e.attr[4], (e.attr[5] >> 16) & 0xFF, (e.attr[5] >> 8) & 0xFF, e.attr[5] & 0xFF ); break; case ET_PLAYERSTART: pos.z += 3.0; formatstring(tmp)("Yaw: %i\nTag: %i", e.attr[0], e.attr[1]); break; case ET_ENVMAP: pos.z += 4.5; formatstring(tmp)("Radius: %i\nSize: %i (%i)\nBlur: %i (%i)", e.attr[0], e.attr[1], e.attr[1] ? clamp(e.attr[1], 4, 9) : 0, e.attr[2], e.attr[2] ? clamp(e.attr[2], 1, 2) : 0 ); break; case ET_PARTICLES: switch(e.attr[0]) { case 0: pos.z += 12.0f; formatstring(tmp)("Type: Fire (0)\nRadius: %f\nHeight: %f\nColour: \fs\fR%i \fJ%i \fD%i\fr\nSize: %i\nSpeed: %i\nFade: %i\nGravity: %i", //NULL, e.attr[1] ? float(e.attr[1])/100.0f : 1.5f, e.attr[2] ? float(e.attr[2])/100.0f : (e.attr[2] ? float(e.attr[2])/100.0f : 1.5f)/3, (e.attr[3] & 0xFF0000) >> 16, (e.attr[3] & 0xFF00) >> 8, e.attr[3] & 0xFF, e.attr[4], e.attr[5], e.attr[6], e.attr[7] ); break; case 1: case 2: pos.z += 12.0f; formatstring(tmp)("Type: %s (%i)\nRadius: %i\nHeight: %i\nColour: \fs\fR%i \fJ%i \fD%i\fr\nSize: %i\nSpeed: %i\nFade: %i\nGravity: %i", e.attr[0]==1 ? "Flame" : "Smoke Plume", e.attr[0], e.attr[1], e.attr[2], (e.attr[3] & 0xFF0000) >> 16, (e.attr[3] & 0xFF00) >> 8, e.attr[3] & 0xFF, e.attr[4], e.attr[5], e.attr[6], e.attr[7] ); break; case 3: case 4: pos.z += 9.0f; formatstring(tmp)("Type: %s (%i)\nDirection: %i\nRadius: %i\nFade: %i\nSize: %i\nGravity: %i", e.attr[0]==3 ? "Smoke" : "Fountain", e.attr[0], e.attr[1], e.attr[2], e.attr[3], e.attr[4], e.attr[5] ); break; case 5: pos.z += 9.0; formatstring(tmp)("Type: Explosion (5)\nSize: %i\nColour: \fs\fR%i \fJ%i \fD%i\fr", //NULL, e.attr[1], (e.attr[2] & 0xFF0000) >> 16, (e.attr[2] & 0xFF00) >> 8, e.attr[2] & 0xFF ); break; case 6: case 7: pos.z += 6; formatstring(tmp)("Type: Meter%s (%i)\nPercentage: %i\n1st Colour: \fs\fR%i \fJ%i \fD%i\fr\n2nd Colour: \fs\fR%i \fJ%i \fD%i\fr", e.attr[0]==7 ? " Versus" : "", e.attr[0], e.attr[1], (e.attr[2] & 0xFF0000) >> 16, (e.attr[2] & 0xFF00) >> 8, e.attr[2] & 0xFF, (e.attr[3] & 0xFF0000) >> 16, (e.attr[3] & 0xFF00) >> 8, e.attr[3] & 0xFF ); break; case 8: pos.z += 6; formatstring(tmp)("Type: Text (8)\nTag: part_text_%i\nColour: \fs\fR%i \fJ%i \fD%i\fr\nSize %i", //NULL, e.attr[1], (e.attr[2] & 0xFF0000) >> 16, (e.attr[2] & 0xFF00) >> 8, e.attr[2] & 0xFF, e.attr[3] ); break; case 9: case 10: case 11: case 12: case 13: case 14: case 15: { pos.z += 12.0f; const static char *typenames[] = {"Flare", "Lightning", "Fire", "Smoke", "Water", "Snow", "Leaves"}; formatstring(tmp)("Type: %s (%i)\n%s : %i\nLength: %i\nColour: \fs\fR%i \fJ%i \fD%i\fr\nFadetime w/%s collision: %i\nSize: %i\nVel: %i\nGravity: %i", typenames[e.attr[0] - 9], e.attr[0], e.attr[1] >= 256 ? "Effect" : "Direction", e.attr[1], e.attr[2], (e.attr[3] & 0xFF0000) >> 16, (e.attr[3] & 0xFF00) >> 8, e.attr[3] & 0xFF, e.attr[4] < 0 ? "" : "o", abs(e.attr[4]), e.attr[5], e.attr[6], e.attr[7] ); break; } case 32: case 33: case 34: case 35: pos.z += 7.5; formatstring(tmp)("Type: %sLens Flare w/%s Sparkle (%i)\n\fs\fRRed: %i\n\fJGreen: %i\n\fDBlue: %i\n\frSize: %i", (e.attr[0]==32 || e.attr[0] == 33) ? "" : "Fixed-Size ", (e.attr[0]==32 || e.attr[0]==34) ? "o" : "", e.attr[0], e.attr[1], e.attr[2], e.attr[3], e.attr[4] ); break; default: pos.z += 1.5; formatstring(tmp)("Invalid type: %i", e.attr[0]); break; } break; case ET_SOUND: pos.z += 4.5; formatstring(tmp)("Index: %i\nRadius: %i\nListen Radius: %i", e.attr[0], e.attr[1], e.attr[2] ); break; case ET_SPOTLIGHT: pos.z += 1.5; formatstring(tmp)("Angle: %i", e.attr[0]); break; default: entities::renderhelpertext(e, colour, pos, tmp); break; } formatstring(ds)("%s%s", tmp, tmp[0]=='\0' ? "" : "\n" /*prevents a newline on an empty tmp string*/ ); printent(e, ds); //concatstring(ds, tmp); particle_textcopy(pos, ds, PART_TEXT, 1, colour, 2.0f); } VARP(editingparticles, 0, 1 ,1); VAR(cullparticles, 0, 1, 1); VAR(replayparticles, 0, 1, 1); VARN(seedparticles, seedmillis, 0, 3000, 10000); VAR(dbgpcull, 0, 0, 1); struct editmarker //editmode markers :D { int type, colour, dist; float size; }; editmarker markers[] = { {PART_WATER, 0x2FBFFF, 80, .4}, {PART_SMOKE, 0xAFAFAF, 80, .5}, {PART_STEAM, 0xAFAFAF, 80, .4}, {PART_FLAME, 0xFFAF3F, 80, .6}, {PART_SPARK, 0xBFAF0F, 80, .5}, {PART_EDIT, 0x3232FF, 80, .32}, {PART_SNOW, 0xBFBFBF, 80, .7}, {PART_FIREBALL1, 0xFFFFFF, 80, .8}, {PART_FIREBALL2, 0xFFFFFF, 80, .8}, {PART_FIREBALL3, 0xFFFFFF, 80, .8}, {PART_EXPLOSION, 0xAF7F3F, NULL, 8} }; VARP(entmarkertype, 0, 5, sizeof(markers)/sizeof(markers[0])-1); int expemitmillis = 0; void seedparticles() { renderprogress(0, "seeding particles"); addparticleemitters(); canemit = true; loopv(emitters) { particleemitter &pe = emitters[i]; extentity &e = *pe.ent; seedemitter = &pe; for(int millis = 0; millis < seedmillis; millis += min(emitmillis, seedmillis/10)) makeparticles(e); seedemitter = NULL; pe.lastemit = -seedmillis; pe.finalize(); } } void updateparticles() { if(regenemitters) addparticleemitters(); if(lastmillis - lastemitframe >= emitmillis) { canemit = true; lastemitframe = lastmillis - (lastmillis%emitmillis); } else canemit = false; flares.makelightflares(); if(!editmode || editingparticles) { int emitted = 0, replayed = 0; addedparticles = 0; loopv(emitters) { particleemitter &pe = emitters[i]; extentity &e = *pe.ent; if(e.o.dist(camera1->o) > maxparticledistance) { pe.lastemit = lastmillis; continue; } if(cullparticles && pe.maxfade >= 0) { if(isfoggedsphere(pe.radius, pe.center)) { pe.lastcull = lastmillis; continue; } if(pvsoccluded(pe.bborigin, pe.bbsize)) { pe.lastcull = lastmillis; continue; } } makeparticles(e); emitted++; if(replayparticles && pe.maxfade > 5 && pe.lastcull > pe.lastemit) { for(emitoffset = max(pe.lastemit + emitmillis - lastmillis, -pe.maxfade); emitoffset < 0; emitoffset += emitmillis) { makeparticles(e); replayed++; } emitoffset = 0; } pe.lastemit = lastmillis; } if(dbgpcull && (canemit || replayed) && addedparticles) conoutf(CON_DEBUG, "%d emitters, %d particles", emitted, addedparticles); } const vector &ents = entities::getents(); if(editmode || (game::showenthelpers() && showentities >= 1) || showentities==2) // show sparkly thingies for map entities in edit mode { // note: order matters in this case as particles of the same type are drawn in the reverse order that they are added loopv(entgroup) { renderentinfo(entgroup[i]); extentity &e = *ents[entgroup[i]]; if(e.type == ET_PARTICLES && e.attr[0] == 11) { defformatstring(aliasname)("part_text_%d", e.attr[1]); defformatstring(party_text)("@particles:%s", getalias(aliasname)); partent_text(e.o, party_text, e.attr[2] & 0xFFFFFF, e.attr[3] > 0 ? e.attr[3] : 200); } else particle_textcopy(e.o, entname(e), PART_TEXT, 1, 0xFF4B19, 2.0f); } loopv(ents) { entity &e = *ents[i]; if(e.type==ET_EMPTY) continue; if(e.type == ET_PARTICLES && e.attr[0] == 11) { defformatstring(aliasname)("part_text_%d", e.attr[1]); defformatstring(party_text)("@particles:%s", getalias(aliasname)); partent_text(e.o, party_text, e.attr[2] & 0xFFFFFF, e.attr[3] > 0 ? e.attr[3] : 200); } else particle_textcopy(e.o, entname(e), PART_TEXT, 1, 0x1EC850, 2.0f); if(markers[entmarkertype].dist) { regular_particle_splash(markers[entmarkertype].type, 2, markers[entmarkertype].dist, e.o, markers[entmarkertype].colour, markers[entmarkertype].size*particlesize/100.0f); } else { if(expemitmillis < totalmillis) particle_fireball(e.o, markers[entmarkertype].size, markers[entmarkertype].type, 1, markers[entmarkertype].colour); } } if(editmode) renderentinfo(enthover); expemitmillis = totalmillis; } } sandboxgamemaker-2.7.1+dfsg/src/engine/client.cpp0000664000175000017500000001646511615526106021707 0ustar showardshoward// client.cpp, mostly network related client game code #include "engine.h" ENetHost *clienthost = NULL; ENetPeer *curpeer = NULL, *connpeer = NULL; int connmillis = 0, connattempts = 0, discmillis = 0; bool multiplayer(bool msg) { bool val = curpeer || hasnonlocalclients(); if(val && msg) conoutf(CON_ERROR, "operation not available in multiplayer"); return val; } void setrate(int rate) { if(!curpeer) return; enet_host_bandwidth_limit(clienthost, rate*1024, rate*1024); } VARF(rate, 0, 0, 1024, setrate(rate)); void throttle(); VARF(throttle_interval, 0, 5, 30, throttle()); VARF(throttle_accel, 0, 2, 32, throttle()); VARF(throttle_decel, 0, 2, 32, throttle()); void throttle() { if(!curpeer) return; ASSERT(ENET_PEER_PACKET_THROTTLE_SCALE==32); enet_peer_throttle_configure(curpeer, throttle_interval*1000, throttle_accel, throttle_decel); } bool isconnected(bool attempt) { return curpeer || (attempt && connpeer); } ICOMMAND(isconnected, "i", (int *attempt), intret(isconnected(*attempt > 0) ? 1 : 0)); const ENetAddress *connectedpeer() { return curpeer ? &curpeer->address : NULL; } ICOMMAND(connectedip, "", (), { const ENetAddress *address = connectedpeer(); string hostname; result(address && enet_address_get_host_ip(address, hostname, sizeof(hostname)) >= 0 ? hostname : ""); }); ICOMMAND(connectedport, "", (), { const ENetAddress *address = connectedpeer(); intret(address ? address->port : -1); }); void abortconnect() { if(!connpeer) return; game::connectfail(); if(connpeer->state!=ENET_PEER_STATE_DISCONNECTED) enet_peer_reset(connpeer); connpeer = NULL; if(curpeer) return; enet_host_destroy(clienthost); clienthost = NULL; } SVAR(connectname, ""); VAR(connectport, 0, 0, 0xFFFF); void connectserv(const char *servername, int serverport, const char *serverpassword) { if(connpeer) { conoutf("aborting connection attempt"); abortconnect(); } if(serverport <= 0) serverport = server::serverport(); ENetAddress address; address.port = serverport; if(servername) { if(strcmp(servername, connectname)) setsvar("connectname", servername); if(serverport != connectport) setvar("connectport", serverport); addserver(servername, serverport, serverpassword && serverpassword[0] ? serverpassword : NULL); conoutf("attempting to connect to %s:%d", servername, serverport); if(!resolverwait(servername, &address)) { conoutf("\f3could not resolve server %s", servername); return; } } else { setsvar("connectname", ""); setvar("connectport", 0); conoutf("attempting to connect over LAN"); address.host = ENET_HOST_BROADCAST; } if(!clienthost) clienthost = enet_host_create(NULL, 2, server::numchannels(), rate, rate); if(clienthost) { connpeer = enet_host_connect(clienthost, &address, server::numchannels(), 0); enet_host_flush(clienthost); connmillis = totalmillis; connattempts = 0; game::connectattempt(servername ? servername : "", serverpassword ? serverpassword : "", address); } else conoutf("\f3could not connect to server"); } void reconnect(const char *serverpassword) { if(!connectname[0] || connectport <= 0) { conoutf(CON_ERROR, "no previous connection"); return; } connectserv(connectname, connectport, serverpassword); } void disconnect(bool async, bool cleanup) { if(curpeer) { if(!discmillis) { enet_peer_disconnect(curpeer, DISC_NONE); enet_host_flush(clienthost); discmillis = totalmillis; } if(curpeer->state!=ENET_PEER_STATE_DISCONNECTED) { if(async) return; enet_peer_reset(curpeer); } curpeer = NULL; discmillis = 0; conoutf("disconnected"); game::gamedisconnect(cleanup); #ifndef NEWGUI mainmenu = 1; #else UI::mainmenu = 1; #endif } if(!connpeer && clienthost) { enet_host_destroy(clienthost); clienthost = NULL; } } void trydisconnect() { if(connpeer) { conoutf("aborting connection attempt"); abortconnect(); } else if(curpeer) { conoutf("attempting to disconnect..."); disconnect(!discmillis); } else conoutf("not connected"); } ICOMMAND(connect, "sis", (char *name, int *port, char *pw), connectserv(name, *port, pw)); ICOMMAND(lanconnect, "is", (int *port, char *pw), connectserv(NULL, *port, pw)); COMMAND(reconnect, "s"); COMMANDN(disconnect, trydisconnect, ""); ICOMMAND(localconnect, "", (), { if(!isconnected() && !haslocalclients()) localconnect(); }); ICOMMAND(localdisconnect, "", (), { if(haslocalclients()) localdisconnect(); }); void sendclientpacket(ENetPacket *packet, int chan) { if(curpeer) enet_peer_send(curpeer, chan, packet); else localclienttoserver(chan, packet); } void flushclient() { if(clienthost) enet_host_flush(clienthost); } void neterr(const char *s, bool disc) { conoutf(CON_ERROR, "\f3illegal network message (%s)", s); if(disc) disconnect(); } void localservertoclient(int chan, ENetPacket *packet) // processes any updates from the server { packetbuf p(packet); game::parsepacketclient(chan, p); } void clientkeepalive() { if(clienthost) enet_host_service(clienthost, NULL, 0); } void gets2c() // get updates from the server { ENetEvent event; if(!clienthost) return; if(connpeer && totalmillis/3000 > connmillis/3000) { conoutf("attempting to connect..."); connmillis = totalmillis; ++connattempts; if(connattempts > 3) { conoutf("\f3could not connect to server"); abortconnect(); return; } } while(clienthost && enet_host_service(clienthost, &event, 0)>0) switch(event.type) { case ENET_EVENT_TYPE_CONNECT: disconnect(false, false); localdisconnect(false); curpeer = connpeer; connpeer = NULL; conoutf("connected to server"); throttle(); if(rate) setrate(rate); game::gameconnect(true); break; case ENET_EVENT_TYPE_RECEIVE: if(discmillis) conoutf("attempting to disconnect..."); else localservertoclient(event.channelID, event.packet); enet_packet_destroy(event.packet); break; case ENET_EVENT_TYPE_DISCONNECT: extern const char *disc_reasons[]; if(event.data>=DISC_NUM) event.data = DISC_NONE; if(event.peer==connpeer) { conoutf("\f3could not connect to server"); abortconnect(); } else { if(!discmillis || event.data) conoutf("\f3server network error, disconnecting (%s) ...", disc_reasons[event.data]); disconnect(); } return; default: break; } } sandboxgamemaker-2.7.1+dfsg/src/engine/animmodel.h0000664000175000017500000016420211655776734022056 0ustar showardshowardVARFP(lightmodels, 0, 1, 1, preloadmodelshaders()); VARFP(envmapmodels, 0, 1, 1, preloadmodelshaders()); VARFP(glowmodels, 0, 1, 1, preloadmodelshaders()); VARFP(bumpmodels, 0, 1, 1, preloadmodelshaders()); VARP(fullbrightmodels, 0, 0, 200); struct animmodel : model { struct animspec { int frame, range; float speed; int priority; }; struct animpos { int anim, fr1, fr2; float t; void setframes(const animinfo &info) { anim = info.anim; if(info.range<=1) { fr1 = 0; t = 0; } else { int time = info.anim&ANIM_SETTIME ? info.basetime : lastmillis-info.basetime; fr1 = (int)(time/info.speed); // round to full frames t = (time-fr1*info.speed)/info.speed; // progress of the frame, value from 0.0f to 1.0f } if(info.anim&ANIM_LOOP) { fr1 = fr1%info.range+info.frame; fr2 = fr1+1; if(fr2>=info.frame+info.range) fr2 = info.frame; } else { fr1 = min(fr1, info.range-1)+info.frame; fr2 = min(fr1+1, info.frame+info.range-1); } if(info.anim&ANIM_REVERSE) { fr1 = (info.frame+info.range-1)-(fr1-info.frame); fr2 = (info.frame+info.range-1)-(fr2-info.frame); } } bool operator==(const animpos &a) const { return fr1==a.fr1 && fr2==a.fr2 && (fr1==fr2 || t==a.t); } bool operator!=(const animpos &a) const { return fr1!=a.fr1 || fr2!=a.fr2 || (fr1!=fr2 && t!=a.t); } }; struct part; struct animstate { part *owner; animpos cur, prev; float interp; bool operator==(const animstate &a) const { return cur==a.cur && (interp<1 ? interp==a.interp && prev==a.prev : a.interp>=1); } bool operator!=(const animstate &a) const { return cur!=a.cur || (interp<1 ? interp!=a.interp || prev!=a.prev : a.interp<1); } }; struct linkedpart; struct mesh; struct skin { part *owner; Texture *tex, *masks, *envmap, *unlittex, *normalmap; Shader *shader; float spec, ambient, glow, glowdelta, glowpulse, specglare, glowglare, fullbright, envmapmin, envmapmax, scrollu, scrollv, alphatest; bool alphablend, cullface; skin() : owner(0), tex(notexture), masks(notexture), envmap(NULL), unlittex(NULL), normalmap(NULL), shader(NULL), spec(1.0f), ambient(0.3f), glow(3.0f), glowdelta(0), glowpulse(0), specglare(1), glowglare(1), fullbright(0), envmapmin(0), envmapmax(0), scrollu(0), scrollv(0), alphatest(0.9f), alphablend(true), cullface(true) {} bool multitextured() { return enableglow; } bool envmapped() { return hasCM && envmapmax>0 && envmapmodels && (renderpath!=R_FIXEDFUNCTION || maxtmus >= 3); } bool bumpmapped() { return renderpath!=R_FIXEDFUNCTION && normalmap && bumpmodels; } bool normals() { return renderpath!=R_FIXEDFUNCTION || (lightmodels && !fullbright) || envmapped() || bumpmapped(); } bool tangents() { return bumpmapped(); } void setuptmus(const animstate *as, bool masked) { if(fullbright) { if(enablelighting) { glDisable(GL_LIGHTING); enablelighting = false; } } else if(lightmodels && !enablelighting) { glEnable(GL_LIGHTING); enablelighting = true; if(!enablerescale) { glEnable(hasRN ? GL_RESCALE_NORMAL_EXT : GL_NORMALIZE); enablerescale = true; } } if(masked!=enableglow) lasttex = lastmasks = NULL; float mincolor = as->cur.anim&ANIM_FULLBRIGHT ? fullbrightmodels/100.0f : 0.0f; vec color = vec(lightcolor).max(mincolor), matcolor(1, 1, 1); if(masked) { bool needenvmap = envmaptmu>=0 && envmapmax>0; if(enableoverbright) disableoverbright(); if(!enableglow || enableenvmap!=needenvmap) setuptmu(0, "1 , C @ T", needenvmap ? "= Ta" : "= Ca"); int glowscale = glow>2 ? 4 : (glow>1 || mincolor>1 ? 2 : 1); matcolor.div(glowscale); glActiveTexture_(GL_TEXTURE1_ARB); if(!enableglow || enableenvmap!=needenvmap) { if(!enableglow) glEnable(GL_TEXTURE_2D); setuptmu(1, "P * T", needenvmap ? "= Pa" : "Pa * Ta"); } scaletmu(1, glowscale); glActiveTexture_(GL_TEXTURE0_ARB); enableglow = true; } else { if(enableglow) disableglow(); if(mincolor>1 && maxtmus>=1) { matcolor.div(2); if(!enableoverbright) { setuptmu(0, "C * T x 2"); enableoverbright = true; } } else if(enableoverbright) disableoverbright(); } if(fullbright) glColor4f(matcolor.x*fullbright, matcolor.y*fullbright, matcolor.z*fullbright, transparent); else if(lightmodels) { GLfloat material[4] = { matcolor.x, matcolor.y, matcolor.z, transparent }; glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, material); } else glColor4f(matcolor.x*color.x, matcolor.y*color.y, matcolor.z*color.z, transparent); if(lightmodels && !fullbright) { float ambientk = min(max(ambient, mincolor)*0.75f, 1.0f), diffusek = 1-ambientk; GLfloat ambientcol[4] = { color.x*ambientk, color.y*ambientk, color.z*ambientk, 1 }, diffusecol[4] = { color.x*diffusek, color.y*diffusek, color.z*diffusek, 1 }; float ambientmax = max(ambientcol[0], max(ambientcol[1], ambientcol[2])), diffusemax = max(diffusecol[0], max(diffusecol[1], diffusecol[2])); if(ambientmax>1e-3f) loopk(3) ambientcol[k] *= min(1.5f, 1.0f/min(ambientmax, 1.0f)); if(diffusemax>1e-3f) loopk(3) diffusecol[k] *= min(1.5f, 1.0f/min(diffusemax, 1.0f)); glLightfv(GL_LIGHT0, GL_AMBIENT, ambientcol); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffusecol); } } void setshaderparams(mesh *m, const animstate *as, bool masked) { if(fullbright) { glColor4f(fullbright/2, fullbright/2, fullbright/2, transparent); setenvparamf("lightscale", SHPARAM_VERTEX, 2, 0, 0, 2); setenvparamf("lightscale", SHPARAM_PIXEL, 2, 0, 0, 2); } else { float mincolor = as->cur.anim&ANIM_FULLBRIGHT ? fullbrightmodels/100.0f : 0.0f, bias = max(mincolor-1.0f, 0.2f), scale = 0.5f*max(0.8f-bias, 0.0f), minshade = scale*max(ambient, mincolor); vec color = vec(lightcolor).max(mincolor); glColor4f(color.x, color.y, color.z, transparent); setenvparamf("lightscale", SHPARAM_VERTEX, 2, scale - minshade, scale, minshade + bias); setenvparamf("lightscale", SHPARAM_PIXEL, 2, scale - minshade, scale, minshade + bias); } float curglow = glow; if(glowpulse > 0) { float curpulse = lastmillis*glowpulse; curpulse -= floor(curpulse); curglow += glowdelta*2*fabs(curpulse - 0.5f); } setenvparamf("maskscale", SHPARAM_PIXEL, 4, 0.5f*spec*lightmodels, 0.5f*curglow*glowmodels, 16*specglare, 4*glowglare); setenvparamf("texscroll", SHPARAM_VERTEX, 5, lastmillis/1000.0f, scrollu*lastmillis/1000.0f, scrollv*lastmillis/1000.0f); if(envmaptmu>=0 && envmapmax>0) setenvparamf("envmapscale", bumpmapped() ? SHPARAM_PIXEL : SHPARAM_VERTEX, 3, envmapmin-envmapmax, envmapmax); } Shader *loadshader(bool shouldenvmap, bool masked) { #define DOMODELSHADER(name, body) \ do { \ static Shader *name##shader = NULL; \ if(!name##shader) name##shader = useshaderbyname(#name); \ body; \ } while(0) #define LOADMODELSHADER(name) DOMODELSHADER(name, return name##shader) #define SETMODELSHADER(m, name) DOMODELSHADER(name, (m)->setshader(name##shader)) if(shader) return shader; else if(bumpmapped()) { if(shouldenvmap) { if(lightmodels && !fullbright && (masked || spec>=0.01f)) LOADMODELSHADER(bumpenvmapmodel); else LOADMODELSHADER(bumpenvmapnospecmodel); } else if(masked && lightmodels && !fullbright) LOADMODELSHADER(bumpmasksmodel); else if(masked && glowmodels) LOADMODELSHADER(bumpmasksnospecmodel); else if(spec>=0.01f && lightmodels && !fullbright) LOADMODELSHADER(bumpmodel); else LOADMODELSHADER(bumpnospecmodel); } else if(shouldenvmap) { if(lightmodels && !fullbright && (masked || spec>=0.01f)) LOADMODELSHADER(envmapmodel); else LOADMODELSHADER(envmapnospecmodel); } else if(masked && lightmodels && !fullbright) LOADMODELSHADER(masksmodel); else if(masked && glowmodels) LOADMODELSHADER(masksnospecmodel); else if(spec>=0.01f && lightmodels && !fullbright) LOADMODELSHADER(stdmodel); else LOADMODELSHADER(nospecmodel); } void preloadBIH() { if(tex && tex->bpp==4 && !tex->alphamask) loadalphamask(tex); } void preloadshader() { bool shouldenvmap = envmapped(); if(masks->type&Texture::STUB && !strncmp(masks->name, "", 6)) { float glowscale = glow/(glow>2 ? 4 : (glow>1 ? 2 : 1)), envscale = envmapmax > 0 ? 0.2f*envmapmax + 0.8f*envmapmin : 0; defformatstring(ffmask)("", floor(glowscale*16 + 0.5f)/16, floor(envscale*16 + 0.5f)/16); masks = textureload(makerelpath(NULL, masks->name + 6, NULL, ffmask), 0, true, false); } loadshader(shouldenvmap, masks!=notexture && !(masks->type&Texture::STUB) && (lightmodels || glowmodels || shouldenvmap)); } void setshader(mesh *m, const animstate *as, bool masked) { m->setshader(loadshader(envmaptmu>=0 && envmapmax>0, masked)); } void bind(mesh *b, const animstate *as) { if(!cullface && enablecullface) { glDisable(GL_CULL_FACE); enablecullface = false; } else if(cullface && !enablecullface) { glEnable(GL_CULL_FACE); enablecullface = true; } if(as->cur.anim&ANIM_NOSKIN) { if(enablealphatest) { glDisable(GL_ALPHA_TEST); enablealphatest = false; } if(enablealphablend) { glDisable(GL_BLEND); enablealphablend = false; } if(enableglow) disableglow(); if(enableenvmap) disableenvmap(); if(enablelighting) { glDisable(GL_LIGHTING); enablelighting = false; } if(enablerescale) { glDisable(hasRN ? GL_RESCALE_NORMAL_EXT : GL_NORMALIZE); enablerescale = false; } if(shadowmapping) SETMODELSHADER(b, shadowmapcaster); else /*if(as->cur.anim&ANIM_SHADOW)*/ SETMODELSHADER(b, notexturemodel); return; } Texture *s = bumpmapped() && unlittex ? unlittex : tex, *m = masks->type&Texture::STUB ? notexture : masks, *n = bumpmapped() ? normalmap : NULL; if((renderpath==R_FIXEDFUNCTION || !lightmodels) && !glowmodels && (!envmapmodels || envmaptmu<0 || envmapmax<=0)) m = notexture; if(renderpath==R_FIXEDFUNCTION) setuptmus(as, m!=notexture); else { setshaderparams(b, as, m!=notexture); setshader(b, as, m!=notexture); } if(s!=lasttex) { if(enableglow) glActiveTexture_(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, s->id); if(enableglow) glActiveTexture_(GL_TEXTURE0_ARB); lasttex = s; } if(n && n!=lastnormalmap) { glActiveTexture_(GL_TEXTURE3_ARB); glBindTexture(GL_TEXTURE_2D, n->id); glActiveTexture_(GL_TEXTURE0_ARB); } if(s->bpp==4) { if(alphablend) { if(!enablealphablend && !reflecting && !refracting) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); enablealphablend = true; } } else if(enablealphablend) { glDisable(GL_BLEND); enablealphablend = false; } if(alphatest>0) { if(!enablealphatest) { glEnable(GL_ALPHA_TEST); enablealphatest = true; } if(lastalphatest!=alphatest) { glAlphaFunc(GL_GREATER, alphatest); lastalphatest = alphatest; } } else if(enablealphatest) { glDisable(GL_ALPHA_TEST); enablealphatest = false; } } else { if(enablealphatest) { glDisable(GL_ALPHA_TEST); enablealphatest = false; } if(enablealphablend && transparent>=1) { glDisable(GL_BLEND); enablealphablend = false; } } if(m!=lastmasks && m!=notexture) { if(!enableglow) glActiveTexture_(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, m->id); if(!enableglow) glActiveTexture_(GL_TEXTURE0_ARB); lastmasks = m; } if((renderpath!=R_FIXEDFUNCTION || m!=notexture) && envmaptmu>=0 && envmapmax>0) { GLuint emtex = envmap ? envmap->id : closestenvmaptex; if(!enableenvmap || lastenvmaptex!=emtex) { glActiveTexture_(GL_TEXTURE0_ARB+envmaptmu); if(!enableenvmap) { glEnable(GL_TEXTURE_CUBE_MAP_ARB); if(!lastenvmaptex && renderpath==R_FIXEDFUNCTION) { glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_R); } enableenvmap = true; if(!enablerescale) { glEnable(hasRN ? GL_RESCALE_NORMAL_EXT : GL_NORMALIZE); enablerescale = true; } } if(lastenvmaptex!=emtex) { glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, emtex); lastenvmaptex = emtex; } glActiveTexture_(GL_TEXTURE0_ARB); } } else if(enableenvmap) disableenvmap(); } }; struct meshgroup; struct mesh { meshgroup *group; char *name; bool noclip; mesh() : group(NULL), name(NULL), noclip(false) { } virtual ~mesh() { DELETEA(name); } virtual void calcbb(int frame, vec &bbmin, vec &bbmax, const matrix3x4 &m) {} virtual void gentris(int frame, Texture *tex, vector *out, const matrix3x4 &m) {} virtual void setshader(Shader *s) { if(glaring) s->setvariant(0, 2); else s->set(); } template void smoothnorms(V *verts, int numverts, T *tris, int numtris, float limit, bool areaweight) { hashtable share; int *next = new int[numverts]; memset(next, -1, numverts*sizeof(int)); loopi(numverts) { V &v = verts[i]; v.norm = vec(0, 0, 0); int idx = share.access(v.pos, i); if(idx != i) { next[i] = next[idx]; next[idx] = i; } } loopi(numtris) { T &t = tris[i]; V &v1 = verts[t.vert[0]], &v2 = verts[t.vert[1]], &v3 = verts[t.vert[2]]; vec norm; norm.cross(vec(v2.pos).sub(v1.pos), vec(v3.pos).sub(v1.pos)); if(!areaweight) norm.normalize(); v1.norm.add(norm); v2.norm.add(norm); v3.norm.add(norm); } vec *norms = new vec[numverts]; memset(norms, 0, numverts*sizeof(vec)); loopi(numverts) { V &v = verts[i]; norms[i].add(v.norm); if(next[i] >= 0) { float vlimit = limit*v.norm.magnitude(); for(int j = next[i]; j >= 0; j = next[j]) { V &o = verts[j]; if(v.norm.dot(o.norm) >= vlimit*o.norm.magnitude()) { norms[i].add(o.norm); norms[j].add(v.norm); } } } } loopi(numverts) verts[i].norm = norms[i].normalize(); delete[] next; delete[] norms; } template void buildnorms(V *verts, int numverts, T *tris, int numtris, bool areaweight) { loopi(numverts) verts[i].norm = vec(0, 0, 0); loopi(numtris) { T &t = tris[i]; V &v1 = verts[t.vert[0]], &v2 = verts[t.vert[1]], &v3 = verts[t.vert[2]]; vec norm; norm.cross(vec(v2.pos).sub(v1.pos), vec(v3.pos).sub(v1.pos)); if(!areaweight) norm.normalize(); v1.norm.add(norm); v2.norm.add(norm); v3.norm.add(norm); } loopi(numverts) verts[i].norm.normalize(); } template void calctangents(B *bumpverts, V *verts, TC *tcverts, int numverts, T *tris, int numtris, bool areaweight) { vec *tangent = new vec[2*numverts], *bitangent = tangent+numverts; memset(tangent, 0, 2*numverts*sizeof(vec)); loopi(numtris) { const T &t = tris[i]; const vec &e0 = verts[t.vert[0]].pos; vec e1 = vec(verts[t.vert[1]].pos).sub(e0), e2 = vec(verts[t.vert[2]].pos).sub(e0); const TC &tc0 = tcverts[t.vert[0]], &tc1 = tcverts[t.vert[1]], &tc2 = tcverts[t.vert[2]]; float u1 = tc1.u - tc0.u, v1 = tc1.v - tc0.v, u2 = tc2.u - tc0.u, v2 = tc2.v - tc0.v; vec u(e2), v(e2); u.mul(v1).sub(vec(e1).mul(v2)); v.mul(u1).sub(vec(e1).mul(u2)); if(vec().cross(e2, e1).dot(vec().cross(v, u)) < 0) { u.neg(); v.neg(); } if(!areaweight) { u.normalize(); v.normalize(); } loopj(3) { tangent[t.vert[j]].add(u); bitangent[t.vert[j]].add(v); } } loopi(numverts) { const vec &n = verts[i].norm, &t = tangent[i], &bt = bitangent[i]; B &bv = bumpverts[i]; (bv.tangent = t).sub(vec(n).mul(n.dot(t))).normalize(); bv.bitangent = vec().cross(n, t).dot(bt) < 0 ? -1 : 1; } delete[] tangent; } }; struct meshgroup { meshgroup *next; int shared; char *name; vector meshes; float scale; vec translate; meshgroup() : next(NULL), shared(0), name(NULL), scale(1), translate(0, 0, 0) { } virtual ~meshgroup() { DELETEA(name); meshes.deletecontents(); DELETEP(next); } virtual int findtag(const char *name) { return -1; } virtual void concattagtransform(part *p, int frame, int i, const matrix3x4 &m, matrix3x4 &n) {} void calcbb(int frame, vec &bbmin, vec &bbmax, const matrix3x4 &m) { loopv(meshes) meshes[i]->calcbb(frame, bbmin, bbmax, m); } void gentris(int frame, vector &skins, vector *tris, const matrix3x4 &m) { loopv(meshes) meshes[i]->gentris(frame, skins[i].tex && skins[i].tex->bpp == 4 ? skins[i].tex : NULL, tris, m); } virtual int totalframes() const { return 1; } bool hasframe(int i) const { return i>=0 && i=0 && i+n<=totalframes(); } int clipframes(int i, int n) const { return min(n, totalframes() - i); } virtual void cleanup() {} virtual void render(const animstate *as, float pitch, const vec &axis, const vec &forward, dynent *d, part *p) {} }; virtual meshgroup *loadmeshes(char *name, va_list args) { return NULL; } meshgroup *sharemeshes(char *name, ...) { static hashtable meshgroups; if(!meshgroups.access(name)) { va_list args; va_start(args, name); meshgroup *group = loadmeshes(name, args); va_end(args); if(!group) return NULL; meshgroups[group->name] = group; } return meshgroups[name]; } struct linkedpart { part *p; int tag, anim, basetime; vec translate; vec *pos; glmatrixf matrix; linkedpart() : p(NULL), tag(-1), anim(-1), basetime(0), translate(0, 0, 0), pos(NULL) {} }; struct part { animmodel *model; int index; meshgroup *meshes; vector links; vector skins; vector *anims[MAXANIMPARTS]; int numanimparts; float pitchscale, pitchoffset, pitchmin, pitchmax; vec translate; part() : meshes(NULL), numanimparts(1), pitchscale(1), pitchoffset(0), pitchmin(0), pitchmax(0), translate(0, 0, 0) { loopk(MAXANIMPARTS) anims[k] = NULL; } virtual ~part() { loopk(MAXANIMPARTS) DELETEA(anims[k]); } virtual void cleanup() { if(meshes) meshes->cleanup(); } void calcbb(int frame, vec &bbmin, vec &bbmax, const matrix3x4 &m) { matrix3x4 t = m; t.translate(translate); t.scale(model->scale); meshes->calcbb(frame, bbmin, bbmax, t); loopv(links) { matrix3x4 n; meshes->concattagtransform(this, frame, links[i].tag, m, n); n.transformedtranslate(links[i].translate, model->scale); links[i].p->calcbb(frame, bbmin, bbmax, n); } } void gentris(int frame, vector *tris, const matrix3x4 &m) { matrix3x4 t = m; t.translate(translate); t.scale(model->scale); meshes->gentris(frame, skins, tris, t); loopv(links) { matrix3x4 n; meshes->concattagtransform(this, frame, links[i].tag, m, n); n.transformedtranslate(links[i].translate, model->scale); links[i].p->gentris(frame, tris, n); } } bool link(part *p, const char *tag, const vec &translate = vec(0, 0, 0), int anim = -1, int basetime = 0, vec *pos = NULL) { int i = meshes ? meshes->findtag(tag) : -1; if(i<0) { loopvrev(links) if(links[i].p && links[i].p->link(p, tag, translate, anim, basetime, pos)) return true; return false; } linkedpart &l = links.add(); l.p = p; l.tag = i; l.anim = anim; l.basetime = basetime; l.translate = translate; l.pos = pos; return true; } bool unlink(part *p) { loopvrev(links) if(links[i].p==p) { links.remove(i, 1); return true; } loopv(links) if(links[i].p && links[i].p->unlink(p)) return true; return false; } void initskins(Texture *tex = notexture, Texture *masks = notexture, int limit = 0) { if(!limit) { if(!meshes) return; limit = meshes->meshes.length(); } while(skins.length() < limit) { skin &s = skins.add(); s.owner = this; s.tex = tex; s.masks = masks; } } void preloadBIH() { loopv(skins) skins[i].preloadBIH(); } void preloadshaders() { loopv(skins) skins[i].preloadshader(); } virtual void getdefaultanim(animinfo &info, int anim, uint varseed, dynent *d) { info.frame = 0; info.range = 1; } bool calcanim(int animpart, int anim, int basetime, int basetime2, dynent *d, int interp, animinfo &info, int &aitime) { uint varseed = uint((size_t)d); info.anim = anim; info.basetime = basetime; info.varseed = varseed; info.speed = anim&ANIM_SETSPEED ? basetime2 : 100.0f; if((anim&ANIM_INDEX)==ANIM_ALL) { info.frame = 0; info.range = meshes->totalframes(); } else { animspec *spec = NULL; if(anims[animpart]) { vector &primary = anims[animpart][anim&ANIM_INDEX]; if(&primary < &anims[animpart][NUMANIMS] && primary.length()) spec = &primary[uint(varseed + basetime)%primary.length()]; if((anim>>ANIM_SECONDARY)&(ANIM_INDEX|ANIM_DIR)) { vector &secondary = anims[animpart][(anim>>ANIM_SECONDARY)&ANIM_INDEX]; if(&secondary < &anims[animpart][NUMANIMS] && secondary.length()) { animspec &spec2 = secondary[uint(varseed + basetime2)%secondary.length()]; if(!spec || spec2.priority > spec->priority) { spec = &spec2; info.anim >>= ANIM_SECONDARY; info.basetime = basetime2; } } } } if(spec) { info.frame = spec->frame; info.range = spec->range; if(spec->speed>0) info.speed = 1000.0f/spec->speed; } else getdefaultanim(info, anim, uint(varseed + info.basetime), d); } info.anim &= (1<hasframes(info.frame, info.range)) { if(!meshes->hasframe(info.frame)) return false; info.range = meshes->clipframes(info.frame, info.range); } if(d && interp>=0) { animinterpinfo &ai = d->animinterp[interp]; if((info.anim&ANIM_CLAMP)==ANIM_CLAMP) aitime = min(aitime, int(info.range*info.speed*0.5e-3f)); if(d->ragdoll && !(anim&ANIM_RAGDOLL)) { ai.prev.range = ai.cur.range = 0; ai.lastswitch = -1; } else if(ai.lastmodel!=this || ai.lastswitch<0 || lastmillis-d->lastrendered>aitime) { ai.prev = ai.cur = info; ai.lastswitch = lastmillis-aitime*2; } else if(ai.cur!=info) { if(lastmillis-ai.lastswitch>aitime/2) ai.prev = ai.cur; ai.cur = info; ai.lastswitch = lastmillis; } else if(info.anim&ANIM_SETTIME) ai.cur.basetime = info.basetime; ai.lastmodel = this; } return true; } void render(int anim, int basetime, int basetime2, float pitch, const vec &axis, const vec &forward, dynent *d) { animstate as[MAXANIMPARTS]; render(anim, basetime, basetime2, pitch, axis, forward, d, as); } void render(int anim, int basetime, int basetime2, float pitch, const vec &axis, const vec &forward, dynent *d, animstate *as) { if(!(anim&ANIM_REUSE)) loopi(numanimparts) { animinfo info; int interp = d && index+numanimparts<=MAXANIMPARTS ? index+i : -1, aitime = animationinterpolationtime; if(!calcanim(i, anim, basetime, basetime2, d, interp, info, aitime)) return; animstate &p = as[i]; p.owner = this; p.cur.setframes(info); p.interp = 1; if(interp>=0 && d->animinterp[interp].prev.range>0) { int diff = lastmillis-d->animinterp[interp].lastswitch; if(diffaniminterp[interp].prev); p.interp = diff/float(aitime); } } } vec oaxis, oforward; matrixstack[matrixpos].transposedtransformnormal(axis, oaxis); float pitchamount = pitchscale*pitch + pitchoffset; if(pitchmin || pitchmax) pitchamount = clamp(pitchamount, pitchmin, pitchmax); if(as->cur.anim&ANIM_NOPITCH || (as->interp < 1 && as->prev.anim&ANIM_NOPITCH)) pitchamount *= (as->cur.anim&ANIM_NOPITCH ? 0 : as->interp) + (as->interp < 1 && as->prev.anim&ANIM_NOPITCH ? 0 : 1-as->interp); if(pitchamount) { ++matrixpos; matrixstack[matrixpos] = matrixstack[matrixpos-1]; matrixstack[matrixpos].rotate(pitchamount*RAD, oaxis); } matrixstack[matrixpos].transposedtransformnormal(forward, oforward); if(!(anim&ANIM_NORENDER)) { glPushMatrix(); glMultMatrixf(matrixstack[matrixpos].v); if(model->scale!=1) glScalef(model->scale, model->scale, model->scale); if(!translate.iszero()) glTranslatef(translate.x, translate.y, translate.z); if(renderpath!=R_FIXEDFUNCTION && envmaptmu>=0) { glMatrixMode(GL_TEXTURE); glLoadMatrixf(matrixstack[matrixpos].v); glMatrixMode(GL_MODELVIEW); } } if(!(anim&(ANIM_NOSKIN|ANIM_NORENDER))) { if(renderpath!=R_FIXEDFUNCTION) { vec odir, ocampos; matrixstack[matrixpos].transposedtransformnormal(lightdir, odir); setenvparamf("lightdir", SHPARAM_VERTEX, 0, odir.x, odir.y, odir.z); setenvparamf("lightdir", SHPARAM_PIXEL, 0, odir.x, odir.y, odir.z); matrixstack[matrixpos].transposedtransform(camera1->o, ocampos); ocampos.div(model->scale).sub(translate); setenvparamf("camera", SHPARAM_VERTEX, 1, ocampos.x, ocampos.y, ocampos.z, 1); } } meshes->render(as, pitch, oaxis, oforward, d, this); if(!(anim&ANIM_NORENDER)) { glPopMatrix(); } if(!(anim&ANIM_REUSE)) { loopv(links) { linkedpart &link = links[i]; link.matrix.transformedtranslate(links[i].translate, model->scale); matrixpos++; matrixstack[matrixpos].mul(matrixstack[matrixpos-1], link.matrix); if(link.pos) *link.pos = matrixstack[matrixpos].gettranslation(); if(!link.p) { matrixpos--; continue; } int nanim = anim, nbasetime = basetime, nbasetime2 = basetime2; if(link.anim>=0) { nanim = link.anim | (anim&ANIM_FLAGS); nbasetime = link.basetime; nbasetime2 = 0; } link.p->render(nanim, nbasetime, nbasetime2, pitch, axis, forward, d); matrixpos--; } } if(pitchamount) matrixpos--; } void setanim(int animpart, int num, int frame, int range, float speed, int priority = 0) { if(animpart<0 || animpart>=MAXANIMPARTS) return; if(frame<0 || range<=0 || !meshes || !meshes->hasframes(frame, range)) { conoutf("invalid frame %d, range %d in model %s", frame, range, model->loadname); return; } if(!anims[animpart]) anims[animpart] = new vector[NUMANIMS]; animspec &spec = anims[animpart][num].add(); spec.frame = frame; spec.range = range; spec.speed = speed; spec.priority = priority; } }; enum { LINK_TAG = 0, LINK_COOP, LINK_REUSE }; virtual int linktype(animmodel *m) const { return LINK_TAG; } void render(int anim, int basetime, int basetime2, float pitch, const vec &axis, const vec &forward, dynent *d, modelattach *a) { if(!loaded) return; int numtags = 0; if(a) { int index = parts.last()->index + parts.last()->numanimparts; for(int i = 0; a[i].tag; i++) { numtags++; animmodel *m = (animmodel *)a[i].m; if(!m || !m->loaded) { if(a[i].pos) link(NULL, a[i].tag, vec(0, 0, 0), 0, 0, a[i].pos); continue; } part *p = m->parts[0]; switch(linktype(m)) { case LINK_TAG: p->index = link(p, a[i].tag, vec(0, 0, 0), a[i].anim, a[i].basetime, a[i].pos) ? index : -1; break; case LINK_COOP: p->index = index; break; default: continue; } index += p->numanimparts; } } animstate as[MAXANIMPARTS]; parts[0]->render(anim, basetime, basetime2, pitch, axis, forward, d, as); if(a) for(int i = numtags-1; i >= 0; i--) { animmodel *m = (animmodel *)a[i].m; if(!m || !m->loaded) { if(a[i].pos) unlink(NULL); continue; } part *p = m->parts[0]; switch(linktype(m)) { case LINK_TAG: if(p->index >= 0) unlink(p); p->index = 0; break; case LINK_COOP: p->render(anim, basetime, basetime2, pitch, axis, forward, d); p->index = 0; break; case LINK_REUSE: p->render(anim | ANIM_REUSE, basetime, basetime2, pitch, axis, forward, d, as); break; } } } void render(int anim, int basetime, int basetime2, const vec &o, float yaw, float pitch, float roll, dynent *d, modelattach *a, const vec &color, const vec &dir, float trans) { if(!loaded) return; yaw += spinyaw*lastmillis/1000.0f; pitch += offsetpitch + spinpitch*lastmillis/1000.0f; roll += offsetroll + spinroll*lastmillis/1000.0f; vec axis(0, -1, 0), forward(1, 0, 0); matrixpos = 0; matrixstack[0].identity(); if(!d || !d->ragdoll || anim&ANIM_RAGDOLL) { matrixstack[0].translate(o); matrixstack[0].rotate_around_z(yaw*RAD); matrixstack[0].rotate_around_x(-roll * RAD); matrixstack[0].transformnormal(vec(axis), axis); matrixstack[0].transformnormal(vec(forward), forward); if(offsetyaw) matrixstack[0].rotate_around_z(offsetyaw*RAD); } else pitch = 0; if(anim&ANIM_NORENDER) { render(anim, basetime, basetime2, pitch, axis, forward, d, a); if(d) d->lastrendered = lastmillis; return; } if(!(anim&ANIM_NOSKIN)) { if(renderpath==R_FIXEDFUNCTION && lightmodels) { GLfloat pos[4] = { dir.x*1000, dir.y*1000, dir.z*1000, 0 }; glLightfv(GL_LIGHT0, GL_POSITION, pos); } transparent = trans; lightdir = dir; lightcolor = color; if(envmapped()) envmaptmu = 2; else if(a) for(int i = 0; a[i].tag; i++) if(a[i].m && a[i].m->envmapped()) { envmaptmu = 2; break; } if(envmaptmu>=0) closestenvmaptex = lookupenvmap(closestenvmap(o)); } if(depthoffset && !enabledepthoffset) { enablepolygonoffset(GL_POLYGON_OFFSET_FILL); enabledepthoffset = true; } if(envmaptmu>=0) { if(renderpath==R_FIXEDFUNCTION) { glActiveTexture_(GL_TEXTURE0_ARB+envmaptmu); setuptmu(envmaptmu, "T , P @ Pa", hasTEX || hasTE4 ? "Ca * $1a" : "= Ca"); glMatrixMode(GL_TEXTURE); glLoadMatrixf(envmatrix.v); glMatrixMode(GL_MODELVIEW); glActiveTexture_(GL_TEXTURE0_ARB); } else { setenvparamf("lightdirworld", SHPARAM_PIXEL, 1, dir.x, dir.y, dir.z); } } if(transparent<1) { if(anim&ANIM_GHOST) { glDepthFunc(GL_GREATER); glDepthMask(GL_FALSE); } else if(alphadepth) { glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); render(anim|ANIM_NOSKIN, basetime, basetime2, pitch, axis, forward, d, a); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, fading ? GL_FALSE : GL_TRUE); glDepthFunc(GL_LEQUAL); } if(!enablealphablend) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); enablealphablend = true; } } render(anim, basetime, basetime2, pitch, axis, forward, d, a); if(envmaptmu>=0) { if(renderpath==R_FIXEDFUNCTION) glActiveTexture_(GL_TEXTURE0_ARB+envmaptmu); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); if(renderpath==R_FIXEDFUNCTION) glActiveTexture_(GL_TEXTURE0_ARB); } if(transparent<1 && (alphadepth || anim&ANIM_GHOST)) { glDepthFunc(GL_LESS); if(anim&ANIM_GHOST) glDepthMask(GL_TRUE); } if(d) d->lastrendered = lastmillis; } bool loaded; char *loadname; vector parts; animmodel(const char *name) : loaded(false) { loadname = newstring(name); } virtual ~animmodel() { delete[] loadname; parts.deletecontents(); } const char *name() const { return loadname; } void cleanup() { loopv(parts) parts[i]->cleanup(); enablelight0 = false; } void initmatrix(matrix3x4 &m) { m.identity(); if(offsetyaw) m.rotate_around_z(offsetyaw*RAD); if(offsetroll) m.rotate_around_x(-offsetroll*RAD); if(offsetpitch) m.rotate_around_y(-offsetpitch*RAD); } void gentris(int frame, vector *tris) { if(parts.empty()) return; matrix3x4 m; initmatrix(m); parts[0]->gentris(frame, tris, m); } void preloadBIH() { model::preloadBIH(); if(bih) loopv(parts) parts[i]->preloadBIH(); } BIH *setBIH() { if(bih) return bih; vector tris[2]; gentris(0, tris); bih = new BIH(tris); return bih; } bool link(part *p, const char *tag, const vec &translate = vec(0, 0, 0), int anim = -1, int basetime = 0, vec *pos = NULL) { if(parts.empty()) return false; return parts[0]->link(p, tag, translate, anim, basetime, pos); } bool unlink(part *p) { if(parts.empty()) return false; return parts[0]->unlink(p); } bool envmapped() { loopv(parts) loopvj(parts[i]->skins) if(parts[i]->skins[j].envmapped()) return true; return false; } virtual bool loaddefaultparts() { return true; } void preloadshaders() { loopv(parts) parts[i]->preloadshaders(); } void setshader(Shader *shader) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].shader = shader; } void setenvmap(float envmapmin, float envmapmax, Texture *envmap) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) { skin &s = parts[i]->skins[j]; if(envmapmax) { s.envmapmin = envmapmin; s.envmapmax = envmapmax; } if(envmap) s.envmap = envmap; } } void setspec(float spec) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].spec = spec; } void setambient(float ambient) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].ambient = ambient; } void setglow(float glow, float delta, float pulse) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) { skin &s = parts[i]->skins[j]; s.glow = glow; s.glowdelta = delta; s.glowpulse = pulse; } } void setglare(float specglare, float glowglare) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) { skin &s = parts[i]->skins[j]; s.specglare = specglare; s.glowglare = glowglare; } } void setalphatest(float alphatest) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].alphatest = alphatest; } void setalphablend(bool alphablend) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].alphablend = alphablend; } void setfullbright(float fullbright) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].fullbright = fullbright; } void setcullface(bool cullface) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].cullface = cullface; } void calcbb(int frame, vec ¢er, vec &radius) { if(parts.empty()) return; vec bbmin(1e16f, 1e16f, 1e16f), bbmax(-1e16f, -1e16f, -1e16f); matrix3x4 m; initmatrix(m); parts[0]->calcbb(frame, bbmin, bbmax, m); radius = bbmax; radius.sub(bbmin); radius.mul(0.5f); center = bbmin; center.add(radius); } static bool enabletc, enablemtc, enablealphatest, enablealphablend, enableenvmap, enableglow, enableoverbright, enablelighting, enablelight0, enablecullface, enablenormals, enabletangents, enablebones, enablerescale, enabledepthoffset; static vec lightdir, lightcolor; static float transparent, lastalphatest; static void *lastvbuf, *lasttcbuf, *lastmtcbuf, *lastnbuf, *lastxbuf, *lastbbuf, *lastsdata, *lastbdata; static GLuint lastebuf, lastenvmaptex, closestenvmaptex; static Texture *lasttex, *lastmasks, *lastnormalmap; static int envmaptmu, matrixpos; static glmatrixf matrixstack[64]; void startrender() { enabletc = enablemtc = enablealphatest = enablealphablend = enableenvmap = enableglow = enableoverbright = enablelighting = enablenormals = enabletangents = enablebones = enablerescale = enabledepthoffset = false; enablecullface = true; lastalphatest = -1; lastvbuf = lasttcbuf = lastmtcbuf = lastxbuf = lastnbuf = lastbbuf = lastsdata = lastbdata = NULL; lastebuf = lastenvmaptex = closestenvmaptex = 0; lasttex = lastmasks = lastnormalmap = NULL; envmaptmu = -1; transparent = 1; if(renderpath==R_FIXEDFUNCTION && lightmodels && !enablelight0) { glEnable(GL_LIGHT0); static const GLfloat zero[4] = { 0, 0, 0, 0 }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, zero); glLightfv(GL_LIGHT0, GL_SPECULAR, zero); glMaterialfv(GL_FRONT, GL_SPECULAR, zero); glMaterialfv(GL_FRONT, GL_EMISSION, zero); enablelight0 = true; } } static void disablebones() { glDisableVertexAttribArray_(6); glDisableVertexAttribArray_(7); enablebones = false; } static void disabletangents() { glDisableVertexAttribArray_(1); enabletangents = false; } static void disablemtc() { glClientActiveTexture_(GL_TEXTURE1_ARB); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glClientActiveTexture_(GL_TEXTURE0_ARB); enablemtc = false; } static void disabletc() { glDisableClientState(GL_TEXTURE_COORD_ARRAY); if(enablemtc) disablemtc(); enabletc = false; } static void disablenormals() { glDisableClientState(GL_NORMAL_ARRAY); enablenormals = false; } static void disablevbo() { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); if(enabletc) disabletc(); if(enablenormals) disablenormals(); if(enabletangents) disabletangents(); if(enablebones) disablebones(); lastvbuf = lasttcbuf = lastmtcbuf = lastxbuf = lastnbuf = lastbbuf = NULL; lastebuf = 0; } static void disableoverbright() { resettmu(0); enableoverbright = false; } static void disableglow() { resettmu(0); glActiveTexture_(GL_TEXTURE1_ARB); resettmu(1); glDisable(GL_TEXTURE_2D); glActiveTexture_(GL_TEXTURE0_ARB); lasttex = lastmasks = NULL; enableglow = false; } static void disableenvmap(bool cleanup = false) { glActiveTexture_(GL_TEXTURE0_ARB+envmaptmu); if(enableenvmap) glDisable(GL_TEXTURE_CUBE_MAP_ARB); if(cleanup && renderpath==R_FIXEDFUNCTION) { resettmu(envmaptmu); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_R); } glActiveTexture_(GL_TEXTURE0_ARB); enableenvmap = false; } void endrender() { if(lastvbuf || lastebuf) disablevbo(); if(enablealphatest) glDisable(GL_ALPHA_TEST); if(enablealphablend) glDisable(GL_BLEND); if(enableglow) disableglow(); if(enableoverbright) disableoverbright(); if(enablelighting) glDisable(GL_LIGHTING); if(lastenvmaptex) disableenvmap(true); if(enablerescale) glDisable(hasRN ? GL_RESCALE_NORMAL_EXT : GL_NORMALIZE); if(!enablecullface) glEnable(GL_CULL_FACE); if(enabledepthoffset) disablepolygonoffset(GL_POLYGON_OFFSET_FILL); } }; bool animmodel::enabletc = false, animmodel::enablemtc = false, animmodel::enablealphatest = false, animmodel::enablealphablend = false, animmodel::enableenvmap = false, animmodel::enableglow = false, animmodel::enableoverbright = false, animmodel::enablelighting = false, animmodel::enablelight0 = false, animmodel::enablecullface = true, animmodel::enablenormals = false, animmodel::enabletangents = false, animmodel::enablebones = false, animmodel::enablerescale = false, animmodel::enabledepthoffset = false; vec animmodel::lightdir(0, 0, 1), animmodel::lightcolor(1, 1, 1); float animmodel::transparent = 1, animmodel::lastalphatest = -1; void *animmodel::lastvbuf = NULL, *animmodel::lasttcbuf = NULL, *animmodel::lastmtcbuf = NULL, *animmodel::lastnbuf = NULL, *animmodel::lastxbuf = NULL, *animmodel::lastbbuf = NULL, *animmodel::lastsdata = NULL, *animmodel::lastbdata = NULL; GLuint animmodel::lastebuf = 0, animmodel::lastenvmaptex = 0, animmodel::closestenvmaptex = 0; Texture *animmodel::lasttex = NULL, *animmodel::lastmasks = NULL, *animmodel::lastnormalmap = NULL; int animmodel::envmaptmu = -1, animmodel::matrixpos = 0; glmatrixf animmodel::matrixstack[64]; template struct modelloader { static MDL *loading; static string dir; static bool animated() { return true; } static bool multiparted() { return true; } static bool multimeshed() { return true; } }; template MDL *modelloader::loading = NULL; template string modelloader::dir = ""; template struct modelcommands { typedef struct MDL::part part; typedef struct MDL::skin skin; static void setdir(char *name) { if(!MDL::loading) { conoutf("not loading an %s", MDL::formatname()); return; } formatstring(MDL::dir)("packages/models/%s", name); } #define loopmeshes(meshname, m, body) \ if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } \ part &mdl = *MDL::loading->parts.last(); \ if(!mdl.meshes) return; \ loopv(mdl.meshes->meshes) \ { \ MESH &m = *(MESH *)mdl.meshes->meshes[i]; \ if(!strcmp(meshname, "*") || (m.name && !strcmp(m.name, meshname))) \ { \ body; \ } \ } #define loopskins(meshname, s, body) loopmeshes(meshname, m, { skin &s = mdl.skins[i]; body; }) static void setskin(char *meshname, char *tex, char *masks, float *envmapmax, float *envmapmin) { loopskins(meshname, s, s.tex = textureload(makerelpath(MDL::dir, tex), 0, true, false); if(*masks) { s.masks = textureload(makerelpath(MDL::dir, masks, ""), 0, true, false); s.envmapmax = *envmapmax; s.envmapmin = *envmapmin; } ); } static void setspec(char *meshname, int *percent) { float spec = 1.0f; if(*percent>0) spec = *percent/100.0f; else if(*percent<0) spec = 0.0f; loopskins(meshname, s, s.spec = spec); } static void setambient(char *meshname, int *percent) { float ambient = 0.3f; if(*percent>0) ambient = *percent/100.0f; else if(*percent<0) ambient = 0.0f; loopskins(meshname, s, s.ambient = ambient); } static void setglow(char *meshname, int *percent, int *delta, float *pulse) { float glow = 3.0f, glowdelta = *delta/100.0f, glowpulse = *pulse > 0 ? *pulse/1000.0f : 0; if(*percent>0) glow = *percent/100.0f; else if(*percent<0) glow = 0.0f; glowdelta -= glow; loopskins(meshname, s, {s.glow = glow; s.glowdelta = glowdelta; s.glowpulse = glowpulse;}); } static void setglare(char *meshname, float *specglare, float *glowglare) { loopskins(meshname, s, { s.specglare = *specglare; s.glowglare = *glowglare; }); } static void setalphatest(char *meshname, float *cutoff) { loopskins(meshname, s, s.alphatest = max(0.0f, min(1.0f, *cutoff))); } static void setalphablend(char *meshname, int *blend) { loopskins(meshname, s, s.alphablend = *blend!=0); } static void setcullface(char *meshname, int *cullface) { loopskins(meshname, s, s.cullface = *cullface!=0); } static void setenvmap(char *meshname, char *envmap) { Texture *tex = cubemapload(envmap); loopskins(meshname, s, s.envmap = tex); } static void setbumpmap(char *meshname, char *normalmapfile, char *skinfile) { Texture *normalmaptex = NULL, *skintex = NULL; normalmaptex = textureload(makerelpath(MDL::dir, normalmapfile, ""), 0, true, false); if(skinfile[0]) skintex = textureload(makerelpath(MDL::dir, skinfile, ""), 0, true, false); loopskins(meshname, s, { s.unlittex = skintex; s.normalmap = normalmaptex; m.calctangents(); }); } static void setfullbright(char *meshname, float *fullbright) { loopskins(meshname, s, s.fullbright = *fullbright); } static void setshader(char *meshname, char *shader) { loopskins(meshname, s, s.shader = lookupshaderbyname(shader)); } static void setscroll(char *meshname, float *scrollu, float *scrollv) { loopskins(meshname, s, { s.scrollu = *scrollu; s.scrollv = *scrollv; }); } static void setnoclip(char *meshname, int *noclip) { loopmeshes(meshname, m, m.noclip = *noclip!=0); } static void setlink(int *parent, int *child, char *tagname, float *x, float *y, float *z) { if(!MDL::loading) { conoutf("not loading an %s", MDL::formatname()); return; } if(!MDL::loading->parts.inrange(*parent) || !MDL::loading->parts.inrange(*child)) { conoutf("no models loaded to link"); return; } if(!MDL::loading->parts[*parent]->link(MDL::loading->parts[*child], tagname, vec(*x, *y, *z))) conoutf("could not link model %s", MDL::loading->loadname); } template void modelcommand(F *fun, const char *suffix, const char *args) { defformatstring(name)("%s%s", MDL::formatname(), suffix); addcommand(newstring(name), (void (*)())fun, args); } modelcommands() { modelcommand(setdir, "dir", "s"); if(MDL::multimeshed()) { modelcommand(setskin, "skin", "sssff"); modelcommand(setspec, "spec", "si"); modelcommand(setambient, "ambient", "si"); modelcommand(setglow, "glow", "siif"); modelcommand(setglare, "glare", "sff"); modelcommand(setalphatest, "alphatest", "sf"); modelcommand(setalphablend, "alphablend", "si"); modelcommand(setcullface, "cullface", "si"); modelcommand(setenvmap, "envmap", "ss"); modelcommand(setbumpmap, "bumpmap", "sss"); modelcommand(setfullbright, "fullbright", "sf"); modelcommand(setshader, "shader", "ss"); modelcommand(setscroll, "scroll", "sff"); modelcommand(setnoclip, "noclip", "si"); } if(MDL::multiparted()) modelcommand(setlink, "link", "iisfff"); } }; sandboxgamemaker-2.7.1+dfsg/src/engine/obj.h0000664000175000017500000002013511460063014020625 0ustar showardshowardstruct obj; struct obj : vertmodel, vertloader { obj(const char *name) : vertmodel(name) {} static const char *formatname() { return "obj"; } static bool animated() { return false; } int type() const { return MDL_OBJ; } struct objmeshgroup : vertmeshgroup { void parsevert(char *s, vector &out) { vec &v = out.add(vec(0, 0, 0)); while(isalpha(*s)) s++; loopi(3) { v[i] = strtod(s, &s); while(isspace(*s)) s++; if(!*s) break; } } bool load(char *filename, float smooth) { int len = strlen(filename); if(len < 4 || strcasecmp(&filename[len-4], ".obj")) return false; stream *file = openfile(filename, "rb"); if(!file) return false; name = newstring(filename); numframes = 1; vector attrib[3]; char buf[512]; hashtable verthash; vector verts; vector tcverts; vector tris; #define STARTMESH do { \ vertmesh &m = *new vertmesh; \ m.group = this; \ m.name = meshname[0] ? newstring(meshname) : NULL; \ meshes.add(&m); \ curmesh = &m; \ verthash.clear(); \ verts.setsize(0); \ tcverts.setsize(0); \ tris.setsize(0); \ } while(0) #define FLUSHMESH do { \ curmesh->numverts = verts.length(); \ if(verts.length()) \ { \ curmesh->verts = new vert[verts.length()]; \ memcpy(curmesh->verts, verts.getbuf(), verts.length()*sizeof(vert)); \ curmesh->tcverts = new tcvert[verts.length()]; \ memcpy(curmesh->tcverts, tcverts.getbuf(), tcverts.length()*sizeof(tcvert)); \ } \ curmesh->numtris = tris.length(); \ if(tris.length()) \ { \ curmesh->tris = new tri[tris.length()]; \ memcpy(curmesh->tris, tris.getbuf(), tris.length()*sizeof(tri)); \ } \ if(attrib[2].empty()) \ { \ if(smooth <= 1) curmesh->smoothnorms(smooth); \ else curmesh->buildnorms(); \ } \ } while(0) string meshname = ""; vertmesh *curmesh = NULL; while(file->getline(buf, sizeof(buf))) { char *c = buf; while(isspace(*c)) c++; switch(*c) { case '#': continue; case 'v': if(isspace(c[1])) parsevert(c, attrib[0]); else if(c[1]=='t') parsevert(c, attrib[1]); else if(c[1]=='n') parsevert(c, attrib[2]); break; case 'g': { while(isalpha(*c)) c++; while(isspace(*c)) c++; char *name = c; size_t namelen = strlen(name); while(namelen > 0 && isspace(name[namelen-1])) namelen--; copystring(meshname, name, min(namelen+1, sizeof(meshname))); if(curmesh) FLUSHMESH; curmesh = NULL; break; } case 'f': { if(!curmesh) STARTMESH; int v0 = -1, v1 = -1; while(isalpha(*c)) c++; for(;;) { while(isspace(*c)) c++; if(!*c) break; ivec vkey(-1, -1, -1); loopi(3) { vkey[i] = strtol(c, &c, 10); if(vkey[i] < 0) vkey[i] = attrib[i].length() + vkey[i]; else vkey[i]--; if(!attrib[i].inrange(vkey[i])) vkey[i] = -1; if(*c!='/') break; c++; } int *index = verthash.access(vkey); if(!index) { index = &verthash[vkey]; *index = verts.length(); vert &v = verts.add(); v.pos = vkey.x < 0 ? vec(0, 0, 0) : attrib[0][vkey.x]; v.pos = vec(v.pos.z, -v.pos.x, v.pos.y); v.norm = vkey.z < 0 ? vec(0, 0, 0) : attrib[2][vkey.z]; v.norm = vec(v.norm.z, -v.norm.x, v.norm.y); tcvert &tcv = tcverts.add(); if(vkey.y < 0) tcv.u = tcv.v = 0; else { tcv.u = attrib[1][vkey.y].x; tcv.v = 1-attrib[1][vkey.y].y; } } if(v0 < 0) v0 = *index; else if(v1 < 0) v1 = *index; else { tri &t = tris.add(); t.vert[0] = ushort(*index); t.vert[1] = ushort(v1); t.vert[2] = ushort(v0); v1 = *index; } } break; } } } if(curmesh) FLUSHMESH; delete file; return true; } }; meshgroup *loadmeshes(char *name, va_list args) { objmeshgroup *group = new objmeshgroup; if(!group->load(name, va_arg(args, double))) { delete group; return NULL; } return group; } bool loaddefaultparts() { part &mdl = *new part; parts.add(&mdl); mdl.model = this; mdl.index = 0; const char *pname = parentdir(loadname); defformatstring(name1)("packages/models/%s/tris.obj", loadname); mdl.meshes = sharemeshes(path(name1), 2.0); if(!mdl.meshes) { defformatstring(name2)("packages/models/%s/tris.obj", pname); // try obj in parent folder (vert sharing) mdl.meshes = sharemeshes(path(name2), 2.0); if(!mdl.meshes) return false; } Texture *tex, *masks; loadskin(loadname, pname, tex, masks); mdl.initskins(tex, masks); if(tex==notexture) conoutf("could not load model skin for %s", name1); return true; } bool load() { if(loaded) return true; formatstring(dir)("packages/models/%s", loadname); defformatstring(cfgname)("packages/models/%s/obj.cfg", loadname); loading = this; identflags &= ~IDF_PERSIST; if(execfile(cfgname, false) && parts.length()) // configured obj, will call the obj* commands below { identflags |= IDF_PERSIST; loading = NULL; loopv(parts) if(!parts[i]->meshes) return false; } else // obj without configuration, try default tris and skin { identflags |= IDF_PERSIST; loading = NULL; if(!loaddefaultparts()) return false; } scale /= 4; translate.y = -translate.y; parts[0]->translate = translate; loopv(parts) parts[i]->meshes->shared++; preloadshaders(); return loaded = true; } }; vertcommands objcommands; sandboxgamemaker-2.7.1+dfsg/src/engine/rendersky.cpp0000664000175000017500000004705611654260372022442 0ustar showardshoward#include "engine.h" Texture *sky[6] = { 0, 0, 0, 0, 0, 0 }, *clouds[6] = { 0, 0, 0, 0, 0, 0 }; void loadsky(const char *basename, Texture *texs[6]) { const char *wildcard = strchr(basename, '*'); loopi(6) { const char *side = cubemapsides[i].name; string name; copystring(name, makerelpath("packages", basename)); if(wildcard) { char *chop = strchr(name, '*'); if(chop) { *chop = '\0'; concatstring(name, side); concatstring(name, wildcard+1); } texs[i] = textureload(name, 3, true, false); } else { defformatstring(ext)("_%s", side); concatstring(name, ext); texs[i] = textureload(name, 3, true, false); } if(texs[i]==notexture) conoutf(CON_ERROR, "could not load side %s of sky texture %s", side, basename); } } Texture *cloudoverlay = NULL; Texture *loadskyoverlay(const char *basename) { //const char *ext = strrchr(basename, '.'); string name; copystring(name, makerelpath("packages", basename)); Texture *t = notexture; //if(ext) t = textureload(name, 0, true, false); //else //{ t = textureload(name, 0, true, false); //} if(t==notexture) conoutf(CON_ERROR, "could not load sky overlay texture %s", basename); return t; } SVARFR(skybox, "", { if(skybox[0]) loadsky(skybox, sky); }); HVARR(skyboxcolour, 0, 0xFFFFFF, 0xFFFFFF); FVARR(spinsky, -720, 0, 720); VARR(yawsky, 0, 0, 360); SVARFR(cloudbox, "", { if(cloudbox[0]) loadsky(cloudbox, clouds); }); HVARR(cloudboxcolour, 0, 0xFFFFFF, 0xFFFFFF); FVARR(cloudboxalpha, 0, 1, 1); FVARR(spinclouds, -720, 0, 720); VARR(yawclouds, 0, 0, 360); FVARR(cloudclip, 0, 0.5f, 1); SVARFR(cloudlayer, "", { if(cloudlayer[0]) cloudoverlay = loadskyoverlay(cloudlayer); }); FVARR(cloudscrollx, -16, 0, 16); FVARR(cloudscrolly, -16, 0, 16); FVARR(cloudscale, 0.001, 1, 64); FVARR(spincloudlayer, -720, 0, 720); VARR(yawcloudlayer, 0, 0, 360); FVARR(cloudheight, -1, 0.2f, 1); FVARR(cloudfade, 0, 0.2f, 1); FVARR(cloudalpha, 0, 1, 1); VARR(cloudsubdiv, 4, 16, 64); HVARR(cloudcolour, 0, 0xFFFFFF, 0xFFFFFF); void draw_envbox_face(float s0, float t0, int x0, int y0, int z0, float s1, float t1, int x1, int y1, int z1, float s2, float t2, int x2, int y2, int z2, float s3, float t3, int x3, int y3, int z3, GLuint texture) { glBindTexture(GL_TEXTURE_2D, texture); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(s3, t3); glVertex3f(x3, y3, z3); glTexCoord2f(s2, t2); glVertex3f(x2, y2, z2); glTexCoord2f(s0, t0); glVertex3f(x0, y0, z0); glTexCoord2f(s1, t1); glVertex3f(x1, y1, z1); glEnd(); xtraverts += 4; } void draw_envbox(int w, float z1clip = 0.0f, float z2clip = 1.0f, int faces = 0x3F, Texture **sky = NULL) { if(z1clip >= z2clip) return; float v1 = 1-z1clip, v2 = 1-z2clip; int z1 = int(ceil(2*w*(z1clip-0.5f))), z2 = int(ceil(2*w*(z2clip-0.5f))); if(faces&0x01) draw_envbox_face(0.0f, v2, -w, -w, z2, 1.0f, v2, -w, w, z2, 1.0f, v1, -w, w, z1, 0.0f, v1, -w, -w, z1, sky[0] ? sky[0]->id : notexture->id); if(faces&0x02) draw_envbox_face(1.0f, v1, w, -w, z1, 0.0f, v1, w, w, z1, 0.0f, v2, w, w, z2, 1.0f, v2, w, -w, z2, sky[1] ? sky[1]->id : notexture->id); if(faces&0x04) draw_envbox_face(1.0f, v1, -w, -w, z1, 0.0f, v1, w, -w, z1, 0.0f, v2, w, -w, z2, 1.0f, v2, -w, -w, z2, sky[2] ? sky[2]->id : notexture->id); if(faces&0x08) draw_envbox_face(1.0f, v1, w, w, z1, 0.0f, v1, -w, w, z1, 0.0f, v2, -w, w, z2, 1.0f, v2, w, w, z2, sky[3] ? sky[3]->id : notexture->id); if(z1clip <= 0 && faces&0x10) draw_envbox_face(0.0f, 1.0f, -w, w, -w, 0.0f, 0.0f, w, w, -w, 1.0f, 0.0f, w, -w, -w, 1.0f, 1.0f, -w, -w, -w, sky[4] ? sky[4]->id : notexture->id); if(z2clip >= 1 && faces&0x20) draw_envbox_face(0.0f, 1.0f, w, w, w, 0.0f, 0.0f, -w, w, w, 1.0f, 0.0f, -w, -w, w, 1.0f, 1.0f, w, -w, w, sky[5] ? sky[5]->id : notexture->id); } void draw_env_overlay(int w, Texture *overlay = NULL, float tx = 0, float ty = 0) { float z = w*cloudheight, tsz = 0.5f*(1-cloudfade)/cloudscale, psz = w*(1-cloudfade); glBindTexture(GL_TEXTURE_2D, overlay ? overlay->id : notexture->id); float r = (cloudcolour>>16)/255.0f, g = ((cloudcolour>>8)&255)/255.0f, b = (cloudcolour&255)/255.0f; glColor4f(r, g, b, cloudalpha); glBegin(GL_TRIANGLE_FAN); loopi(cloudsubdiv+1) { vec p(1, 1, 0); p.rotate_around_z((-2.0f*M_PI*i)/cloudsubdiv); glTexCoord2f(tx + p.x*tsz, ty + p.y*tsz); glVertex3f(p.x*psz, p.y*psz, z); } glEnd(); float tsz2 = 0.5f/cloudscale; glBegin(GL_TRIANGLE_STRIP); loopi(cloudsubdiv+1) { vec p(1, 1, 0); p.rotate_around_z((-2.0f*M_PI*i)/cloudsubdiv); glColor4f(r, g, b, cloudalpha); glTexCoord2f(tx + p.x*tsz, ty + p.y*tsz); glVertex3f(p.x*psz, p.y*psz, z); glColor4f(r, g, b, 0); glTexCoord2f(tx + p.x*tsz2, ty + p.y*tsz2); glVertex3f(p.x*w, p.y*w, z); } glEnd(); } static struct domevert { vec pos; uchar color[4]; domevert() {} domevert(const vec &pos, const bvec &fcolor, float alpha) : pos(pos) { memcpy(color, fcolor.v, 3); color[3] = uchar(alpha*255); } domevert(const domevert &v0, const domevert &v1) : pos(vec(v0.pos).add(v1.pos).normalize()) { memcpy(color, v0.color, 4); if(v0.pos.z != v1.pos.z) color[3] += uchar((v1.color[3] - v0.color[3]) * (pos.z - v0.pos.z) / (v1.pos.z - v0.pos.z)); } } *domeverts = NULL; static GLushort *domeindices = NULL; static int domenumverts = 0, domenumindices = 0, domecapindices = 0; static GLuint domevbuf = 0, domeebuf = 0; static bvec domecolor(0, 0, 0); static float domeminalpha = 0, domemaxalpha = 0, domecapsize = -1, domeclipz = 1; static void subdivide(int depth, int face); static void genface(int depth, int i1, int i2, int i3) { int face = domenumindices; domenumindices += 3; domeindices[face] = i3; domeindices[face+1] = i2; domeindices[face+2] = i1; subdivide(depth, face); } static void subdivide(int depth, int face) { if(depth-- <= 0) return; int idx[6]; loopi(3) idx[i] = domeindices[face+2-i]; loopi(3) { int vert = domenumverts++; domeverts[vert] = domevert(domeverts[idx[i]], domeverts[idx[(i+1)%3]]); //push on to unit sphere idx[3+i] = vert; domeindices[face+2-i] = vert; } subdivide(depth, face); loopi(3) genface(depth, idx[i], idx[3+i], idx[3+(i+2)%3]); } static int sortdomecap(GLushort x, GLushort y) { const vec &xv = domeverts[x].pos, &yv = domeverts[y].pos; return xv.y < 0 ? yv.y >= 0 || xv.x < yv.x : yv.y >= 0 && xv.x > yv.x; } static void initdome(const bvec &color, float minalpha = 0.0f, float maxalpha = 1.0f, float capsize = -1, float clipz = 1, int hres = 16, int depth = 2) { const int tris = hres << (2*depth); domenumverts = domenumindices = domecapindices = 0; DELETEA(domeverts); DELETEA(domeindices); domeverts = new domevert[tris+1 + (capsize >= 0 ? 1 : 0)]; domeindices = new GLushort[(tris + (capsize >= 0 ? hres<= 1) { domeverts[domenumverts++] = domevert(vec(0.0f, 0.0f, 1.0f), color, minalpha); //build initial 'hres' sided pyramid loopi(hres) { float angle = 2*M_PI*float(i)/hres; domeverts[domenumverts++] = domevert(vec(cosf(angle), sinf(angle), 0.0f), color, maxalpha); } loopi(hres) genface(depth, 0, i+1, 1+(i+1)%hres); } else if(clipz <= 0) { loopi(hres<= 0) { GLushort *domecap = &domeindices[domenumindices]; int domecapverts = 0; loopi(domenumverts) if(!domeverts[i].pos.z) domecap[domecapverts++] = i; domeverts[domenumverts++] = domevert(vec(0.0f, 0.0f, -capsize), color, maxalpha); quicksort(domecap, domecapverts, sortdomecap); loopi(domecapverts) { int n = domecapverts-1-i; domecap[n*3] = domecap[n]; domecap[n*3+1] = domecap[(n+1)%domecapverts]; domecap[n*3+2] = domenumverts-1; domecapindices += 3; } } if(hasVBO) { if(!domevbuf) glGenBuffers_(1, &domevbuf); glBindBuffer_(GL_ARRAY_BUFFER_ARB, domevbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, domenumverts*sizeof(domevert), domeverts, GL_STATIC_DRAW_ARB); DELETEA(domeverts); if(!domeebuf) glGenBuffers_(1, &domeebuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, domeebuf); glBufferData_(GL_ELEMENT_ARRAY_BUFFER_ARB, (domenumindices + domecapindices)*sizeof(GLushort), domeindices, GL_STATIC_DRAW_ARB); DELETEA(domeindices); } } static void deletedome() { domenumverts = domenumindices = 0; if(domevbuf) { glDeleteBuffers_(1, &domevbuf); domevbuf = 0; } if(domeebuf) { glDeleteBuffers_(1, &domeebuf); domeebuf = 0; } DELETEA(domeverts); DELETEA(domeindices); } FVARR(fogdomeheight, -1, -0.5f, 1); FVARR(fogdomemin, 0, 0, 1); FVARR(fogdomemax, 0, 0, 1); VARR(fogdomecap, 0, 1, 1); FVARR(fogdomeclip, 0, 1, 1); bvec fogdomecolor(0, 0, 0); HVARFR(fogdomecolour, 0, 0, 0xFFFFFF, { fogdomecolor = bvec((fogdomecolour>>16)&0xFF, (fogdomecolour>>8)&0xFF, fogdomecolour&0xFF); }); static void drawdome() { float capsize = fogdomecap && fogdomeheight < 1 ? (1 + fogdomeheight) / (1 - fogdomeheight) : -1; bvec color = fogdomecolour ? fogdomecolor : fogcolor; if(!domenumverts || domecolor != color || domeminalpha != fogdomemin || domemaxalpha != fogdomemax || domecapsize != capsize || domeclipz != fogdomeclip) { initdome(color, min(fogdomemin, fogdomemax), fogdomemax, capsize, fogdomeclip); domecolor = color; domeminalpha = fogdomemin; domemaxalpha = fogdomemax; domecapsize = capsize; domeclipz = fogdomeclip; } if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, domevbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, domeebuf); } glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(domevert), &domeverts->pos); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(domevert), &domeverts->color); if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, 0, domenumverts-1, domenumindices + fogdomecap*domecapindices, GL_UNSIGNED_SHORT, domeindices); else glDrawElements(GL_TRIANGLES, domenumindices + fogdomecap*domecapindices, GL_UNSIGNED_SHORT, domeindices); xtraverts += domenumverts; glde++; glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } } void cleanupsky() { deletedome(); } VARP(sparklyfix, 0, 0, 1); VAR(showsky, 0, 1, 1); VAR(clipsky, 0, 1, 1); bool drawskylimits(bool explicitonly) { nocolorshader->set(); glDisable(GL_TEXTURE_2D); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); bool rendered = rendersky(explicitonly); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glEnable(GL_TEXTURE_2D); return rendered; } void drawskyoutline() { lineshader->set(); glDisable(GL_TEXTURE_2D); glDepthMask(GL_FALSE); extern int wireframe; if(!wireframe) { enablepolygonoffset(GL_POLYGON_OFFSET_LINE); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } glColor3f(0.5f, 0.0f, 0.5f); rendersky(true); if(!wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); disablepolygonoffset(GL_POLYGON_OFFSET_LINE); } glDepthMask(GL_TRUE); glEnable(GL_TEXTURE_2D); if(!glaring) defaultshader->set(); } VAR(clampsky, 0, 1, 1); VARR(fogdomeclouds, 0, 1, 1); static void drawfogdome(int farplane) { notextureshader->set(); glDisable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glLoadMatrixf(viewmatrix.v); glRotatef(camera1->roll, 0, 1, 0); glRotatef(camera1->pitch, -1, 0, 0); glRotatef(camera1->yaw, 0, 0, -1); if(reflecting) glScalef(1, 1, -1); glTranslatef(0, 0, farplane*fogdomeheight*0.5f); glScalef(farplane/2, farplane/2, farplane*(0.5f - fogdomeheight*0.5f)); drawdome(); glPopMatrix(); glDisable(GL_BLEND); glEnable(GL_TEXTURE_2D); } static int yawskyfaces(int faces, int yaw, float spin = 0) { if(spin || yaw%90) return faces&0x0F ? faces | 0x0F : faces; static const int faceidxs[3][4] = { { 3, 2, 0, 1 }, { 1, 0, 3, 2 }, { 2, 3, 1, 0 } }; yaw /= 90; if(yaw < 1 || yaw > 3) return faces; const int *idxs = faceidxs[yaw - 1]; return (faces & ~0x0F) | (((faces>>idxs[0])&1)<<0) | (((faces>>idxs[1])&1)<<1) | (((faces>>idxs[2])&1)<<2) | (((faces>>idxs[3])&1)<<3); } void drawskybox(int farplane, bool limited) { extern int renderedskyfaces, renderedskyclip; // , renderedsky, renderedexplicitsky; bool alwaysrender = editmode || !insideworld(camera1->o) || reflecting, explicitonly = false; if(limited) { explicitonly = alwaysrender || !sparklyfix || refracting; if(!drawskylimits(explicitonly) && !alwaysrender) return; extern int ati_skybox_bug; if(!alwaysrender && !renderedskyfaces && !ati_skybox_bug) explicitonly = false; } else if(!alwaysrender) { extern vtxarray *visibleva; renderedskyfaces = 0; renderedskyclip = INT_MAX; for(vtxarray *va = visibleva; va; va = va->next) { if(va->occluded >= OCCLUDE_BB && va->skyfaces&0x80) continue; renderedskyfaces |= va->skyfaces&0x3F; if(!(va->skyfaces&0x1F) || camera1->o.z < va->skyclip) renderedskyclip = min(renderedskyclip, va->skyclip); else renderedskyclip = 0; } if(!renderedskyfaces) return; } if(alwaysrender) { renderedskyfaces = 0x3F; renderedskyclip = 0; } float skyclip = clipsky ? max(renderedskyclip-1, 0) : 0, topclip = 1; if(reflectzo.z)/float(worldsize); else if(reflectz>skyclip) skyclip = reflectz; } if(skyclip) skyclip = 0.5f + 0.5f*(skyclip-camera1->o.z)/float(worldsize); if(glaring) { static Shader *skyboxglareshader = NULL; if(!skyboxglareshader) skyboxglareshader = lookupshaderbyname("skyboxglare"); skyboxglareshader->set(); } else defaultshader->set(); glDisable(GL_FOG); if(limited) { if(explicitonly) glDisable(GL_DEPTH_TEST); else glDepthFunc(GL_GEQUAL); } else glDepthFunc(GL_LEQUAL); glDepthMask(GL_FALSE); if(clampsky) glDepthRange(1, 1); glColor3f((skyboxcolour>>16)/255.0f, ((skyboxcolour>>8)&255)/255.0f, (skyboxcolour&255)/255.0f); glPushMatrix(); glLoadMatrixf(viewmatrix.v); glRotatef(camera1->roll, 0, 1, 0); glRotatef(camera1->pitch, -1, 0, 0); glRotatef(camera1->yaw+spinsky*lastmillis/1000.0f+yawsky, 0, 0, -1); if(reflecting) glScalef(1, 1, -1); draw_envbox(farplane/2, skyclip, topclip, yawskyfaces(renderedskyfaces, yawsky, spinsky), sky); glPopMatrix(); if(!glaring && fogdomemax && !fogdomeclouds) { if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); drawfogdome(farplane); defaultshader->set(); } if(!glaring && cloudbox[0]) { if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f((cloudboxcolour>>16)/255.0f, ((cloudboxcolour>>8)&255)/255.0f, (cloudboxcolour&255)/255.0f, cloudboxalpha); glPushMatrix(); glLoadMatrixf(viewmatrix.v); glRotatef(camera1->roll, 0, 1, 0); glRotatef(camera1->pitch, -1, 0, 0); glRotatef(camera1->yaw+spinclouds*lastmillis/1000.0f+yawclouds, 0, 0, -1); if(reflecting) glScalef(1, 1, -1); draw_envbox(farplane/2, skyclip ? skyclip : cloudclip, topclip, yawskyfaces(renderedskyfaces, yawclouds, spinclouds), clouds); glPopMatrix(); glDisable(GL_BLEND); } if(!glaring && cloudlayer[0] && cloudheight && renderedskyfaces&(cloudheight < 0 ? 0x1F : 0x2F)) { if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glLoadMatrixf(viewmatrix.v); glRotatef(camera1->roll, 0, 1, 0); glRotatef(camera1->pitch, -1, 0, 0); glRotatef(camera1->yaw+spincloudlayer*lastmillis/1000.0f+yawcloudlayer, 0, 0, -1); if(reflecting) glScalef(1, 1, -1); draw_env_overlay(farplane/2, cloudoverlay, cloudscrollx * lastmillis/1000.0f, cloudscrolly * lastmillis/1000.0f); glPopMatrix(); glDisable(GL_BLEND); glEnable(GL_CULL_FACE); } if(!glaring && fogdomemax && fogdomeclouds) { if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); drawfogdome(farplane); } if(clampsky) glDepthRange(0, 1); glDepthMask(GL_TRUE); if(limited) { if(explicitonly) glEnable(GL_DEPTH_TEST); else glDepthFunc(GL_LESS); if(!reflecting && !refracting && !envmapping && editmode && showsky) drawskyoutline(); } else glDepthFunc(GL_LESS); glEnable(GL_FOG); } VARNR(skytexture, useskytexture, 0, 1, 1); int explicitsky = 0; double skyarea = 0; bool limitsky() { return (explicitsky && (useskytexture || editmode)) || (sparklyfix && skyarea / (double(worldsize)*double(worldsize)*6) < 0.9); } sandboxgamemaker-2.7.1+dfsg/src/engine/master.cpp0000664000175000017500000005044511637730516021726 0ustar showardshoward#include "cube.h" #include #include #define INPUT_LIMIT 4096 #define OUTPUT_LIMIT (64*1024) #define CLIENT_TIME (3*60*1000) #define AUTH_TIME (30*1000) #define AUTH_LIMIT 100 #define AUTH_THROTTLE 1000 #define CLIENT_LIMIT 8192 #define DUP_LIMIT 16 #define PING_TIME 3000 #define PING_RETRY 5 #define KEEPALIVE_TIME (65*60*1000) #define SERVER_LIMIT (10*1024) FILE *logfile = NULL; struct userinfo { char *name; void *pubkey; }; hashtable users; void adduser(char *name, char *pubkey) { name = newstring(name); userinfo &u = users[name]; u.name = name; u.pubkey = parsepubkey(pubkey); } COMMAND(adduser, "ss"); void clearusers() { enumerate(users, userinfo, u, { delete[] u.name; freepubkey(u.pubkey); }); users.clear(); } COMMAND(clearusers, ""); struct baninfo { enet_uint32 ip, mask; }; vector bans, servbans, gbans; void clearbans() { bans.shrink(0); servbans.shrink(0); gbans.shrink(0); } COMMAND(clearbans, ""); void addban(vector &bans, const char *name) { union { uchar b[sizeof(enet_uint32)]; enet_uint32 i; } ip, mask; ip.i = 0; mask.i = 0; loopi(4) { char *end = NULL; int n = strtol(name, &end, 10); if(!end) break; if(end > name) { ip.b[i] = n; mask.b[i] = 0xFF; } name = end; while(*name && *name++ != '.'); } baninfo &ban = bans.add(); ban.ip = ip.i; ban.mask = mask.i; } ICOMMAND(ban, "s", (char *name), addban(bans, name)); ICOMMAND(servban, "s", (char *name), addban(servbans, name)); ICOMMAND(gban, "s", (char *name), addban(gbans, name)); char *printban(const baninfo &ban, char *buf) { union { uchar b[sizeof(enet_uint32)]; enet_uint32 i; } ip, mask; ip.i = ban.ip; mask.i = ban.mask; int lastdigit = -1; loopi(4) if(mask.b[i]) { if(lastdigit >= 0) *buf++ = '.'; loopj(i - lastdigit - 1) { *buf++ = '*'; *buf++ = '.'; } buf += sprintf(buf, "%d", ip.b[i]); lastdigit = i; } return buf; } bool checkban(vector &bans, enet_uint32 host) { loopv(bans) if((host & bans[i].mask) == bans[i].ip) return true; return false; } struct authreq { enet_uint32 reqtime; uint id; void *answer; }; struct gameserver { ENetAddress address; string ip; int port, numpings; enet_uint32 lastping, lastpong; }; vector gameservers; struct messagebuf { vector &owner; vector buf; int refs; messagebuf(vector &owner) : owner(owner), refs(0) {} const char *getbuf() { return buf.getbuf(); } int length() { return buf.length(); } void purge(); bool equals(const messagebuf &m) const { return buf.length() == m.buf.length() && !memcmp(buf.getbuf(), m.buf.getbuf(), buf.length()); } bool endswith(const messagebuf &m) const { return buf.length() >= m.buf.length() && !memcmp(&buf[buf.length() - m.buf.length()], m.buf.getbuf(), m.buf.length()); } void concat(const messagebuf &m) { if(buf.length() && buf.last() == '\0') buf.pop(); buf.put(m.buf.getbuf(), m.buf.length()); } }; vector gameserverlists, gbanlists; bool updateserverlist = true; struct client { ENetAddress address; ENetSocket socket; char input[INPUT_LIMIT]; messagebuf *message; vector output; int inputpos, outputpos; enet_uint32 connecttime, lastinput; int servport; enet_uint32 lastauth; vector authreqs; bool shouldpurge; bool registeredserver; client() : message(NULL), inputpos(0), outputpos(0), servport(-1), lastauth(0), shouldpurge(false), registeredserver(false) {} }; vector clients; ENetSocket serversocket = ENET_SOCKET_NULL; time_t starttime; enet_uint32 servtime = 0; void fatal(const char *fmt, ...) { va_list args; va_start(args, fmt); vfprintf(logfile, fmt, args); fputc('\n', logfile); va_end(args); exit(EXIT_FAILURE); } void conoutfv(int type, const char *fmt, va_list args) { vfprintf(logfile, fmt, args); fputc('\n', logfile); } void conoutf(const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(CON_INFO, fmt, args); va_end(args); } void conoutf(int type, const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(type, fmt, args); va_end(args); } void purgeclient(int n) { client &c = *clients[n]; if(c.message) c.message->purge(); enet_socket_destroy(c.socket); delete clients[n]; clients.remove(n); } void output(client &c, const char *msg, int len = 0) { if(!len) len = strlen(msg); c.output.put(msg, len); } void outputf(client &c, const char *fmt, ...) { string msg; va_list args; va_start(args, fmt); vformatstring(msg, fmt, args); va_end(args); output(c, msg); } ENetSocket pingsocket = ENET_SOCKET_NULL; bool setuppingsocket(ENetAddress *address) { if(pingsocket != ENET_SOCKET_NULL) return true; pingsocket = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM); if(pingsocket == ENET_SOCKET_NULL) return false; if(address && enet_socket_bind(pingsocket, address) < 0) return false; enet_socket_set_option(pingsocket, ENET_SOCKOPT_NONBLOCK, 1); return true; } void setupserver(int port, const char *ip = NULL) { ENetAddress address; address.host = ENET_HOST_ANY; address.port = port; if(ip) { if(enet_address_set_host(&address, ip)<0) fatal("failed to resolve server address: %s", ip); } serversocket = enet_socket_create(ENET_SOCKET_TYPE_STREAM); if(serversocket==ENET_SOCKET_NULL || enet_socket_set_option(serversocket, ENET_SOCKOPT_REUSEADDR, 1) < 0 || enet_socket_bind(serversocket, &address) < 0 || enet_socket_listen(serversocket, -1) < 0) fatal("failed to create server socket"); if(enet_socket_set_option(serversocket, ENET_SOCKOPT_NONBLOCK, 1)<0) fatal("failed to make server socket non-blocking"); if(!setuppingsocket(&address)) fatal("failed to create ping socket"); enet_time_set(0); starttime = time(NULL); char *ct = ctime(&starttime); if(strchr(ct, '\n')) *strchr(ct, '\n') = '\0'; conoutf("*** Starting master server on %s %d at %s ***", ip ? ip : "localhost", port, ct); } void genserverlist() { if(!updateserverlist) return; while(gameserverlists.length() && gameserverlists.last()->refs<=0) delete gameserverlists.pop(); messagebuf *l = new messagebuf(gameserverlists); loopv(gameservers) { gameserver &s = *gameservers[i]; if(!s.lastpong) continue; defformatstring(cmd)("addserver %s %d\n", s.ip, s.port); l->buf.put(cmd, strlen(cmd)); } l->buf.add('\0'); gameserverlists.add(l); updateserverlist = false; } void gengbanlist() { messagebuf *l = new messagebuf(gbanlists); const char *header = "cleargbans\n"; l->buf.put(header, strlen(header)); string cmd = "addgban "; int cmdlen = strlen(cmd); loopv(gbans) { baninfo &b = gbans[i]; l->buf.put(cmd, printban(b, &cmd[cmdlen]) - cmd); l->buf.add('\n'); } if(gbanlists.length() && gbanlists.last()->equals(*l)) { delete l; return; } while(gbanlists.length() && gbanlists.last()->refs<=0) delete gbanlists.pop(); loopv(gbanlists) { messagebuf *m = gbanlists[i]; if(m->refs > 0 && !m->endswith(*l)) m->concat(*l); } gbanlists.add(l); loopv(clients) { client &c = *clients[i]; if(c.servport >= 0 && !c.message) { c.message = l; c.message->refs++; } } } void addgameserver(client &c) { if(gameservers.length() >= SERVER_LIMIT) return; loopv(gameservers) { gameserver &s = *gameservers[i]; if(s.address.host == c.address.host && s.port == c.servport) { s.lastping = 0; s.numpings = 0; return; } } string hostname; if(enet_address_get_host_ip(&c.address, hostname, sizeof(hostname)) < 0) { outputf(c, "failreg failed resolving ip\n"); return; } gameserver &s = *gameservers.add(new gameserver); s.address.host = c.address.host; s.address.port = c.servport+1; copystring(s.ip, hostname); s.port = c.servport; s.numpings = 0; s.lastping = s.lastpong = 0; } client *findclient(gameserver &s) { loopv(clients) { client &c = *clients[i]; if(s.address.host == c.address.host && s.port == c.servport) return &c; } return NULL; } void servermessage(gameserver &s, const char *msg) { client *c = findclient(s); if(c) outputf(*c, msg); } void checkserverpongs() { ENetBuffer buf; ENetAddress addr; static uchar pong[MAXTRANS]; for(;;) { buf.data = pong; buf.dataLength = sizeof(pong); int len = enet_socket_receive(pingsocket, &addr, &buf, 1); if(len <= 0) break; loopv(gameservers) { gameserver &s = *gameservers[i]; if(s.address.host == addr.host && s.address.port == addr.port) { if(s.lastping && (!s.lastpong || ENET_TIME_GREATER(s.lastping, s.lastpong))) { client *c = findclient(s); if(c) { c->registeredserver = true; outputf(*c, "succreg\n"); if(!c->message && gbanlists.length()) { c->message = gbanlists.last(); c->message->refs++; } } } if(!s.lastpong) updateserverlist = true; s.lastpong = servtime ? servtime : 1; break; } } } } void bangameservers() { loopvrev(gameservers) if(checkban(servbans, gameservers[i]->address.host)) { delete gameservers.remove(i); updateserverlist = true; } } void checkgameservers() { ENetBuffer buf; loopv(gameservers) { gameserver &s = *gameservers[i]; if(s.lastping && s.lastpong && ENET_TIME_LESS_EQUAL(s.lastping, s.lastpong)) { if(ENET_TIME_DIFFERENCE(servtime, s.lastpong) > KEEPALIVE_TIME) { delete gameservers.remove(i--); updateserverlist = true; } } else if(!s.lastping || ENET_TIME_DIFFERENCE(servtime, s.lastping) > PING_TIME) { if(s.numpings >= PING_RETRY) { servermessage(s, "failreg failed pinging server\n"); delete gameservers.remove(i--); updateserverlist = true; } else { static const uchar ping[] = { 1 }; buf.data = (void *)ping; buf.dataLength = sizeof(ping); s.numpings++; s.lastping = servtime ? servtime : 1; enet_socket_send(pingsocket, &s.address, &buf, 1); } } } } void messagebuf::purge() { refs = max(refs - 1, 0); if(refs<=0 && owner.last()!=this) { owner.removeobj(this); delete this; } } void purgeauths(client &c) { int expired = 0; loopv(c.authreqs) { if(ENET_TIME_DIFFERENCE(servtime, c.authreqs[i].reqtime) >= AUTH_TIME) { outputf(c, "failauth %u\n", c.authreqs[i].id); freechallenge(c.authreqs[i].answer); expired = i + 1; } else break; } if(expired > 0) c.authreqs.remove(0, expired); } void reqauth(client &c, uint id, char *name) { if(ENET_TIME_DIFFERENCE(servtime, c.lastauth) < AUTH_THROTTLE) return; c.lastauth = servtime; purgeauths(c); time_t t = time(NULL); char *ct = ctime(&t); if(ct) { char *newline = strchr(ct, '\n'); if(newline) *newline = '\0'; } string ip; if(enet_address_get_host_ip(&c.address, ip, sizeof(ip)) < 0) copystring(ip, "-"); conoutf("%s: attempting \"%s\" as %u from %s", ct ? ct : "-", name, id, ip); userinfo *u = users.access(name); if(!u) { outputf(c, "failauth %u\n", id); return; } if(c.authreqs.length() >= AUTH_LIMIT) { outputf(c, "failauth %u\n", c.authreqs[0].id); freechallenge(c.authreqs[0].answer); c.authreqs.remove(0); } authreq &a = c.authreqs.add(); a.reqtime = servtime; a.id = id; uint seed[3] = { starttime, servtime, randomMT() }; static vector buf; buf.setsize(0); a.answer = genchallenge(u->pubkey, seed, sizeof(seed), buf); outputf(c, "chalauth %u %s\n", id, buf.getbuf()); } void confauth(client &c, uint id, const char *val) { purgeauths(c); loopv(c.authreqs) if(c.authreqs[i].id == id) { string ip; if(enet_address_get_host_ip(&c.address, ip, sizeof(ip)) < 0) copystring(ip, "-"); if(checkchallenge(val, c.authreqs[i].answer)) { outputf(c, "succauth %u\n", id); conoutf("succeeded %u from %s", id, ip); } else { outputf(c, "failauth %u\n", id); conoutf("failed %u from %s", id, ip); } freechallenge(c.authreqs[i].answer); c.authreqs.remove(i--); return; } outputf(c, "failauth %u\n", id); } bool checkclientinput(client &c) { if(c.inputpos<0) return true; char *end = (char *)memchr(c.input, '\n', c.inputpos); while(end) { *end++ = '\0'; c.lastinput = servtime; int port; uint id; string user, val; if(!strncmp(c.input, "list", 4) && (!c.input[4] || isspace(c.input[4]))) { genserverlist(); if(gameserverlists.empty() || c.message) return false; c.message = gameserverlists.last(); c.message->refs++; c.output.setsize(0); c.outputpos = 0; c.shouldpurge = true; return true; } else if(sscanf(c.input, "regserv %d", &port) == 1) { if(checkban(servbans, c.address.host)) return false; if(port < 0 || port + 1 < 0 || (c.servport >= 0 && port != c.servport)) outputf(c, "failreg invalid port\n"); else { c.servport = port; addgameserver(c); } } else if(sscanf(c.input, "reqauth %u %100s", &id, user) == 2) { reqauth(c, id, user); } else if(sscanf(c.input, "confauth %u %100s", &id, val) == 2) { confauth(c, id, val); } c.inputpos = &c.input[c.inputpos] - end; memmove(c.input, end, c.inputpos); end = (char *)memchr(c.input, '\n', c.inputpos); } return c.inputpos<(int)sizeof(c.input); } ENetSocketSet readset, writeset; void checkclients() { ENetSocketSet readset, writeset; ENetSocket maxsock = max(serversocket, pingsocket); ENET_SOCKETSET_EMPTY(readset); ENET_SOCKETSET_EMPTY(writeset); ENET_SOCKETSET_ADD(readset, serversocket); ENET_SOCKETSET_ADD(readset, pingsocket); loopv(clients) { client &c = *clients[i]; if(c.authreqs.length()) purgeauths(c); if(c.message || c.output.length()) ENET_SOCKETSET_ADD(writeset, c.socket); else ENET_SOCKETSET_ADD(readset, c.socket); maxsock = max(maxsock, c.socket); } if(enet_socketset_select(maxsock, &readset, &writeset, 1000)<=0) return; if(ENET_SOCKETSET_CHECK(readset, pingsocket)) checkserverpongs(); if(ENET_SOCKETSET_CHECK(readset, serversocket)) { ENetAddress address; ENetSocket clientsocket = enet_socket_accept(serversocket, &address); if(clients.length()>=CLIENT_LIMIT || checkban(bans, address.host)) enet_socket_destroy(clientsocket); else if(clientsocket!=ENET_SOCKET_NULL) { int dups = 0, oldest = -1; loopv(clients) if(clients[i]->address.host == address.host) { dups++; if(oldest<0 || clients[i]->connecttime < clients[oldest]->connecttime) oldest = i; } if(dups >= DUP_LIMIT) purgeclient(oldest); client *c = new client; c->address = address; c->socket = clientsocket; c->connecttime = servtime; c->lastinput = servtime; clients.add(c); } } loopv(clients) { client &c = *clients[i]; if((c.message || c.output.length()) && ENET_SOCKETSET_CHECK(writeset, c.socket)) { const char *data = c.output.length() ? c.output.getbuf() : c.message->getbuf(); int len = c.output.length() ? c.output.length() : c.message->length(); ENetBuffer buf; buf.data = (void *)&data[c.outputpos]; buf.dataLength = len-c.outputpos; int res = enet_socket_send(c.socket, NULL, &buf, 1); if(res>=0) { c.outputpos += res; if(c.outputpos>=len) { if(c.output.length()) c.output.setsize(0); else { c.message->purge(); c.message = NULL; } c.outputpos = 0; if(!c.message && c.output.empty() && c.shouldpurge) { purgeclient(i--); continue; } } } else { purgeclient(i--); continue; } } if(ENET_SOCKETSET_CHECK(readset, c.socket)) { ENetBuffer buf; buf.data = &c.input[c.inputpos]; buf.dataLength = sizeof(c.input) - c.inputpos; int res = enet_socket_receive(c.socket, NULL, &buf, 1); if(res>0) { c.inputpos += res; c.input[min(c.inputpos, (int)sizeof(c.input)-1)] = '\0'; if(!checkclientinput(c)) { purgeclient(i--); continue; } } else { purgeclient(i--); continue; } } if(c.output.length() > OUTPUT_LIMIT) { purgeclient(i--); continue; } if(ENET_TIME_DIFFERENCE(servtime, c.lastinput) >= (c.registeredserver ? KEEPALIVE_TIME : CLIENT_TIME)) { purgeclient(i--); continue; } } } void banclients() { loopvrev(clients) if(checkban(bans, clients[i]->address.host)) purgeclient(i); } volatile bool reloadcfg = true; void reloadsignal(int signum) { reloadcfg = true; } int main(int argc, char **argv) { if(enet_initialize()<0) fatal("Unable to initialise network module"); atexit(enet_deinitialize); const char *dir = "", *ip = NULL; int port = 28787; if(argc>=2) dir = argv[1]; if(argc>=3) port = atoi(argv[2]); if(argc>=4) ip = argv[3]; defformatstring(logname)("%smaster.log", dir); defformatstring(cfgname)("%smaster.cfg", dir); path(logname); path(cfgname); logfile = fopen(logname, "a"); if(!logfile) logfile = stdout; setvbuf(logfile, NULL, _IOLBF, BUFSIZ); #ifndef WIN32 signal(SIGUSR1, reloadsignal); #endif setupserver(port, ip); for(;;) { if(reloadcfg) { conoutf("reloading master.cfg"); execfile(cfgname); bangameservers(); banclients(); gengbanlist(); reloadcfg = false; } servtime = enet_time_get(); checkclients(); checkgameservers(); } return EXIT_SUCCESS; } sandboxgamemaker-2.7.1+dfsg/src/engine/rendertext.cpp0000664000175000017500000002775211655776734022640 0ustar showardshoward#include "engine.h" static hashtable fonts; static font *fontdef = NULL; static int fontdeftex = 0; font *curfont = NULL; int curfonttex = 0; void newfont(char *name, char *tex, int *defaultw, int *defaulth) { font *f = fonts.access(name); if(!f) { name = newstring(name); f = &fonts[name]; f->name = name; } f->texs.shrink(0); f->texs.add(textureload(tex)); f->chars.shrink(0); f->charoffset = '!'; f->defaultw = *defaultw; f->defaulth = *defaulth; fontdef = f; fontdeftex = 0; } void fontoffset(char *c) { if(!fontdef) return; fontdef->charoffset = c[0]; } void fonttex(char *s) { if(!fontdef) return; Texture *t = textureload(s); loopv(fontdef->texs) if(fontdef->texs[i] == t) { fontdeftex = i; return; } fontdeftex = fontdef->texs.length(); fontdef->texs.add(t); } void fontchar(int *x, int *y, int *w, int *h, int *offsetx, int *offsety, int *advance) { if(!fontdef) return; font::charinfo &c = fontdef->chars.add(); c.x = *x; c.y = *y; c.w = *w ? *w : fontdef->defaultw; c.h = *h ? *h : fontdef->defaulth; c.offsetx = *offsetx; c.offsety = *offsety; c.advance = *advance ? *advance : c.offsetx + c.w; c.tex = fontdeftex; } void fontskip(int *n) { if(!fontdef) return; loopi(max(*n, 1)) { font::charinfo &c = fontdef->chars.add(); c.x = c.y = c.w = c.h = c.offsetx = c.offsety = c.advance = c.tex = 0; } } COMMANDN(font, newfont, "ssii"); COMMAND(fontoffset, "s"); COMMAND(fonttex, "s"); COMMAND(fontchar, "iiiiiii"); COMMAND(fontskip, "i"); bool setfont(const char *name) { font *f = fonts.access(name); if(!f) return false; curfont = f; return true; } ICOMMAND(setfont, "s", (const char *name), if(!setfont(name)) conoutf("font %s does not exist", name); ) static vector fontstack; void pushfont() { fontstack.add(curfont); } bool popfont() { if(fontstack.empty()) return false; curfont = fontstack.pop(); return true; } void gettextres(int &w, int &h) { if(w < MINRESW || h < MINRESH) { if(MINRESW > w*MINRESH/h) { h = h*MINRESW/w; w = MINRESW; } else { w = w*MINRESH/h; h = MINRESH; } } } #define PIXELTAB (4*curfont->defaultw) int text_width(const char *str) { //@TODO deprecate in favour of text_bounds(..) int width, height; text_bounds(str, width, height); return width; } ICOMMAND(text_width, "s", (char *s), intret(text_width(s))) void tabify(const char *str, int *numtabs) { vector tabbed; tabbed.put(str, strlen(str)); int w = text_width(str), tw = max(*numtabs, 0)*PIXELTAB; while(w < tw) { tabbed.add('\t'); w = ((w+PIXELTAB)/PIXELTAB)*PIXELTAB; } tabbed.add('\0'); result(tabbed.getbuf()); } COMMAND(tabify, "si"); void draw_textf(const char *fstr, int left, int top, ...) { defvformatstring(str, top, fstr); draw_text(str, left, top); } static int draw_char(Texture *&tex, int c, int x, int y) { font::charinfo &info = curfont->chars[c-curfont->charoffset]; if(tex != curfont->texs[info.tex]) { xtraverts += varray::end(); tex = curfont->texs[info.tex]; glBindTexture(GL_TEXTURE_2D, tex->id); } float tc_left = info.x / float(tex->xs); float tc_top = info.y / float(tex->ys); float tc_right = (info.x + info.w) / float(tex->xs); float tc_bottom = (info.y + info.h) / float(tex->ys); x += info.offsetx; y += info.offsety; varray::attrib(x, y ); varray::attrib(tc_left, tc_top ); varray::attrib(x + info.w, y ); varray::attrib(tc_right, tc_top ); varray::attrib(x + info.w, y + info.h); varray::attrib(tc_right, tc_bottom); varray::attrib(x, y + info.h); varray::attrib(tc_left, tc_bottom); return info.advance; } //stack[sp] is current color index static void text_color(char c, char *stack, int size, int &sp, bvec colour, int a) { if(c=='s') // save color { c = stack[sp]; if(sp 0) ? --sp : sp]; // restore color else stack[sp] = c; switch(c) { case '0': colour = bvec( 64, 255, 128); break; // green: player talk case '1': colour = bvec( 96, 160, 255); break; // blue: "echo" command case '2': colour = bvec(255, 192, 64); break; // yellow: gameplay messages case '3': colour = bvec(255, 64, 64); break; // red: important errors case '4': colour = bvec(128, 128, 128); break; // gray case '5': colour = bvec(192, 64, 192); break; // magenta case '6': colour = bvec(255, 128, 0); break; // orange case '7': colour = bvec(255, 255, 255); break; // white // provided color: everything else case 'A': colour = bvec(255, 224, 192); break; //apricot case 'B': colour = bvec(192, 96, 0); break; //brown case 'C': colour = bvec(255, 224, 96); break; //corn case 'D': colour = bvec(64, 160, 192); break; //dodger blue case 'E': colour = bvec(96 , 224, 128); break; //emerald case 'F': colour = bvec(255, 64, 255); break; //fuchsia case 'G': colour = bvec(255, 224, 64); break; //gold case 'H': colour = bvec(224, 160, 255); break; //heliotrope case 'I': colour = bvec(128, 64, 192); break; //indigo case 'J': colour = bvec( 0, 192, 128); break; //jade case 'K': colour = bvec(192, 176, 144); break; //khaki case 'L': colour = bvec(255, 224, 32); break; //lemon case 'M': colour = bvec(160, 255, 160); break; //mint case 'N': colour = bvec(255, 224, 160); break; //navajo white case 'O': colour = bvec(160, 160, 64); break; //olive case 'P': colour = bvec(255, 192, 208); break; //pink //case 'Q': nothing case 'R': colour = bvec(255, 64, 128); break; //rose case 'S': colour = bvec(224, 224, 224); break; //silver case 'T': colour = bvec( 64, 224, 224); break; //turquoise case 'U': colour = bvec( 32, 32, 192); break; //ultramarine case 'V': colour = bvec(192, 96, 224); break; //violet case 'W': colour = bvec(255, 224, 176); break; //wheat //case 'X': nothing case 'Y': colour = bvec(255, 255, 96); break; //yellow case 'Z': colour = bvec(224, 192, 160); break; //zinnwaldite } glColor4ub(colour.x, colour.y, colour.z, a); } } #define TEXTSKELETON \ int y = 0, x = 0;\ int i;\ for(i = 0; str[i]; i++)\ {\ TEXTINDEX(i)\ int c = uchar(str[i]);\ if(c=='\t') { x = ((x+PIXELTAB)/PIXELTAB)*PIXELTAB; TEXTWHITE(i) }\ else if(c==' ') { x += curfont->defaultw; TEXTWHITE(i) }\ else if(c=='\n') { TEXTLINE(i) x = 0; y += FONTH; }\ else if(c=='\f') { if(str[i+1]) { i++; TEXTCOLOR(i) }}\ else if(curfont->chars.inrange(c-curfont->charoffset))\ {\ int cw = curfont->chars[c-curfont->charoffset].advance;\ if(cw <= 0) continue;\ if(maxwidth != -1)\ {\ int j = i;\ int w = cw;\ for(; str[i+1]; i++)\ {\ int c = uchar(str[i+1]);\ if(c=='\f') { if(str[i+2]) i++; continue; }\ if(i-j > 16) break;\ if(!curfont->chars.inrange(c-curfont->charoffset)) break;\ int cw = curfont->chars[c-curfont->charoffset].advance;\ if(cw <= 0 || w + cw >= maxwidth) break;\ w += cw;\ }\ if(x + w >= maxwidth && j!=0) { TEXTLINE(j-1) x = 0; y += FONTH; }\ TEXTWORD\ }\ else\ { TEXTCHAR(i) }\ }\ } //all the chars are guaranteed to be either drawable or color commands #define TEXTWORDSKELETON \ for(; j <= i; j++)\ {\ TEXTINDEX(j)\ int c = uchar(str[j]);\ if(c=='\f') { if(str[j+1]) { j++; TEXTCOLOR(j) }}\ else { int cw = curfont->chars[c-curfont->charoffset].advance; TEXTCHAR(j) }\ } int text_visible(const char *str, int hitx, int hity, int maxwidth) { #define TEXTINDEX(idx) #define TEXTWHITE(idx) if(y+FONTH > hity && x >= hitx) return idx; #define TEXTLINE(idx) if(y+FONTH > hity) return idx; #define TEXTCOLOR(idx) #define TEXTCHAR(idx) x += cw; TEXTWHITE(idx) #define TEXTWORD TEXTWORDSKELETON TEXTSKELETON #undef TEXTINDEX #undef TEXTWHITE #undef TEXTLINE #undef TEXTCOLOR #undef TEXTCHAR #undef TEXTWORD return i; } //inverse of text_visible void text_pos(const char *str, int cursor, int &cx, int &cy, int maxwidth) { #define TEXTINDEX(idx) if(idx == cursor) { cx = x; cy = y; break; } #define TEXTWHITE(idx) #define TEXTLINE(idx) #define TEXTCOLOR(idx) #define TEXTCHAR(idx) x += cw; #define TEXTWORD TEXTWORDSKELETON if(i >= cursor) break; cx = INT_MIN; cy = 0; TEXTSKELETON if(cx == INT_MIN) { cx = x; cy = y; } #undef TEXTINDEX #undef TEXTWHITE #undef TEXTLINE #undef TEXTCOLOR #undef TEXTCHAR #undef TEXTWORD } void text_bounds(const char *str, int &width, int &height, int maxwidth) { #define TEXTINDEX(idx) #define TEXTWHITE(idx) #define TEXTLINE(idx) if(x > width) width = x; #define TEXTCOLOR(idx) #define TEXTCHAR(idx) x += cw; #define TEXTWORD x += w; width = 0; TEXTSKELETON height = y + FONTH; TEXTLINE(_) #undef TEXTINDEX #undef TEXTWHITE #undef TEXTLINE #undef TEXTCOLOR #undef TEXTCHAR #undef TEXTWORD } void draw_text(const char *str, int left, int top, int r, int g, int b, int a, int cursor, int maxwidth) { #define TEXTINDEX(idx) if(idx == cursor) { cx = x; cy = y; } #define TEXTWHITE(idx) #define TEXTLINE(idx) #define TEXTCOLOR(idx) if(usecolor) text_color(str[idx], colorstack, sizeof(colorstack), colorpos, color, a); #define TEXTCHAR(idx) draw_char(tex, c, left+x, top+y); x += cw; #define TEXTWORD TEXTWORDSKELETON char colorstack[10]; colorstack[0] = 'c'; //indicate user color bvec color(r, g, b); int colorpos = 0, cx = INT_MIN, cy = 0; bool usecolor = true; if(a < 0) { usecolor = false; a = -a; } Texture *tex = curfont->texs[0]; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D, tex->id); glColor4ub(color.x, color.y, color.z, a); varray::enable(); varray::defattrib(varray::ATTRIB_VERTEX, 2, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); varray::begin(GL_QUADS); TEXTSKELETON xtraverts += varray::end(); if(cursor >= 0 && (totalmillis/250)&1) { glColor4ub(r, g, b, a); if(cx == INT_MIN) { cx = x; cy = y; } if(maxwidth != -1 && cx >= maxwidth) { cx = 0; cy += FONTH; } draw_char(tex, '_', left+cx, top+cy); xtraverts += varray::end(); } varray::disable(); #undef TEXTINDEX #undef TEXTWHITE #undef TEXTLINE #undef TEXTCOLOR #undef TEXTCHAR #undef TEXTWORD } void reloadfonts() { enumerate(fonts, font, f, loopv(f.texs) if(!reloadtexture(*f.texs[i])) fatal("failed to reload font texture"); ); } sandboxgamemaker-2.7.1+dfsg/src/engine/worldio.cpp0000664000175000017500000020561511660231274022104 0ustar showardshoward // worldio.cpp: loading & saving of maps and savegames #include "engine.h" void cutogz(char *s) { char *ogzp = strstr(s, ".ogz"); if(ogzp) *ogzp = '\0'; } string mname, mpath; //holds the mapname and mappath void getmapfilenames(const char *cname, bool fall) { const char *slash = NULL; const char *next = NULL; do { slash = next; next = strpbrk(next ? (next + 1) : cname, "/\\"); } while (next != NULL); if(slash) { copystring(mpath, "base/"); concatstring(mpath, cname, (slash - cname) + 6); copystring(mname, slash+1); } else { formatstring(mpath)("packages/base/%s/%s.ogz", game::gameident(), cname); path(mpath); stream *f = openfile(mpath, "r"); if(!fall || f) { formatstring(mpath)("base/%s", game::gameident()); delete f; } else { copystring(mpath, "base"); } copystring(mname, cname); } defformatstring(tmp)("packages/%s", mpath); createdir(tmp); } static void fixent(entity &e, int version) { if(version <= 10 && e.type >= 7) e.type++; if(version <= 12 && e.type >= 8) e.type++; if(version <= 14 && e.type >= ET_MAPMODEL && e.type <= 16) { if(e.type == 16) e.type = ET_MAPMODEL; else e.type++; } if(version <= 20 && e.type >= ET_ENVMAP) e.type++; if(version <= 21 && e.type >= ET_PARTICLES) e.type++; if(version <= 22 && e.type >= ET_SOUND) e.type++; if(version <= 23 && e.type >= ET_SPOTLIGHT) e.type++; if(version <= 30 && (e.type == ET_MAPMODEL || e.type == ET_PLAYERSTART)) e.attr[0] = (int(e.attr[0])+180)%360; if(version <= 31 && e.type == ET_MAPMODEL) { int yaw = (int(e.attr[0])%360 + 360)%360 + 7; e.attr[0] = yaw - yaw%15; } } bool loadents(const char *fname, vector &ents, uint *crc) { getmapfilenames(fname, true); defformatstring(ogzname)("packages/%s/%s.ogz", mpath, mname); stream *f = opengzfile(ogzname, "rb"); if(!f) return false; octaheader hdr; if(f->read(&hdr, 7*sizeof(int))!=int(7*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } lilswap(&hdr.version, 6); int maptype = 0, octaversion = 0; if(strncmp(hdr.magic, "OCTA", 4)==0) { maptype = MAP_OCTA; octaversion = hdr.version; if(hdr.version>MAPVERSION) { conoutf(CON_ERROR, "map %s requires a newer version of Platinum Arts Sandbox", ogzname); delete f; return false; } } else if(strncmp(hdr.magic, "PASM", 4)==0) { maptype = MAP_PAS; if(hdr.version > PASMAPVERSION) { conoutf(CON_ERROR, "map %s requires a newer version of Platinum Arts Sandbox", ogzname); delete f; return false; } switch(hdr.version) { case 6: octaversion = 32; break; case 5: case 4: octaversion = 31; break; case 3: case 2: octaversion = 30; break; case 1: octaversion = 29; break; default: octaversion = MAPVERSION; break; } } if((strncmp(hdr.magic, "OCTA", 4) && strncmp(hdr.magic, "PASM", 4)) || hdr.worldsize <= 0|| hdr.numents < 0) { conoutf("map %s has malformatted header", ogzname); delete f; return false; } compatheader chdr; if(octaversion <= 28) { if(f->read(&chdr.lightprecision, sizeof(chdr) - 7*sizeof(int)) != int(sizeof(chdr) - 7*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } } else { int extra = 0; if(octaversion <= 29) extra++; if(f->read(&hdr.blendmap, sizeof(hdr) - (7+extra)*sizeof(int)) != int(sizeof(hdr) - (7+extra)*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } } if(octaversion <= 28) { lilswap(&chdr.lightprecision, 3); hdr.blendmap = chdr.blendmap; hdr.numvars = 0; hdr.numvslots = 0; } else { lilswap(&hdr.blendmap, 2); if(octaversion <= 29) hdr.numvslots = 0; else lilswap(&hdr.numvslots, 1); } loopi(hdr.numvars) { int type = f->getchar(), ilen = f->getlil(); f->seek(ilen, SEEK_CUR); switch(type) { case ID_VAR: f->getlil(); break; case ID_FVAR: f->getlil(); break; case ID_SVAR: { int slen = f->getlil(); f->seek(slen, SEEK_CUR); break; } } } string gametype; copystring(gametype, "fps"); bool samegame = true; int eif = 0; if(octaversion>=16) { int len = f->getchar(); f->read(gametype, len+1); } if(strcmp(gametype, game::gameident())) { samegame = false; conoutf(CON_WARN, "WARNING: loading map from %s game, ignoring entities except for lights/mapmodels", gametype); } if(octaversion>=16) { eif = f->getlil(); int extrasize = f->getlil(); f->seek(extrasize, SEEK_CUR); } if(octaversion<14) { f->seek(256, SEEK_CUR); } else { ushort nummru = f->getlil(); f->seek(nummru*sizeof(ushort), SEEK_CUR); } loopi(min(hdr.numents, MAXENTS)) { entity &e = ents.add(); e.o.x = f->getlil(); e.o.y = f->getlil(); e.o.z = f->getlil(); uchar numattrs; if(maptype == MAP_OCTA) { numattrs = 5; } else if(maptype == MAP_PAS && hdr.version >= 5) {numattrs = f->getchar(); } else {numattrs = 8;} loopj(numattrs) { if(maptype == MAP_OCTA) e.attr.add(f->getlil()); else e.attr.add(f->getlil()); } e.type = f->getchar(); if(maptype == MAP_OCTA) f->getchar(); //gets rid of reserved padding at end of struct (1 byte) else if(maptype == MAP_PAS && hdr.version <= 4) loopi(3) f->getchar(); //(3 byte), pieces add to 46, struct is 48 + reserved byte if(maptype == MAP_OCTA) { switch(e.type) { case ET_PARTICLES: switch(e.attr[0]) { case 0: if(!e.attr[3]) break; case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 12: case 13: case 14: e.attr[3] = ((e.attr[3] & 0xF00) << 12) | ((e.attr[3] & 0x0F0) << 8) | ((e.attr[3] & 0x00F) << 4) | 0x0F0F0F; if(e.attr[0] != 5 && e.attr[0] != 6) break; case 3: case 11: e.attr[2] = ((e.attr[2] & 0xF00) << 12) | ((e.attr[2] & 0x0F0) << 8) | ((e.attr[2] & 0x00F) << 4) | 0x0F0F0F; default: break; } break; default: break; } } //update particles to use new indexes if(e.type == ET_PARTICLES && (maptype == MAP_OCTA || (maptype == MAP_PAS && hdr.version < 3))) { switch(e.attr[0]) { // fire/smoke case 13: case 14: e.attr[0] -= 12; break; //fountains and explosion case 1: case 2: case 3: e.attr[0] += 2; break; //bars case 5: case 6: e.attr[0]++; break; //text case 11: e.attr[0] = 8; break; //multi effect case 4: case 7: case 8: case 9: case 10: case 12: { int num[] = {9, 0, 0, 10, 11, 12, 13, 0, 14}; e.attr[0] = num[e.attr[0] - 4]; break; } } } fixent(e, octaversion); if(eif > 0) f->seek(eif, SEEK_CUR); if(samegame) { entities::readent(e, NULL, octaversion); } else if(e.type>=ET_GAMESPECIFIC || octaversion<=14) { ents.pop(); continue; } } if(crc) { f->seek(0, SEEK_END); *crc = f->getcrc(); } delete f; return true; } #ifndef STANDALONE string ogzname, bakname, mcfname, acfname, picname; VARP(savebak, 0, 2, 2); void setmapfilenames(const char *fname, bool fall = true) { getmapfilenames(fname, fall); formatstring(ogzname)("packages/%s/%s.ogz", mpath, mname); if(savebak==1) formatstring(bakname)("packages/%s/%s.BAK", mpath, mname); else formatstring(bakname)("packages/%s/%s_%d.BAK", mpath, mname, totalmillis); formatstring(mcfname)("packages/%s/%s.cfg", mpath, mname); formatstring(acfname)("packages/%s/%s-art.cfg", mpath, mname); formatstring(picname)("packages/%s/%s", mpath, mname); path(ogzname); path(bakname); path(mcfname); path(acfname); path(picname); } void mapcfgname() { defformatstring(res)("packages/%s/%s.cfg", mpath, mname); path(res); result(res); } COMMAND(mapcfgname, ""); void backup(char *name, char *backupname) { string backupfile; copystring(backupfile, findfile(backupname, "wb")); remove(backupfile); rename(findfile(name, "wb"), backupfile); } enum { OCTSAV_CHILDREN = 0, OCTSAV_EMPTY, OCTSAV_SOLID, OCTSAV_NORMAL, OCTSAV_LODCUBE }; static int savemapprogress = 0; void savec(cube *c, const ivec &o, int size, stream *f, bool nolms) { if((savemapprogress++&0xFFF)==0) renderprogress(float(savemapprogress)/allocnodes, "saving octree..."); loopi(8) { ivec co(i, o.x, o.y, o.z, size); if(c[i].children) { f->putchar(OCTSAV_CHILDREN); savec(c[i].children, co, size>>1, f, nolms); } else { int oflags = 0, surfmask = 0, totalverts = 0; if(c[i].material!=MAT_AIR) oflags |= 0x40; if(!nolms) { if(c[i].merged) oflags |= 0x80; if(c[i].ext) loopj(6) { const surfaceinfo &surf = c[i].ext->surfaces[j]; if(!surf.used()) continue; oflags |= 0x20; surfmask |= 1<putchar(oflags | OCTSAV_LODCUBE); else if(isempty(c[i])) f->putchar(oflags | OCTSAV_EMPTY); else if(isentirelysolid(c[i])) f->putchar(oflags | OCTSAV_SOLID); else { f->putchar(oflags | OCTSAV_NORMAL); f->write(c[i].edges, 12); } loopj(6) f->putlil(c[i].texture[j]); if(oflags&0x40) f->putchar(c[i].material); if(oflags&0x80) f->putchar(c[i].merged); if(oflags&0x20) { f->putchar(surfmask); f->putchar(totalverts); loopj(6) if(surfmask&(1<surfaces[j]; vertinfo *verts = c[i].ext->verts() + surf.verts; int layerverts = surf.numverts&MAXFACEVERTS, numverts = surf.totalverts(), vertmask = 0, vertorder = 0, uvorder = 0, dim = dimension(j), vc = C[dim], vr = R[dim]; if(numverts) { if(c[i].merged&(1<write(&surf, sizeof(surfaceinfo)); bool hasxyz = (vertmask&0x04)!=0, hasuv = (vertmask&0x40)!=0, hasnorm = (vertmask&0x80)!=0; if(layerverts == 4) { if(hasxyz && vertmask&0x01) { ivec v0 = verts[vertorder].getxyz(), v2 = verts[(vertorder+2)&3].getxyz(); f->putlil(v0[vc]); f->putlil(v0[vr]); f->putlil(v2[vc]); f->putlil(v2[vr]); hasxyz = false; } if(hasuv && vertmask&0x02) { const vertinfo &v0 = verts[uvorder], &v2 = verts[(uvorder+2)&3]; f->putlil(v0.u); f->putlil(v0.v); f->putlil(v2.u); f->putlil(v2.v); if(surf.numverts&LAYER_DUP) { const vertinfo &b0 = verts[4+uvorder], &b2 = verts[4+((uvorder+2)&3)]; f->putlil(b0.u); f->putlil(b0.v); f->putlil(b2.u); f->putlil(b2.v); } hasuv = false; } } if(hasnorm && vertmask&0x08) { f->putlil(verts[0].norm); hasnorm = false; } if(hasxyz || hasuv || hasnorm) loopk(layerverts) { const vertinfo &v = verts[(k+vertorder)%layerverts]; if(hasxyz) { ivec xyz = v.getxyz(); f->putlil(xyz[vc]); f->putlil(xyz[vr]); } if(hasuv) { f->putlil(v.u); f->putlil(v.v); } if(hasnorm) f->putlil(v.norm); } if(surf.numverts&LAYER_DUP) loopk(layerverts) { const vertinfo &v = verts[layerverts + (k+vertorder)%layerverts]; if(hasuv) { f->putlil(v.u); f->putlil(v.v); } } } } if(c[i].children) savec(c[i].children, co, size>>1, f, nolms); } } } struct surfacecompat { uchar texcoords[8]; uchar w, h; ushort x, y; uchar lmid, layer; }; struct normalscompat { bvec normals[4]; }; struct mergecompat { ushort u1, u2, v1, v2; }; cube *loadchildren(stream *f, const ivec &co, int size, bool &failed); void convertoldsurfaces(cube &c, const ivec &co, int size, surfacecompat *srcsurfs, int hassurfs, normalscompat *normals, int hasnorms, mergecompat *merges, int hasmerges) { surfaceinfo dstsurfs[6]; vertinfo verts[6*2*MAXFACEVERTS]; int totalverts = 0, numsurfs = 6; memset(dstsurfs, 0, sizeof(dstsurfs)); loopi(6) if((hassurfs|hasnorms|hasmerges)&(1<layer&2) { blend = &srcsurfs[numsurfs++]; dst.lmid[0] = src->lmid; dst.lmid[1] = blend->lmid; dst.numverts |= LAYER_BLEND; if(blend->lmid >= LMID_RESERVED && (src->x != blend->x || src->y != blend->y || src->w != blend->w || src->h != blend->h || memcmp(src->texcoords, blend->texcoords, sizeof(src->texcoords)))) dst.numverts |= LAYER_DUP; } else if(src->layer == 1) { dst.lmid[1] = src->lmid; dst.numverts |= LAYER_BOTTOM; } else { dst.lmid[0] = src->lmid; dst.numverts |= LAYER_TOP; } } else dst.numverts |= LAYER_TOP; bool uselms = hassurfs&(1<= LMID_RESERVED || dst.lmid[1] >= LMID_RESERVED || dst.numverts&~LAYER_TOP), usemerges = hasmerges&(1< 0 && (pos[k] == pos[0] || pos[k] == pos[k-1])) continue; vertinfo &dv = curverts[numverts++]; dv.setxyz(pos[k]); if(uselms) { float u = src->x + (src->texcoords[k*2] / 255.0f) * (src->w - 1), v = src->y + (src->texcoords[k*2+1] / 255.0f) * (src->h - 1); dv.u = ushort(floor(clamp((u) * float(USHRT_MAX+1)/LM_PACKW + 0.5f, 0.0f, float(USHRT_MAX)))); dv.v = ushort(floor(clamp((v) * float(USHRT_MAX+1)/LM_PACKH + 0.5f, 0.0f, float(USHRT_MAX)))); } else dv.u = dv.v = 0; dv.norm = usenorms && normals[i].normals[k] != bvec(128, 128, 128) ? encodenormal(normals[i].normals[k].tovec().normalize()) : 0; } dst.verts = totalverts; dst.numverts |= numverts; totalverts += numverts; if(dst.numverts&LAYER_DUP) loopk(4) { if(k > 0 && (pos[k] == pos[0] || pos[k] == pos[k-1])) continue; vertinfo &bv = verts[totalverts++]; bv.setxyz(pos[k]); bv.u = ushort(floor(clamp((blend->x + (blend->texcoords[k*2] / 255.0f) * (blend->w - 1)) * float(USHRT_MAX+1)/LM_PACKW, 0.0f, float(USHRT_MAX)))); bv.v = ushort(floor(clamp((blend->y + (blend->texcoords[k*2+1] / 255.0f) * (blend->h - 1)) * float(USHRT_MAX+1)/LM_PACKH, 0.0f, float(USHRT_MAX)))); bv.norm = usenorms && normals[i].normals[k] != bvec(128, 128, 128) ? encodenormal(normals[i].normals[k].tovec().normalize()) : 0; } } } setsurfaces(c, dstsurfs, verts, totalverts); } void loadc(stream *f, cube &c, const ivec &co, int size, bool &failed) { bool haschildren = false; int octsav = f->getchar(); switch(octsav&0x7) { case OCTSAV_CHILDREN: c.children = loadchildren(f, co, size>>1, failed); return; case OCTSAV_LODCUBE: haschildren = true; break; case OCTSAV_EMPTY: emptyfaces(c); break; case OCTSAV_SOLID: solidfaces(c); break; case OCTSAV_NORMAL: f->read(c.edges, 12); break; default: failed = true; return; } loopi(6) c.texture[i] = mapversion<14 ? f->getchar() : f->getlil(); if(mapversion < 7) f->seek(3, SEEK_CUR); else if(mapversion <= 31) { uchar mask = f->getchar(); if(mask & 0x80) { int mat = f->getchar(); if(mapversion < 27) { static uchar matconv[] = { MAT_AIR, MAT_WATER, MAT_CLIP, MAT_GLASS|MAT_CLIP, MAT_NOCLIP, MAT_LAVA|MAT_DEATH, MAT_GAMECLIP, MAT_DEATH }; mat = size_t(mat) < sizeof(matconv)/sizeof(matconv[0]) ? matconv[mat] : MAT_AIR; } c.material = mat; } surfacecompat surfaces[12]; normalscompat normals[6]; mergecompat merges[6]; int hassurfs = 0, hasnorms = 0, hasmerges = 0; if(mask & 0x3F) { int numsurfs = 6; loopi(numsurfs) { if(i >= 6 || mask & (1 << i)) { f->read(&surfaces[i], sizeof(surfacecompat)); lilswap(&surfaces[i].x, 2); if(mapversion < 10) ++surfaces[i].lmid; if(mapversion < 18) { if(surfaces[i].lmid >= LMID_AMBIENT1) ++surfaces[i].lmid; if(surfaces[i].lmid >= LMID_BRIGHT1) ++surfaces[i].lmid; } if(mapversion < 19) { if(surfaces[i].lmid >= LMID_DARK) surfaces[i].lmid += 2; } if(i < 6) { if(mask & 0x40) { hasnorms |= 1<read(&normals[i], sizeof(normalscompat)); } if(surfaces[i].layer != 0 || surfaces[i].lmid != LMID_AMBIENT) hassurfs |= 1<= 20) { if(octsav&0x80) { int merged = f->getchar(); c.merged = merged&0x3F; if(merged&0x80) { int mask = f->getchar(); if(mask) { hasmerges = mask&0x3F; loopi(6) if(mask&(1<read(m, sizeof(mergecompat)); lilswap(&m->u1, 4); if(mapversion <= 25) { int uorigin = m->u1 & 0xE000, vorigin = m->v1 & 0xE000; m->u1 = (m->u1 - uorigin) << 2; m->u2 = (m->u2 - uorigin) << 2; m->v1 = (m->v1 - vorigin) << 2; m->v2 = (m->v2 - vorigin) << 2; } } } } } } if(hassurfs || hasnorms || hasmerges) convertoldsurfaces(c, co, size, surfaces, hassurfs, normals, hasnorms, merges, hasmerges); } else { if(octsav&0x40) c.material = f->getchar(); if(octsav&0x80) c.merged = f->getchar(); if(octsav&0x20) { int surfmask, totalverts; surfmask = f->getchar(); totalverts = f->getchar(); newcubeext(c, totalverts, false); memset(c.ext->surfaces, 0, sizeof(c.ext->surfaces)); memset(c.ext->verts(), 0, totalverts*sizeof(vertinfo)); int offset = 0; loopi(6) if(surfmask&(1<surfaces[i]; f->read(&surf, sizeof(surfaceinfo)); int vertmask = surf.verts, numverts = surf.totalverts(); if(!numverts) { surf.verts = 0; continue; } surf.verts = offset; vertinfo *verts = c.ext->verts() + offset; offset += numverts; ivec v[4], n; int layerverts = surf.numverts&MAXFACEVERTS, dim = dimension(i), vc = C[dim], vr = R[dim], bias = 0; genfaceverts(c, i, v); bool hasxyz = (vertmask&0x04)!=0, hasuv = (vertmask&0x40)!=0, hasnorm = (vertmask&0x80)!=0; if(hasxyz) { ivec e1, e2, e3; n.cross((e1 = v[1]).sub(v[0]), (e2 = v[2]).sub(v[0])); if(n.iszero()) n.cross(e2, (e3 = v[3]).sub(v[0])); bias = -n.dot(ivec(v[0]).mul(size).add(ivec(co).mask(0xFFF).shl(3))); } else { int vis = layerverts < 4 ? (vertmask&0x02 ? 2 : 1) : 3, order = vertmask&0x01 ? 1 : 0, k = 0; ivec vo = ivec(co).mask(0xFFF).shl(3); verts[k++].setxyz(v[order].mul(size).add(vo)); if(vis&1) verts[k++].setxyz(v[order+1].mul(size).add(vo)); verts[k++].setxyz(v[order+2].mul(size).add(vo)); if(vis&2) verts[k++].setxyz(v[(order+3)&3].mul(size).add(vo)); } if(layerverts == 4) { if(hasxyz && vertmask&0x01) { ushort c1 = f->getlil(), r1 = f->getlil(), c2 = f->getlil(), r2 = f->getlil(); ivec xyz; xyz[vc] = c1; xyz[vr] = r1; xyz[dim] = -(bias + n[vc]*xyz[vc] + n[vr]*xyz[vr])/n[dim]; verts[0].setxyz(xyz); xyz[vc] = c1; xyz[vr] = r2; xyz[dim] = -(bias + n[vc]*xyz[vc] + n[vr]*xyz[vr])/n[dim]; verts[1].setxyz(xyz); xyz[vc] = c2; xyz[vr] = r2; xyz[dim] = -(bias + n[vc]*xyz[vc] + n[vr]*xyz[vr])/n[dim]; verts[2].setxyz(xyz); xyz[vc] = c2; xyz[vr] = r1; xyz[dim] = -(bias + n[vc]*xyz[vc] + n[vr]*xyz[vr])/n[dim]; verts[3].setxyz(xyz); hasxyz = false; } if(hasuv && vertmask&0x02) { int uvorder = (vertmask&0x30)>>4; vertinfo &v0 = verts[uvorder], &v1 = verts[(uvorder+1)&3], &v2 = verts[(uvorder+2)&3], &v3 = verts[(uvorder+3)&3]; v0.u = f->getlil(); v0.v = f->getlil(); v2.u = f->getlil(); v2.v = f->getlil(); v1.u = v0.u; v1.v = v2.v; v3.u = v2.u; v3.v = v0.v; if(surf.numverts&LAYER_DUP) { vertinfo &b0 = verts[4+uvorder], &b1 = verts[4+((uvorder+1)&3)], &b2 = verts[4+((uvorder+2)&3)], &b3 = verts[4+((uvorder+3)&3)]; b0.u = f->getlil(); b0.v = f->getlil(); b2.u = f->getlil(); b2.v = f->getlil(); b1.u = b0.u; b1.v = b2.v; b3.u = b2.u; b3.v = b0.v; } hasuv = false; } } if(hasnorm && vertmask&0x08) { ushort norm = f->getlil(); loopk(layerverts) verts[k].norm = norm; hasnorm = false; } if(hasxyz || hasuv || hasnorm) loopk(layerverts) { vertinfo &v = verts[k]; if(hasxyz) { ivec xyz; xyz[vc] = f->getlil(); xyz[vr] = f->getlil(); xyz[dim] = -(bias + n[vc]*xyz[vc] + n[vr]*xyz[vr])/n[dim]; v.setxyz(xyz); } if(hasuv) { v.u = f->getlil(); v.v = f->getlil(); } if(hasnorm) v.norm = f->getlil(); } if(surf.numverts&LAYER_DUP) loopk(layerverts) { vertinfo &v = verts[k+layerverts], &t = verts[k]; v.setxyz(t.x, t.y, t.z); if(hasuv) { v.u = f->getlil(); v.v = f->getlil(); } v.norm = t.norm; } } } } c.children = (haschildren ? loadchildren(f, co, size>>1, failed) : NULL); } cube *loadchildren(stream *f, const ivec &co, int size, bool &failed) { cube *c = newcubes(); loopi(8) { loadc(f, c[i], ivec(i, co.x, co.y, co.z, size), size, failed); if(failed) break; } return c; } //the following is from redeclipse... thanks quin! void saveslotconfig(stream *h, Slot &s, int index) { VSlot &vs = *s.variants; if(index >= 0) { if(s.shader) { h->printf("setshader %s\n", s.shader->name); } loopvj(s.params) { h->printf("set%sparam", s.params[j].type == SHPARAM_LOOKUP ? "shader" : (s.params[j].type == SHPARAM_UNIFORM ? "uniform" : (s.params[j].type == SHPARAM_PIXEL ? "pixel" : "vertex"))); if(s.params[j].type == SHPARAM_LOOKUP || s.params[j].type == SHPARAM_UNIFORM) h->printf(" \"%s\"", s.params[j].name); else h->printf(" %d", s.params[j].index); loopk(4) h->printf(" %g", s.params[j].val[k]); h->printf("\n"); } } loopvj(s.sts) { h->printf("texture"); if(index >= 0) h->printf(" %s ", textypename(s.sts[j].type)); else h->printf(" 1 "); writeescapedstring(h, s.sts[j].name); if(!j && index >= 0) h->printf(" // %d", index); h->putchar('\n'); } if(index >= 0) { if(vs.rotation) h->printf("texrotate %d\n", vs.rotation); if(vs.xoffset || vs.yoffset) h->printf("texoffset %d %d\n", vs.xoffset, vs.yoffset); if(vs.scale != 1) h->printf("texscale %g\n", vs.scale); if(vs.scrollS != 0.f || vs.scrollT != 0.f) h->printf("texscroll %g %g\n", vs.scrollS * 1000.0f, vs.scrollT * 1000.0f); if(vs.layer != 0) { if(s.layermaskname) h->printf("texlayer %d \"%s\" %d %g\n", vs.layer, s.layermaskname, s.layermaskmode, s.layermaskscale); else h->printf("texlayer %d\n", vs.layer); } if(vs.alphafront != 0.5f || vs.alphaback != 0) h->printf("texalpha %g %g\n", vs.alphafront, vs.alphaback); if(vs.colorscale != vec(1, 1, 1)) h->printf("texcolor %g %g %g\n", vs.colorscale.x, vs.colorscale.y, vs.colorscale.z); if(s.ffenv) h->printf("texffenv 1\n"); if(s.autograss) h->printf("autograss \"%s\"\n", s.autograss); } h->printf("\n"); } void writemapcfg(const char *a) { if(!*a) a = game::getclientmap(); setmapfilenames(*a ? a : "untitled"); if (savebak) { defformatstring(bak)("packages/%s/%s_%d.cfg.BAK", mpath, mname, totalmillis); backup(acfname, bak); } stream *f = openutf8file(path(acfname, true), "wb"); f->printf("//Configuration generated by Platinum Arts Sandbox %s, modify with caution\n//This file contains map variables, and art definitions\n//to add anything, add them onto the end of the file or it's given section.\n//for further information, see our wiki or catch us on IRC\n//Part 1: Game module specific stuff\n//Part 2: World Variables\n//Part 3: Mapsounds\n//Part 4: Mapmodels\n//Part 5: Textures\n\n", version); f->printf("\n//game data\n\n"); game::writemapdata(f); f->printf("\n\n"); f->printf("//world variables\n//uncomment to override\n\n"); extern int sortidents(ident *x, ident *y); vector ids; enumerate(idents, ident, id, ids.add(&id)); ids.sort(sortidents); loopv(ids) { ident &id = *ids[i]; if(!(id.flags&IDF_OVERRIDDEN) || id.flags&IDF_READONLY) continue; switch(id.type) { case ID_VAR: f->printf(id.flags & IDF_HEX ? "//%s 0x%.6X\n" : "//%s %d\n", id.name, *id.storage.i); break; case ID_FVAR: f->printf("//%s %s\n", id.name, floatstr(*id.storage.f)); break; case ID_SVAR: f->printf("//%s ", id.name); writeescapedstring(f, *id.storage.s); f->putchar('\n'); break; } } f->printf("\n//mapsounds\n\nmapsoundreset\n\n"); writemapsounds(f); f->printf("//map models\n\nmapmodelreset\n\n"); extern vector mapmodels; loopv(mapmodels) { f->printf("mmodel "); writeescapedstring(f, mapmodels[i].name); f->printf(" // %i\n", i); } f->printf("\n//Textures\n\ntexturereset\n\n"); extern vector slots; loopv(slots) { saveslotconfig(f, *slots[i], i); } f->printf("\n//Texture Animations; cleared on texture reset\n\n"); extern void writetexanims(stream *f); writetexanims(f); f->printf("\n\n"); delete f; conoutf("successfully generated mapdata cfg: %s", acfname); } COMMAND(writemapcfg, "s"); VAR(dbgvars, 0, 0, 1); void savevslot(stream *f, VSlot &vs, int prev) { f->putlil(vs.changed); f->putlil(prev); if(vs.changed & (1<putlil(vs.params.length()); loopv(vs.params) { ShaderParam &p = vs.params[i]; f->putlil(strlen(p.name)); f->write(p.name, strlen(p.name)); loopk(4) f->putlil(p.val[k]); } } if(vs.changed & (1<putlil(vs.scale); if(vs.changed & (1<putlil(vs.rotation); if(vs.changed & (1<putlil(vs.xoffset); f->putlil(vs.yoffset); } if(vs.changed & (1<putlil(vs.scrollS); f->putlil(vs.scrollT); } if(vs.changed & (1<putlil(vs.layer); if(vs.changed & (1<putlil(vs.alphafront); f->putlil(vs.alphaback); } if(vs.changed & (1<putlil(vs.colorscale[k]); } } void savevslots(stream *f, int numvslots) { if(vslots.empty()) return; int *prev = new int[numvslots]; memset(prev, -1, numvslots*sizeof(int)); loopi(numvslots) { VSlot *vs = vslots[i]; if(vs->changed) continue; for(;;) { VSlot *cur = vs; do vs = vs->next; while(vs && vs->index >= numvslots); if(!vs) break; prev[vs->index] = cur->index; } } int lastroot = 0; loopi(numvslots) { VSlot &vs = *vslots[i]; if(!vs.changed) continue; if(lastroot < i) f->putlil(-(i - lastroot)); savevslot(f, vs, prev[i]); lastroot = i+1; } if(lastroot < numvslots) f->putlil(-(numvslots - lastroot)); delete[] prev; } void loadvslot(stream *f, VSlot &vs, int changed) { vs.changed = changed; if(vs.changed & (1<getlil(); string name; loopi(numparams) { ShaderParam &p = vs.params.add(); int nlen = f->getlil(); f->read(name, min(nlen, MAXSTRLEN-1)); name[min(nlen, MAXSTRLEN-1)] = '\0'; if(nlen >= MAXSTRLEN) f->seek(nlen - (MAXSTRLEN-1), SEEK_CUR); p.name = getshaderparamname(name); p.type = SHPARAM_LOOKUP; p.index = -1; p.loc = -1; loopk(4) p.val[k] = f->getlil(); } } if(vs.changed & (1<getlil(); if(vs.changed & (1<getlil(); if(vs.changed & (1<getlil(); vs.yoffset = f->getlil(); } if(vs.changed & (1<getlil(); vs.scrollT = f->getlil(); } if(vs.changed & (1<getlil(); if(vs.changed & (1<getlil(); vs.alphaback = f->getlil(); } if(vs.changed & (1<getlil(); } } void loadvslots(stream *f, int numvslots) { int *prev = new int[numvslots]; memset(prev, -1, numvslots*sizeof(int)); while(numvslots > 0) { int changed = f->getlil(); if(changed < 0) { loopi(-changed) vslots.add(new VSlot(NULL, vslots.length())); numvslots += changed; } else { prev[vslots.length()] = f->getlil(); loadvslot(f, *vslots.add(new VSlot(NULL, vslots.length())), changed); numvslots--; } } loopv(vslots) if(vslots.inrange(prev[i])) vslots[prev[i]]->next = vslots[i]; delete[] prev; } bool save_world(const char *mname, bool nolms, bool octa) { if(!*mname) mname = game::getclientmap(); setmapfilenames(*mname ? mname : "untitled", false); if(savebak) backup(ogzname, bakname); stream *f = opengzfile(ogzname, "wb"); if(!f) { conoutf(CON_WARN, "could not write map to %s", ogzname); return false; } int numvslots = vslots.length(); if(!nolms && !multiplayer(false)) { numvslots = compactvslots(); allchanged(); } savemapprogress = 0; renderprogress(0, "saving map..."); octaheader hdr; memcpy(hdr.magic, (octa ? "OCTA" : "PASM"), 4); hdr.version = octa ? MAPVERSION : PASMAPVERSION; hdr.headersize = sizeof(hdr); hdr.worldsize = worldsize; hdr.numents = 0; const vector &ents = entities::getents(); loopv(ents) if(ents[i]->type!=ET_EMPTY || nolms) hdr.numents++; hdr.numpvs = nolms ? 0 : getnumviewcells(); hdr.lightmaps = nolms ? 0 : lightmaps.length(); hdr.blendmap = shouldsaveblendmap(); hdr.numvars = 0; hdr.numvslots = numvslots; enumerate(idents, ident, id, { if((id.type == ID_VAR || id.type == ID_FVAR || id.type == ID_SVAR) && id.flags&IDF_OVERRIDE && !(id.flags&IDF_READONLY) && id.flags&IDF_OVERRIDDEN) hdr.numvars++; }); lilswap(&hdr.version, 9); f->write(&hdr, sizeof(hdr)); enumerate(idents, ident, id, { if((id.type!=ID_VAR && id.type!=ID_FVAR && id.type!=ID_SVAR) || !(id.flags&IDF_OVERRIDE) || id.flags&IDF_READONLY || !(id.flags&IDF_OVERRIDDEN)) continue; f->putchar(id.type); f->putlil(strlen(id.name)); f->write(id.name, strlen(id.name)); switch(id.type) { case ID_VAR: if(dbgvars) conoutf(CON_DEBUG, "wrote var %s: %d", id.name, *id.storage.i); f->putlil(*id.storage.i); break; case ID_FVAR: if(dbgvars) conoutf(CON_DEBUG, "wrote fvar %s: %f", id.name, *id.storage.f); f->putlil(*id.storage.f); break; case ID_SVAR: if(dbgvars) conoutf(CON_DEBUG, "wrote svar %s: %s", id.name, *id.storage.s); f->putlil(strlen(*id.storage.s)); f->write(*id.storage.s, strlen(*id.storage.s)); break; } }); if(dbgvars) conoutf(CON_DEBUG, "wrote %d vars", hdr.numvars); f->putchar((int)strlen(game::gameident())); f->write(game::gameident(), (int)strlen(game::gameident())+1); f->putlil(entities::extraentinfosize()); vector extras; game::writegamedata(extras); f->putlil(extras.length()); f->write(extras.getbuf(), extras.length()); f->putlil(texmru.length()); loopv(texmru) f->putlil(texmru[i]); char *ebuf = new char[entities::extraentinfosize()]; loopv(ents) { if(ents[i]->type!=ET_EMPTY || nolms) { if(octa) { entity &tmp = *ents[i]; struct octaent { vec o; short attr1, attr2, attr3, attr4, attr5; uchar type; uchar reserved; } ent; ent.o = tmp.o; int numattrs = tmp.attr.length(); ent.attr1 = numattrs >= 1 ? tmp.attr[0] : 0; ent.attr2 = numattrs >= 2 ? tmp.attr[1] : 0; ent.attr3 = numattrs >= 3 ? tmp.attr[2] : 0; ent.attr4 = numattrs >= 4 ? tmp.attr[3] : 0; ent.attr5 = numattrs >= 5 ? tmp.attr[4] : 0; ent.type = tmp.type; ent.reserved = 0; switch(tmp.type) { case ET_PARTICLES: { switch(ent.attr1) { case 0: if(!ent.attr4) break; case 1: case 2: case 6: case 7: case 9: case 10: case 11: case 12: case 13: case 14: case 15: ent.attr4 = ((tmp.attr[3] & 0xF00000) >> 12) | ((tmp.attr[3] & 0xF000) >> 8) | ((tmp.attr[3] & 0xF0) >> 4); if(ent.attr1 != 6 && ent.attr1 != 7) break; case 5: case 8: ent.attr3 = ((tmp.attr[2] & 0xF00000) >> 12) | ((tmp.attr[2] & 0xF000) >> 8) | ((tmp.attr[2] & 0xF0) >> 4); default: break; } switch(ent.attr1) { //fire/smoke 11/12 case 1: case 2: ent.attr1 += 12; break; //fountains and explosion 1/2/3 case 3: case 4: case 5: ent.attr1 -= 2; break; //bars 5/6 case 6: case 7: ent.attr1--; break; //text case 8: ent.attr1 = 11; break; //multi effect case 9: case 10: case 11: case 12: case 13: case 14: { int num[] = {4, 7, 8, 9, 10, 12}; ent.attr1 = num[ent.attr1 - 9]; break; } default: break; } } break; default: break; } lilswap(&ent.o.x, 3); lilswap(&ent.attr1, 5); f->write(&ent, sizeof(octaent)); entities::writeent(*ents[i], ebuf); if(entities::extraentinfosize()) f->write(ebuf, entities::extraentinfosize()); } else { entity tmp = *ents[i]; lilswap(&tmp.o.x, 3); f->write(&tmp.o, sizeof(vec)); f->putchar(tmp.attr.length()); loopvj(tmp.attr) f->putlil(tmp.attr[j]); f->putchar(tmp.type); entities::writeent(*ents[i], ebuf); if(entities::extraentinfosize()) f->write(ebuf, entities::extraentinfosize()); } } } delete[] ebuf; savevslots(f, numvslots); renderprogress(0, "saving octree..."); savec(worldroot, ivec(0, 0, 0), worldsize>>1, f, nolms); if(!nolms) { if(lightmaps.length()) renderprogress(0, "saving lightmaps..."); loopv(lightmaps) { LightMap &lm = lightmaps[i]; f->putchar(lm.type | (lm.unlitx>=0 ? 0x80 : 0)); if(lm.unlitx>=0) { f->putlil(ushort(lm.unlitx)); f->putlil(ushort(lm.unlity)); } f->write(lm.data, lm.bpp*LM_PACKW*LM_PACKH); renderprogress(float(i+1)/lightmaps.length(), "saving lightmaps..."); } if(getnumviewcells()>0) { renderprogress(0, "saving pvs..."); savepvs(f); } } if(shouldsaveblendmap()) { renderprogress(0, "saving blendmap..."); saveblendmap(f); } delete f; conoutf("wrote map file %s", ogzname); writemapcfg(mname); return true; } static uint mapcrc = 0; uint getmapcrc() { return mapcrc; } static void swapXZ(cube *c) { loopi(8) { swap(c[i].faces[0], c[i].faces[2]); swap(c[i].texture[0], c[i].texture[4]); swap(c[i].texture[1], c[i].texture[5]); if(c[i].ext && c[i].ext->surfaces) { swap(c[i].ext->surfaces[0], c[i].ext->surfaces[4]); swap(c[i].ext->surfaces[1], c[i].ext->surfaces[5]); } if(c[i].children) swapXZ(c[i].children); } } bool load_world(const char *mname, const char *cname) // still supports all map formats that have existed since the earliest cube betas! { int loadingstart = SDL_GetTicks(); setmapfilenames(mname); stream *f = opengzfile(ogzname, "rb"); defformatstring(capt)("Sandbox Engine %s: %s - loading...", version, mname); SDL_WM_SetCaption(capt, NULL); if(!f) { conoutf(CON_ERROR, "could not read map %s", ogzname); game::mapfailed(mname); return false; } octaheader hdr; if(f->read(&hdr, 7*sizeof(int))!=int(7*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } lilswap(&hdr.version, 6); int maptype = 0, octaversion = 0; if(strncmp(hdr.magic, "OCTA", 4)==0) { maptype = MAP_OCTA; octaversion = hdr.version; if(hdr.version>MAPVERSION) { conoutf(CON_ERROR, "map %s requires a newer version of Platinum Arts Sandbox", ogzname); delete f; return false; } } else if(strncmp(hdr.magic, "PASM", 4)==0) { maptype = MAP_PAS; if(hdr.version > PASMAPVERSION) { conoutf(CON_ERROR, "map %s requires a newer version of Platinum Arts Sandbox", ogzname); delete f; return false; } switch(hdr.version) { case 6: octaversion = 32; break; case 5: case 4: octaversion = 31; break; case 3: case 2: octaversion = 30; break; case 1: octaversion = 29; break; default: octaversion = MAPVERSION; break; } } else { conoutf("Unsupported map format (%s), a newer version of sandbox might support it", hdr.magic); delete f; return false; } if(hdr.worldsize <= 0|| hdr.numents < 0) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } compatheader chdr; if(octaversion <= 28) { if(f->read(&chdr.lightprecision, sizeof(chdr) - 7*sizeof(int)) != int(sizeof(chdr) - 7*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } } else { int extra = 0; if(octaversion <= 29) extra++; if(f->read(&hdr.blendmap, sizeof(hdr) - (7+extra)*sizeof(int)) != int(sizeof(hdr) - (7+extra)*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } } resetmap(); Texture *mapshot = textureload(picname, 3, true, false); renderbackground("loading...", mapshot, mname, game::getmapinfo()); //checks are done not to render the map setvar("mapversion", octaversion, true, false); if(octaversion <= 28) { lilswap(&chdr.lightprecision, 3); if(octaversion<=20) conoutf(CON_WARN, "loading older / less efficient map format, may benefit from \"calclight\", then \"savecurrentmap\""); if(chdr.lightprecision) setvar("lightprecision", chdr.lightprecision); if(chdr.lighterror) setvar("lighterror", chdr.lighterror); if(chdr.bumperror) setvar("bumperror", chdr.bumperror); setvar("lightlod", chdr.lightlod); if(chdr.ambient) setvar("ambient", (chdr.ambient<<16) | (chdr.ambient<<8) | chdr.ambient); setvar("skylight", (int(chdr.skylight[0])<<16) | (int(chdr.skylight[1])<<8) | int(chdr.skylight[2])); setvar("watercolour", (int(chdr.watercolour[0])<<16) | (int(chdr.watercolour[1])<<8) | int(chdr.watercolour[2]), true); setvar("waterfallcolour", (int(chdr.waterfallcolour[0])<<16) | (int(chdr.waterfallcolour[1])<<8) | int(chdr.waterfallcolour[2])); setvar("lavacolour", (int(chdr.lavacolour[0])<<16) | (int(chdr.lavacolour[1])<<8) | int(chdr.lavacolour[2])); setvar("fullbright", 0, true); if(chdr.lerpsubdivsize || chdr.lerpangle) setvar("lerpangle", chdr.lerpangle); if(chdr.lerpsubdivsize) { setvar("lerpsubdiv", chdr.lerpsubdiv); setvar("lerpsubdivsize", chdr.lerpsubdivsize); } setsvar("maptitle", chdr.maptitle); hdr.blendmap = chdr.blendmap; hdr.numvars = 0; hdr.numvslots = 0; } else { lilswap(&hdr.blendmap, 2); if(octaversion <= 29) hdr.numvslots = 0; else lilswap(&hdr.numvslots, 1); } renderprogress(0, "clearing world..."); freeocta(worldroot); worldroot = NULL; setvar("mapsize", hdr.worldsize, true, false); int worldscale = 0; while(1<getchar(), ilen = f->getlil(); string name; f->read(name, min(ilen, MAXSTRLEN-1)); name[min(ilen, MAXSTRLEN-1)] = '\0'; if(ilen >= MAXSTRLEN) f->seek(ilen - (MAXSTRLEN-1), SEEK_CUR); ident *id = getident(name); bool exists = id && id->type == type; switch(type) { case ID_VAR: { int val = f->getlil(); if(exists && id->minval <= id->maxval) setvar(name, val); if(dbgvars) conoutf(CON_DEBUG, "read var %s: %d", name, val); break; } case ID_FVAR: { float val = f->getlil(); if(exists && id->minvalf <= id->maxvalf) setfvar(name, val); if(dbgvars) conoutf(CON_DEBUG, "read fvar %s: %f", name, val); break; } case ID_SVAR: { int slen = f->getlil(); string val; f->read(val, min(slen, MAXSTRLEN-1)); val[min(slen, MAXSTRLEN-1)] = '\0'; if(slen >= MAXSTRLEN) f->seek(slen - (MAXSTRLEN-1), SEEK_CUR); if(exists) setsvar(name, val); if(dbgvars) conoutf(CON_DEBUG, "read svar %s: %s", name, val); break; } } } if(dbgvars) conoutf(CON_DEBUG, "read %d vars", hdr.numvars); string gametype; copystring(gametype, "fps"); bool samegame = true; int eif = 0; if(octaversion>=16) { int len = f->getchar(); f->read(gametype, len+1); } if(strcmp(gametype, game::gameident())!=0) { samegame = false; conoutf(CON_WARN, "WARNING: loading map from %s game, ignoring entities except for lights/mapmodels)", gametype); } if(octaversion>=16) { eif = f->getlil(); int extrasize = f->getlil(); vector extras; f->read(extras.pad(extrasize), extrasize); if(samegame) game::readgamedata(extras); } texmru.shrink(0); if(octaversion<14) { uchar oldtl[256]; f->read(oldtl, sizeof(oldtl)); loopi(256) texmru.add(oldtl[i]); } else { ushort nummru = f->getlil(); loopi(nummru) texmru.add(f->getlil()); } renderprogress(0, "loading entities..."); vector &ents = entities::getents(); char *ebuf = eif > 0 ? new char[eif] : NULL; loopi(min(hdr.numents, MAXENTS)) { extentity &e = *entities::newentity(); ents.add(&e); e.o.x = f->getlil(); e.o.y = f->getlil(); e.o.z = f->getlil(); uchar numattrs; if(maptype == MAP_OCTA) { numattrs = 5; } else if(maptype == MAP_PAS && hdr.version >= 5) {numattrs = f->getchar(); } else {numattrs = 8;} loopj(numattrs) { if(maptype == MAP_OCTA) e.attr.add(f->getlil()); else e.attr.add(f->getlil()); } e.type = f->getchar(); if(maptype == MAP_OCTA) f->getchar(); //gets rid of reserved padding at end of struct (1 byte) else if(maptype == MAP_PAS && hdr.version <= 4) loopi(3) f->getchar(); //(3 byte), pieces add to 46, struct is 48 + reserved byte if(samegame || e.type < ET_GAMESPECIFIC) { numattrs = getattrnum(e.type); if(e.attr.length() > numattrs) e.attr.setsize(numattrs); else while(e.attr.length() < numattrs) e.attr.add(0); } if(maptype == MAP_OCTA) { switch(e.type) { case ET_PARTICLES: switch(e.attr[0]) { case 0: if(!e.attr[3]) break; case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 12: case 13: case 14: e.attr[3] = ((e.attr[3] & 0xF00) << 12) | ((e.attr[3] & 0x0F0) << 8) | ((e.attr[3] & 0x00F) << 4) | 0x0F0F0F; if(e.attr[0] != 5 && e.attr[0] != 6) break; case 3: case 11: e.attr[2] = ((e.attr[2] & 0xF00) << 12) | ((e.attr[2] & 0x0F0) << 8) | ((e.attr[2] & 0x00F) << 4) | 0x0F0F0F; default: break; } break; default: break; } } //update particles to use new indexes if(e.type == ET_PARTICLES && (maptype == MAP_OCTA || (maptype == MAP_PAS && hdr.version < 3))) { switch(e.attr[0]) { // fire/smoke case 13: case 14: e.attr[0] -= 12; break; //fountains and explosion case 1: case 2: case 3: e.attr[0] += 2; break; //bars case 5: case 6: e.attr[0]++; break; //text case 11: e.attr[0] = 8; break; //multi effect case 4: case 7: case 8: case 9: case 10: case 12: { int num[] = {9, 0, 0, 10, 11, 12, 13, 0, 14}; e.attr[0] = num[e.attr[0] - 4]; break; } } } e.spawned = false; e.inoctanode = false; fixent(e, octaversion); if(samegame) { if(eif > 0) f->read(ebuf, eif); entities::readent(e, ebuf, mapversion); } else { f->seek(eif, SEEK_CUR); if(e.type>=ET_GAMESPECIFIC || octaversion<=14) { entities::deleteentity(ents.pop()); continue; } } if(!insideworld(e.o)) { if(e.type != ET_LIGHT && e.type != ET_SPOTLIGHT) { conoutf(CON_WARN, "warning: ent outside of world: enttype[%s] index %d (%f, %f, %f)", entities::entname(e.type), i, e.o.x, e.o.y, e.o.z); } } if(octaversion <= 14 && e.type == ET_MAPMODEL) { e.o.z += e.attr[2]; if(e.attr[3]) conoutf(CON_WARN, "warning: mapmodel ent (index %d) uses texture slot %d", i, e.attr[3]); e.attr[2] = e.attr[3] = 0; } } if(ebuf) delete[] ebuf; if(hdr.numents > MAXENTS) { conoutf(CON_WARN, "warning: map has %d entities", hdr.numents); f->seek((hdr.numents-MAXENTS)*(sizeof(entity) + eif), SEEK_CUR); } renderprogress(0, "loading slots..."); loadvslots(f, hdr.numvslots); renderprogress(0, "loading octree..."); bool failed = false; worldroot = loadchildren(f, ivec(0, 0, 0), hdr.worldsize>>1, failed); if(failed) conoutf(CON_ERROR, "garbage in map"); if(octaversion <= 11) swapXZ(worldroot); if(octaversion <= 8) converttovectorworld(); renderprogress(0, "validating..."); validatec(worldroot, hdr.worldsize>>1); if(!failed) { if(octaversion >= 7) loopi(hdr.lightmaps) { renderprogress(i/(float)hdr.lightmaps, "loading lightmaps..."); LightMap &lm = lightmaps.add(); if(octaversion >= 17) { int type = f->getchar(); lm.type = type&0x7F; if(octaversion >= 20 && type&0x80) { lm.unlitx = f->getlil(); lm.unlity = f->getlil(); } } if(lm.type&LM_ALPHA && (lm.type&LM_TYPE)!=LM_BUMPMAP1) lm.bpp = 4; lm.data = new uchar[lm.bpp*LM_PACKW*LM_PACKH]; f->read(lm.data, lm.bpp * LM_PACKW * LM_PACKH); lm.finalize(); } if(octaversion >= 25 && hdr.numpvs > 0) loadpvs(f, hdr.numpvs); if(octaversion >= 28 && hdr.blendmap) loadblendmap(f, hdr.blendmap); } mapcrc = f->getcrc(); delete f; conoutf("read map %s (%.1f seconds)", ogzname, (SDL_GetTicks()-loadingstart)/1000.0f); #ifndef NEWGUI clearmainmenu(); #else UI::clearmainmenu(); #endif identflags |= IDF_OVERRIDDEN; execfile("data/default_map_settings.cfg", false); execfile(acfname, false); execfile(mcfname, false); if(identexists("on_start")) execute("on_start"); identflags &= ~IDF_OVERRIDDEN; extern void fixlightmapnormals(); if(octaversion <= 25) fixlightmapnormals(); extern void fixrotatedlightmaps(); if(octaversion <= 31) fixrotatedlightmaps(); preloadusedmapmodels(true); game::preload(); flushpreloadedmodels(); entitiesinoctanodes(); attachentities(); initlights(); startmap(cname ? cname : mname); allchanged(true); if(maptitle[0] && strcmp(maptitle, "Untitled Map by Unknown")) conoutf(CON_ECHO, "%s", maptitle); game::setwindowcaption(); return true; } void savecurrentmap() { save_world(game::getclientmap()); } void savemap(char *mname) { save_world(mname, false, false); } COMMAND(savemap, "s"); COMMAND(savecurrentmap, ""); ICOMMAND(exportocta, "s", (char *mname), save_world(mname, false, true);); void writeobj(char *name) { defformatstring(fname)("%s.obj", name); stream *f = openfile(path(fname), "w"); if(!f) return; f->printf("# obj file of Cube 2 level\n\n"); defformatstring(mtlname)("%s.mtl", name); path(mtlname); f->printf("mtllib %s\n\n", mtlname); extern vector valist; vector verts; vector texcoords; hashtable shareverts(1<<16); hashtable sharetc(1<<16); hashtable > mtls(1<<8); vector usedmtl; vec bbmin(1e16f, 1e16f, 1e16f), bbmax(-1e16f, -1e16f, -1e16f); loopv(valist) { vtxarray &va = *valist[i]; ushort *edata = NULL; uchar *vdata = NULL; if(!readva(&va, edata, vdata)) continue; int vtxsize = VTXSIZE; ushort *idx = edata; loopj(va.texs) { elementset &es = va.eslist[j]; if(usedmtl.find(es.texture) < 0) usedmtl.add(es.texture); vector &keys = mtls[es.texture]; loopk(es.length[1]) { int n = idx[k] - va.voffset; const vec &pos = renderpath==R_FIXEDFUNCTION ? ((const vertexff *)&vdata[n*vtxsize])->pos : ((const vertex *)&vdata[n*vtxsize])->pos; vec2 tc(renderpath==R_FIXEDFUNCTION ? ((const vertexff *)&vdata[n*vtxsize])->u : ((const vertex *)&vdata[n*vtxsize])->u, renderpath==R_FIXEDFUNCTION ? ((const vertexff *)&vdata[n*vtxsize])->v : ((const vertex *)&vdata[n*vtxsize])->v); ivec &key = keys.add(); key.x = shareverts.access(pos, verts.length()); if(key.x == verts.length()) { verts.add(pos); loopl(3) { bbmin[l] = min(bbmin[l], pos[l]); bbmax[l] = max(bbmax[l], pos[l]); } } key.y = sharetc.access(tc, texcoords.length()); if(key.y == texcoords.length()) texcoords.add(tc); } idx += es.length[1]; } delete[] edata; delete[] vdata; } vec center(-(bbmax.x + bbmin.x)/2, -(bbmax.y + bbmin.y)/2, -bbmin.z); loopv(verts) { vec v = verts[i]; v.add(center); if(v.y != floor(v.y)) f->printf("v %.3f ", -v.y); else f->printf("v %d ", int(-v.y)); if(v.z != floor(v.z)) f->printf("%.3f ", v.z); else f->printf("%d ", int(v.z)); if(v.x != floor(v.x)) f->printf("%.3f\n", v.x); else f->printf("%d\n", int(v.x)); } f->printf("\n"); loopv(texcoords) { const vec2 &tc = texcoords[i]; f->printf("vt %.6f %.6f\n", tc.x, 1-tc.y); } f->printf("\n"); usedmtl.sort(); loopv(usedmtl) { vector &keys = mtls[usedmtl[i]]; f->printf("g slot%d\n", usedmtl[i]); f->printf("usemtl slot%d\n\n", usedmtl[i]); for(int i = 0; i < keys.length(); i += 3) { f->printf("f"); loopk(3) f->printf(" %d/%d", keys[i+2-k].x+1, keys[i+2-k].y+1); f->printf("\n"); } f->printf("\n"); } delete f; f = openfile(mtlname, "w"); if(!f) return; f->printf("# mtl file of Cube 2 level\n\n"); loopv(usedmtl) { VSlot &vslot = lookupvslot(usedmtl[i], false); f->printf("newmtl slot%d\n", usedmtl[i]); f->printf("map_Kd %s\n", vslot.slot->sts.empty() ? notexture->name : path(makerelpath("packages", vslot.slot->sts[0].name))); f->printf("\n"); } delete f; } COMMAND(writeobj, "s"); #endif sandboxgamemaker-2.7.1+dfsg/src/engine/command.cpp0000664000175000017500000023463711655776734022074 0ustar showardshoward// command.cpp: implements the parsing and execution of a tiny script language which // is largely backwards compatible with the quake console language. #include "engine.h" #ifndef STANDALONE VAR(confver, 1, CONFVERSION, -1); VAR(ignoreconfver, 0, 0, 1); #endif hashset idents; // contains ALL vars/commands/aliases vector identmap; int identflags = IDF_PERSIST; static const int MAXARGS = 25; VARN(numargs, _numargs, MAXARGS, 0, 0); static inline void freearg(tagval &v) { switch(v.type) { case VAL_STR: delete[] v.s; break; case VAL_CODE: if(v.code[-1] == CODE_NOP) delete[] (uchar *)&v.code[-1]; break; } } static inline void forcenull(tagval &v) { switch(v.type) { case VAL_NULL: return; } freearg(v); v.setnull(); } static inline float forcefloat(tagval &v) { float f = 0.0f; switch(v.type) { case VAL_INT: f = v.i; break; case VAL_STR: f = parsefloat(v.s); break; case VAL_MACRO: f = parsefloat(v.s); break; case VAL_FLOAT: return v.f; } freearg(v); v.setfloat(f); return f; } static inline int forceint(tagval &v) { int i = 0; switch(v.type) { case VAL_FLOAT: i = v.f; break; case VAL_STR: i = parseint(v.s); break; case VAL_MACRO: i = parseint(v.s); break; case VAL_INT: return v.i; } freearg(v); v.setint(i); return i; } static inline const char *forcestr(tagval &v) { const char *s = ""; switch(v.type) { case VAL_FLOAT: s = floatstr(v.f); break; case VAL_INT: s = intstr(v.i); break; case VAL_STR: case VAL_MACRO: return v.s; } freearg(v); v.setstr(newstring(s)); return s; } static inline void forcearg(tagval &v, int type) { switch(type) { case RET_STR: if(v.type != VAL_STR) forcestr(v); break; case RET_INT: if(v.type != VAL_INT) forceint(v); break; case RET_FLOAT: if(v.type != VAL_FLOAT) forcefloat(v); break; } } void tagval::cleanup() { freearg(*this); } static inline void freeargs(tagval *args, int &oldnum, int newnum) { for(int i = newnum; i < oldnum; i++) freearg(args[i]); oldnum = newnum; } static inline void freecode(ident &id) { if(id.code) { id.code[0] -= 0x100; if(!(id.code[0]>>8)) delete[] id.code; id.code = NULL; } } struct nullval : tagval { nullval() { setnull(); } } nullret; tagval *commandret = &nullret; void clear_command() { enumerate(idents, ident, i, { if(i.type==ID_ALIAS) { DELETEA(i.name); i.nullval(); DELETEA(i.code); } }); } void clearoverride(ident &i) { if(!(i.flags&IDF_OVERRIDDEN)) return; switch(i.type) { case ID_ALIAS: if(i.valtype==VAL_STR) { if(!i.val.s[0]) break; delete[] i.val.s; } freecode(i); i.valtype = VAL_STR; i.val.s = newstring(""); break; case ID_VAR: *i.storage.i = i.overrideval.i; i.changed(); break; case ID_FVAR: *i.storage.f = i.overrideval.f; i.changed(); break; case ID_SVAR: delete[] *i.storage.s; *i.storage.s = i.overrideval.s; i.changed(); break; } i.flags &= ~IDF_OVERRIDDEN; } void clearoverrides() { enumerate(idents, ident, i, clearoverride(i)); } static bool initedidents = false; static vector *identinits = NULL; static inline ident *addident(const ident &id) { if(!initedidents) { if(!identinits) identinits = new vector; identinits->add(id); return NULL; } ident &def = idents.access(id.name, id); def.index = identmap.length(); return identmap.add(&def); } static bool initidents() { initedidents = true; if(identinits) { loopv(*identinits) addident((*identinits)[i]); DELETEP(identinits); } return true; } static bool forceinitidents = initidents(); static const char *sourcefile = NULL, *sourcestr = NULL; static const char *debugline(const char *p, const char *fmt) { if(!sourcestr) return fmt; int num = 1; const char *line = sourcestr; for(;;) { const char *end = strchr(line, '\n'); if(!end) end = line + strlen(line); if(p >= line && p <= end) { static string buf; if(sourcefile) formatstring(buf)("%s:%d: %s", sourcefile, num, fmt); else formatstring(buf)("%d: %s", num, fmt); return buf; } if(!*end) break; line = end + 1; num++; } return fmt; } static struct identlink { ident *id; identlink *next; } *aliasstack = NULL; VAR(dbgalias, 0, 4, 1000); static int nodebug = 0; static void debugcode(const char *fmt, ...) { if(nodebug) return; va_list args; va_start(args, fmt); conoutfv(CON_ERROR, fmt, args); va_end(args); if(!dbgalias) return; int total = 0, depth = 0; for(identlink *l = aliasstack; l; l = l->next) total++; for(identlink *l = aliasstack; l; l = l->next) { ident *id = l->id; ++depth; if(depth < dbgalias) conoutf(CON_ERROR, " %d) %s", total-depth+1, id->name); else if(!l->next) conoutf(CON_ERROR, depth == dbgalias ? " %d) %s" : " ..%d) %s", total-depth+1, id->name); } } ICOMMAND(nodebug, "e", (uint *body), { nodebug++; executeret(body, *commandret); nodebug--; }); void addident(ident *id) { addident(*id); } static inline void pusharg(ident &id, tagval &v, identstack &stack) { stack.val = id.val; stack.valtype = id.valtype; stack.next = id.stack; id.stack = &stack; id.setval(v); freecode(id); } static inline void poparg(ident &id) { if(!id.stack) return; identstack *stack = id.stack; if(id.valtype == VAL_STR) delete[] id.val.s; id.setval(*stack); freecode(id); id.stack = stack->next; } ICOMMAND(push, "rte", (ident *id, tagval *v, uint *code), { if(id->type != ID_ALIAS) return; identstack stack; pusharg(*id, *v, stack); v->type = VAL_NULL; id->flags &= ~IDF_UNKNOWN; executeret(code, *commandret); poparg(*id); }); static inline bool isinteger(const char *c) { return isdigit(c[0]) || ((c[0]=='+' || c[0]=='-' || c[0]=='.') && isdigit(c[1])); } ident *newident(const char *name, int flags) { ident *id = idents.access(name); if(!id) { if(isinteger(name)) { debugcode("number %s is not a valid identifier name", name); return newident("//dummy", IDF_UNKNOWN); } ident init(ID_ALIAS, newstring(name), flags); id = addident(init); } return id; } void resetvar(char *name) { ident *id = idents.access(name); if(!id) return; if(id->flags&IDF_READONLY) debugcode("variable %s is read-only", id->name); else clearoverride(*id); } COMMAND(resetvar, "s"); static inline void setalias(ident &id, tagval &v) { if(id.valtype == VAL_STR) delete[] id.val.s; id.setval(v); freecode(id); id.flags = (id.flags & identflags) | identflags; } static void setalias(const char *name, tagval &v) { ident *id = idents.access(name); if(id) { if(id->type == ID_ALIAS) setalias(*id, v); else { debugcode("cannot redefine builtin %s with an alias", id->name); freearg(v); } } else if(isinteger(name)) { debugcode("cannot alias number %s", name); freearg(v); } else { ident def(ID_ALIAS, newstring(name), v, identflags); addident(def); } } void alias(const char *name, const char *str) { tagval v; v.setstr(newstring(str)); setalias(name, v); } void alias(const char *name, tagval &v) { setalias(name, v); } ICOMMAND(alias, "st", (const char *name, tagval *v), { setalias(name, *v); v->type = VAL_NULL; }); // variable's and commands are registered through globals, see cube.h int variable(const char *name, int min, int cur, int max, int *storage, identfun fun, int flags) { ident v(ID_VAR, name, min, max, storage, (void *)fun, flags); addident(v); return cur; } float fvariable(const char *name, float min, float cur, float max, float *storage, identfun fun, int flags) { ident v(ID_FVAR, name, min, max, storage, (void *)fun, flags); addident(v); return cur; } char *svariable(const char *name, const char *cur, char **storage, identfun fun, int flags) { ident v(ID_SVAR, name, storage, (void *)fun, flags); addident(v); return newstring(cur); } #define _GETVAR(id, vartype, name, retval) \ ident *id = idents.access(name); \ if(!id || id->type!=vartype) return retval; #define GETVAR(id, name, retval) _GETVAR(id, ID_VAR, name, retval) #define OVERRIDEVAR(errorval, saveval, resetval, clearval) \ if(identflags&IDF_OVERRIDDEN || id->flags&IDF_OVERRIDE) \ { \ if(id->flags&IDF_PERSIST) \ { \ debugcode("cannot override persistent variable %s", id->name); \ errorval; \ } \ if(!(id->flags&IDF_OVERRIDDEN)) { saveval; id->flags |= IDF_OVERRIDDEN; } \ else { clearval; } \ } \ else \ { \ if(id->flags&IDF_OVERRIDDEN) { resetval; id->flags &= ~IDF_OVERRIDDEN; } \ clearval; \ } void setvar(const char *name, int i, bool dofunc, bool doclamp) { GETVAR(id, name, ); OVERRIDEVAR(return, id->overrideval.i = *id->storage.i, , ) if(doclamp) *id->storage.i = clamp(i, id->minval, id->maxval); else *id->storage.i = i; if(dofunc) id->changed(); } void setfvar(const char *name, float f, bool dofunc, bool doclamp) { _GETVAR(id, ID_FVAR, name, ); OVERRIDEVAR(return, id->overrideval.f = *id->storage.f, , ); if(doclamp) *id->storage.f = clamp(f, id->minvalf, id->maxvalf); else *id->storage.f = f; if(dofunc) id->changed(); } void setsvar(const char *name, const char *str, bool dofunc) { _GETVAR(id, ID_SVAR, name, ); OVERRIDEVAR(return, id->overrideval.s = *id->storage.s, delete[] id->overrideval.s, delete[] *id->storage.s); *id->storage.s = newstring(str); if(dofunc) id->changed(); } int getvar(const char *name) { GETVAR(id, name, 0); return *id->storage.i; } int getvarmin(const char *name) { GETVAR(id, name, 0); return id->minval; } int getvarmax(const char *name) { GETVAR(id, name, 0); return id->maxval; } float getfvarmin(const char *name) { _GETVAR(id, ID_FVAR, name, 0); return id->minvalf; } float getfvarmax(const char *name) { _GETVAR(id, ID_FVAR, name, 0); return id->maxvalf; } bool identexists(const char *name) { return idents.access(name)!=NULL; } ident *getident(const char *name) { return idents.access(name); } void touchvar(const char *name) { ident *id = idents.access(name); if(id) switch(id->type) { case ID_VAR: case ID_FVAR: case ID_SVAR: id->changed(); break; } } const char *getalias(const char *name) { ident *i = idents.access(name); return i && i->type==ID_ALIAS ? i->getstr() : ""; } void setvarchecked(ident *id, int val) { if(id->flags&IDF_READONLY) debugcode("variable %s is read-only", id->name); #ifndef STANDALONE else if(!(id->flags&IDF_OVERRIDE) || identflags&IDF_OVERRIDDEN || game::showenthelpers()) #else else #endif { OVERRIDEVAR(return, id->overrideval.i = *id->storage.i, , ) if(valminval || val>id->maxval) { val = valminval ? id->minval : id->maxval; // clamp to valid range debugcode(id->flags&IDF_HEX ? (id->minval <= 255 ? "valid range for %s is %d..0x%X" : "valid range for %s is 0x%X..0x%X") : "valid range for %s is %d..%d", id->name, id->minval, id->maxval); } *id->storage.i = val; id->changed(); // call trigger function if available #ifndef STANDALONE if(id->flags&IDF_OVERRIDE && !(identflags&IDF_OVERRIDDEN)) game::vartrigger(id); #endif } } void setfvarchecked(ident *id, float val) { if(id->flags&IDF_READONLY) debugcode("variable %s is read-only", id->name); #ifndef STANDALONE else if(!(id->flags&IDF_OVERRIDE) || identflags&IDF_OVERRIDDEN || game::showenthelpers()) #else else #endif { OVERRIDEVAR(return, id->overrideval.f = *id->storage.f, , ); if(valminvalf || val>id->maxvalf) { val = valminvalf ? id->minvalf : id->maxvalf; // clamp to valid range debugcode("valid range for %s is %s..%s", id->name, floatstr(id->minvalf), floatstr(id->maxvalf)); } *id->storage.f = val; id->changed(); #ifndef STANDALONE if(id->flags&IDF_OVERRIDE && !(identflags&IDF_OVERRIDDEN)) game::vartrigger(id); #endif } } void setsvarchecked(ident *id, const char *val) { if(id->flags&IDF_READONLY) debugcode("variable %s is read-only", id->name); #ifndef STANDALONE else if(!(id->flags&IDF_OVERRIDE) || identflags&IDF_OVERRIDDEN || game::showenthelpers()) #else else #endif { OVERRIDEVAR(return, id->overrideval.s = *id->storage.s, delete[] id->overrideval.s, delete[] *id->storage.s); *id->storage.s = newstring(val); id->changed(); #ifndef STANDALONE if(id->flags&IDF_OVERRIDE && !(identflags&IDF_OVERRIDDEN)) game::vartrigger(id); #endif } } bool addcommand(const char *name, identfun fun, const char *args) { uint argmask = 0; int i = 0; for(const char *fmt = args; *fmt && i < MAXARGS; fmt++, i++) switch(*fmt) { case 'i': case 'f': case 't': case 'D': break; case 's': case 'e': case 'r': argmask |= 1<= end) break; int e = *src++; switch(e) { case 'n': *dst++ = '\n'; break; case 't': *dst++ = '\t'; break; case 'f': *dst++ = '\f'; break; default: *dst++ = e; break; } } else *dst++ = c; } return dst - start; } static char *conc(vector &buf, tagval *v, int n, bool space, const char *prefix = NULL, int prefixlen = 0) { if(prefix) { buf.put(prefix, prefixlen); if(space && n) buf.add(' '); } loopi(n) { const char *s = ""; int len = 0; switch(v[i].type) { case VAL_INT: s = intstr(v[i].i); break; case VAL_FLOAT: s = floatstr(v[i].f); break; case VAL_STR: s = v[i].s; break; case VAL_MACRO: s = v[i].s; len = v[i].code[-1]>>8; goto haslen; } len = int(strlen(s)); haslen: buf.put(s, len); if(i == n-1) break; if(space) buf.add(' '); } buf.add('\0'); return buf.getbuf(); } char *conc(tagval *v, int n, bool space, const char *prefix = NULL) { int len = space ? max(prefix ? n : n-1, 0) : 0, prefixlen = 0; if(prefix) { prefixlen = strlen(prefix); len += prefixlen; } loopi(n) switch(v[i].type) { case VAL_MACRO: len += v[i].code[-1]>>8; break; case VAL_STR: len += int(strlen(v[i].s)); break; default: { vector buf; buf.reserve(len); conc(buf, v, n, space, prefix, prefixlen); return newstring(buf.getbuf(), buf.length()-1); } } char *buf = newstring(prefix ? prefix : "", len); if(prefix && space && n) { buf[prefixlen] = ' '; buf[prefixlen] = '\0'; } loopi(n) { strcat(buf, v[i].s); if(i==n-1) break; if(space) strcat(buf, " "); } return buf; } static inline void skipcomments(const char *&p) { for(;;) { p += strspn(p, " \t\r"); if(p[0]!='/' || p[1]!='/') break; p += strcspn(p, "\n\0"); } } static inline char *cutstring(const char *&p, int &len) { p++; const char *end = parsestring(p); char *s = newstring(end - p); len = escapestring(s, p, end); s[len] = '\0'; p = end; if(*p=='\"') p++; return s; } static inline char *cutword(const char *&p, int &len) { const char *word = p; for(int parens = 0, braks = 0;;) { p += strcspn(p, "/;()[] \t\r\n\0"); switch(p[0]) { case ';': case ' ': case '\t': case '\r': case '\n': case '\0': goto done; case '/': if(p[1] == '/') goto done; break; case '(': parens++; break; case ')': if(--parens < 0) goto done; break; case '[': braks++; break; case ']': if(--braks < 0) goto done; break; } p++; } done: len = p-word; if(!len) return NULL; return newstring(word, len); } static inline void compilestr(vector &code, const char *word, int len, bool macro = false) { if(len <= 3 && !macro) { uint op = CODE_VALI|RET_STR; for(int i = 0; i < len; i++) op |= uint(word[i])<<((i+1)*8); code.add(op); return; } code.add((macro ? CODE_MACRO : CODE_VAL|RET_STR)|(len<<8)); code.put((uint *)word, len/sizeof(uint)); size_t endlen = len%sizeof(uint); union { char c[sizeof(uint)]; uint u; } end; end.u = 0; memcpy(end.c, word + len - endlen, endlen); code.add(end.u); } static inline void compilestr(vector &code, const char *word = NULL) { if(!word) { code.add(CODE_VALI|RET_STR); return; } compilestr(code, word, int(strlen(word))); } static inline void compileint(vector &code, int i) { if(abs(i) <= 0x7FFFFF) code.add(CODE_VALI|RET_INT|int(i)<<8); else { code.add(CODE_VAL|RET_INT); code.add(i); } } static inline void compilenull(vector &code) { code.add(CODE_VALI|RET_NULL); } static inline void compileblock(vector &code) { int start = code.length(); code.add(CODE_BLOCK); code.add(CODE_EXIT); code[start] |= uint(code.length() - (start + 1))<<8; } static inline void compileident(vector &code, const char *word = NULL) { code.add(CODE_IDENT|(newident(word ? word : "//dummy", IDF_UNKNOWN)->index<<8)); } static inline void compileint(vector &code, const char *word = NULL) { return compileint(code, word ? parseint(word) : 0); } static inline void compilefloat(vector &code, float f) { union { float f; uint u; } conv; conv.f = f; if(floor(conv.f) == conv.f && fabs(conv.f) <= 0x7FFFFF) code.add(CODE_VALI|RET_FLOAT|int(conv.f)<<8); else { code.add(CODE_VAL|RET_FLOAT); code.add(conv.u); } } static inline void compilefloat(vector &code, const char *word = NULL) { return compilefloat(code, word ? parsefloat(word) : 0.0f); } static bool compilearg(vector &code, const char *&p, int wordtype); static void compilestatements(vector &code, const char *&p, int rettype, int brak = '\0'); static inline void compileval(vector &code, int wordtype, char *word, int wordlen) { switch(wordtype) { case VAL_STR: compilestr(code, word, wordlen, true); break; case VAL_ANY: compilestr(code, word, wordlen); break; case VAL_FLOAT: compilefloat(code, word); break; case VAL_INT: compileint(code, word); break; case VAL_CODE: { int start = code.length(); code.add(CODE_BLOCK); const char *p = word; compilestatements(code, p, VAL_ANY); code.add(CODE_EXIT|RET_STR); code[start] |= uint(code.length() - (start + 1))<<8; break; } case VAL_IDENT: compileident(code, word); break; default: break; } } static bool compileword(vector &code, const char *&p, int wordtype, char *&word, int &wordlen); static bool compilelookup(vector &code, const char *&p, int ltype) { char *lookup = NULL; int lookuplen = 0; switch(*++p) { case '(': case '[': if(!compileword(code, p, VAL_STR, lookup, lookuplen)) return false; break; case '$': if(!compilelookup(code, p, VAL_STR)) return false; break; default: { lookup = cutword(p, lookuplen); if(!lookup) return false; ident *id = newident(lookup, IDF_UNKNOWN); if(id) switch(id->type) { case ID_VAR: code.add(CODE_IVAR|((ltype >= VAL_ANY ? VAL_INT : ltype)<index<<8)); goto done; case ID_FVAR: code.add(CODE_FVAR|((ltype >= VAL_ANY ? VAL_FLOAT : ltype)<index<<8)); goto done; case ID_SVAR: code.add(CODE_SVAR|((ltype >= VAL_ANY ? VAL_STR : ltype)<index<<8)); goto done; case ID_ALIAS: code.add(CODE_LOOKUP|((ltype >= VAL_ANY ? VAL_STR : ltype)<index<<8)); goto done; } compilestr(code, lookup, lookuplen, true); break; } } code.add(CODE_LOOKUPU|((ltype < VAL_ANY ? ltype< &code, const char *str, const char *end, bool macro) { int start = code.length(); code.add(macro ? CODE_MACRO : CODE_VAL|RET_STR); char *buf = (char *)code.reserve((end-str)/sizeof(uint)+1).buf; int len = 0; while(str < end) { int n = strcspn(str, "\r/\"@]\0"); memcpy(&buf[len], str, n); len += n; str += n; switch(*str) { case '\r': str++; break; case '\"': { const char *start = str; str = parsestring(str+1); if(*str=='\"') str++; memcpy(&buf[len], start, str-start); len += str-start; break; } case '/': if(str[1] == '/') str += strcspn(str, "\n\0"); else buf[len++] = *str++; break; case '@': case ']': if(str < end) { buf[len++] = *str++; break; } case '\0': goto done; } } done: memset(&buf[len], '\0', sizeof(uint)-len%sizeof(uint)); code.advance(len/sizeof(uint)+1); code[start] |= len<<8; return true; } static bool compileblocksub(vector &code, const char *&p) { switch(*p) { case '(': if(!compilearg(code, p, VAL_STR)) return false; break; case '[': if(!compilearg(code, p, VAL_STR)) return false; code.add(CODE_LOOKUPU|RET_STR); break; default: { const char *start = p; while(isalnum(*p) || *p=='_') p++; if(p <= start) return false; char *lookup = newstring(start, p-start); ident *id = newident(lookup, IDF_UNKNOWN); if(id) switch(id->type) { case ID_VAR: code.add(CODE_IVAR|RET_STR|(id->index<<8)); goto done; case ID_FVAR: code.add(CODE_FVAR|RET_STR|(id->index<<8)); goto done; case ID_SVAR: code.add(CODE_SVAR|RET_STR|(id->index<<8)); goto done; case ID_ALIAS: code.add(CODE_LOOKUP|RET_STR|(id->index<<8)); goto done; } compilestr(code, lookup, p-start, true); code.add(CODE_LOOKUPU|RET_STR); done: delete[] lookup; break; } } return true; } static bool compileblock(vector &code, const char *&p, int wordtype) { const char *line = p, *start = p; int concs = 0; for(int brak = 1; brak;) { p += strcspn(p, "@\"/[]"); int c = *p++; switch(c) { case '\0': debugcode(debugline(line, "missing \"]\"")); p--; return false; case '\"': p = parsestring(p); if(*p=='\"') p++; break; case '/': if(*p=='/') { p += strcspn(p, "\n\0"); continue; } break; case '[': brak++; break; case ']': brak--; break; case '@': { const char *esc = p; while(*p == '@') p++; if(brak > p - (esc - 1)) continue; if(!concs) code.add(CODE_ENTER); if(concs + 2 > MAXARGS) { code.add(CODE_CONCW|RET_STR|(concs<<8)); concs = 1; } if(compileblockstr(code, start, esc-1, true)) concs++; if(compileblocksub(code, p)) concs++; if(!concs) code.pop(); else start = p; break; } } } if(p-1 > start) { if(!concs) switch(wordtype) { case VAL_CODE: { p = start; int inst = code.length(); code.add(CODE_BLOCK); compilestatements(code, p, VAL_ANY, ']'); code.add(CODE_EXIT); code[inst] |= uint(code.length() - (inst + 1))<<8; return true; } case VAL_IDENT: { char *name = newstring(start, p-1-start); compileident(code, name); delete[] name; return true; } } compileblockstr(code, start, p-1, concs > 0); if(concs > 1) concs++; } if(concs) { code.add(CODE_CONCM|(wordtype < VAL_ANY ? wordtype< &code, const char *&p, int wordtype, char *&word, int &wordlen) { skipcomments(p); switch(*p) { case '\"': word = cutstring(p, wordlen); break; case '$': return compilelookup(code, p, wordtype); case '(': p++; code.add(CODE_ENTER); compilestatements(code, p, VAL_ANY, ')'); code.add(CODE_EXIT|(wordtype < VAL_ANY ? wordtype< &code, const char *&p, int wordtype) { char *word = NULL; int wordlen = 0; bool more = compileword(code, p, wordtype, word, wordlen); if(!more) return false; if(word) { compileval(code, wordtype, word, wordlen); delete[] word; } return true; } static void compilestatements(vector &code, const char *&p, int rettype, int brak) { const char *line = p; char *idname = NULL; int idlen = 0; ident *id = NULL; int numargs = 0; for(;;) { skipcomments(p); idname = NULL; bool more = compileword(code, p, VAL_ANY, idname, idlen); if(!more) goto endstatement; skipcomments(p); if(p[0] == '=') switch(p[1]) { case '/': if(p[2] != '/') break; case ';': case ' ': case '\t': case '\r': case '\n': case '\0': p++; if(idname) { id = newident(idname, IDF_UNKNOWN); if(!id || id->type != ID_ALIAS) { compilestr(code, idname, idlen, true); id = NULL; } delete[] idname; } if(!(more = compilearg(code, p, VAL_ANY))) compilestr(code); code.add(id && idname ? CODE_ALIAS|(id->index<<8) : CODE_ALIASU); goto endstatement; } numargs = 0; if(!idname) { noid: while(numargs < MAXARGS && (more = compilearg(code, p, VAL_ANY))) numargs++; code.add(CODE_CALLU); } else { id = idents.access(idname); if(!id) { if(!isinteger(idname)) { compilestr(code, idname, idlen); delete[] idname; goto noid; } char *end = idname; int val = int(strtol(idname, &end, 0)); if(*end) compilestr(code, idname, idlen); else compileint(code, val); code.add(CODE_RESULT); } else switch(id->type) { case ID_ALIAS: while(numargs < MAXARGS && (more = compilearg(code, p, VAL_ANY))) numargs++; code.add(CODE_CALL|(id->index<<8)); break; case ID_COMMAND: { int comtype = CODE_COM; bool rep = false; for(const char *fmt = id->args; *fmt; fmt++) switch(*fmt) { case 's': if(more) more = compilearg(code, p, VAL_STR); if(!more) { if(rep) break; compilestr(code, NULL, 0, true); } else if(!fmt[1]) { int numconc = 0; while(numargs + numconc < MAXARGS && (more = compilearg(code, p, VAL_STR))) numconc++; if(numconc > 0) code.add(CODE_CONC|RET_STR|((numconc+1)<<8)); } numargs++; break; case 'i': if(more) more = compilearg(code, p, VAL_INT); if(!more) { if(rep) break; compileint(code); } numargs++; break; case 'f': if(more) more = compilearg(code, p, VAL_FLOAT); if(!more) { if(rep) break; compilefloat(code); } numargs++; break; case 't': if(more) more = compilearg(code, p, VAL_ANY); if(!more) { if(rep) break; compilenull(code); } numargs++; break; case 'e': if(more) more = compilearg(code, p, VAL_CODE); if(!more) { if(rep) break; compileblock(code); } numargs++; break; case 'r': if(more) more = compilearg(code, p, VAL_IDENT); if(!more) { if(rep) break; compileident(code); } numargs++; break; #ifndef STANDALONE case 'D': comtype = CODE_COMD; numargs++; break; #endif case 'C': comtype = CODE_COMC; if(more) while(numargs < MAXARGS && (more = compilearg(code, p, VAL_ANY))) numargs++; numargs = 1; goto endfmt; case 'V': comtype = CODE_COMV; if(more) while(numargs < MAXARGS && (more = compilearg(code, p, VAL_ANY))) numargs++; numargs = 2; goto endfmt; case '1': case '2': case '3': case '4': if(more) { fmt -= *fmt-'0'+1; rep = true; } break; default: fatal("builtin declared with illegal type"); } if(numargs > 8) fatal("builtin declared with too many args"); endfmt: code.add(comtype|(rettype < VAL_ANY ? rettype<index<<8)); break; } case ID_VAR: if(!(more = compilearg(code, p, VAL_INT))) code.add(CODE_PRINT|(id->index<<8)); else if(!(id->flags&IDF_HEX) || !(more = compilearg(code, p, VAL_INT))) code.add(CODE_IVAR1|(id->index<<8)); else if(!(more = compilearg(code, p, VAL_INT))) code.add(CODE_IVAR2|(id->index<<8)); else code.add(CODE_IVAR3|(id->index<<8)); break; case ID_FVAR: if(!(more = compilearg(code, p, VAL_FLOAT))) code.add(CODE_PRINT|(id->index<<8)); else code.add(CODE_FVAR1|(id->index<<8)); break; case ID_SVAR: if(!(more = compilearg(code, p, VAL_STR))) code.add(CODE_PRINT|(id->index<<8)); else { int numconc = 0; while(numconc+1 < MAXARGS && (more = compilearg(code, p, VAL_ANY))) numconc++; if(numconc > 0) code.add(CODE_CONC|RET_STR|((numconc+1)<<8)); code.add(CODE_SVAR1|(id->index<<8)); } break; } delete[] idname; } endstatement: if(more) while(compilearg(code, p, VAL_ANY)) code.add(CODE_POP); p += strcspn(p, ")];/\n\0"); int c = *p++; switch(c) { case '\0': if(c != brak) debugcode(debugline(line, "missing \"%c\""), brak); return; case ')': case ']': if(c == brak) return; debugcode(debugline(line, "unexpected \"%c\""), c); break; case '/': if(*p == '/') p += strcspn(p, "\n\0"); goto endstatement; } } } static void compilemain(vector &code, const char *p, int rettype = VAL_ANY) { code.add(CODE_NOP); compilestatements(code, p, VAL_ANY); code.add(CODE_EXIT|(rettype < VAL_ANY ? rettype< buf; buf.reserve(64); compilemain(buf, p); uint *code = new uint[buf.length()]; memcpy(code, buf.getbuf(), buf.length()*sizeof(uint)); return code; } static void printvar(ident *id) { switch(id->type) { case ID_VAR: { int i = *id->storage.i; if(id->flags&IDF_HEX && id->maxval==0xFFFFFF) conoutf("%s = 0x%.6X (%d, %d, %d)", id->name, i, (i>>16)&0xFF, (i>>8)&0xFF, i&0xFF); else conoutf(id->flags&IDF_HEX ? "%s = 0x%X" : "%s = %d", id->name, i); break; } case ID_FVAR: conoutf("%s = %s", id->name, floatstr(*id->storage.f)); break; case ID_SVAR: conoutf(strchr(*id->storage.s, '"') ? "%s = [%s]" : "%s = \"%s\"", id->name, *id->storage.s); break; } } typedef void (__cdecl *comfun)(); typedef void (__cdecl *comfun1)(void *); typedef void (__cdecl *comfun2)(void *, void *); typedef void (__cdecl *comfun3)(void *, void *, void *); typedef void (__cdecl *comfun4)(void *, void *, void *, void *); typedef void (__cdecl *comfun5)(void *, void *, void *, void *, void *); typedef void (__cdecl *comfun6)(void *, void *, void *, void *, void *, void *); typedef void (__cdecl *comfun7)(void *, void *, void *, void *, void *, void *, void *); typedef void (__cdecl *comfun8)(void *, void *, void *, void *, void *, void *, void *, void *); typedef void (__cdecl *comfunv)(tagval *, int); struct argidentsvector : vector { argidentsvector() { for(int i = 0; i < MAXARGS; i++) { defformatstring(argname)("arg%d", i+1); add(newident(argname)); } } } argidents; static const uint *runcode(const uint *code, tagval &result) { ident *id = NULL; int numargs = 0; tagval args[MAXARGS+1], *prevret = commandret; result.setnull(); commandret = &result; for(;;) { uint op = *code++; switch(op&0xFF) { case CODE_NOP: continue; case CODE_POP: freearg(args[--numargs]); continue; case CODE_ENTER: code = runcode(code, args[numargs++]); continue; case CODE_EXIT|RET_NULL: case CODE_EXIT|RET_STR: case CODE_EXIT|RET_INT: case CODE_EXIT|RET_FLOAT: forcearg(result, op&CODE_RET_MASK); goto exit; case CODE_PRINT: printvar(identmap[op>>8]); continue; case CODE_MACRO: { uint len = op>>8; args[numargs++].setmacro(code); code += len/sizeof(uint) + 1; continue; } case CODE_VAL|RET_STR: { uint len = op>>8; args[numargs++].setstr(newstring((char *)code, len)); code += len/sizeof(uint) + 1; continue; } case CODE_VALI|RET_STR: { char s[4] = { (op>>8)&0xFF, (op>>16)&0xFF, (op>>24)&0xFF, '\0' }; args[numargs++].setstr(newstring(s)); continue; } case CODE_VAL|RET_NULL: case CODE_VALI|RET_NULL: args[numargs++].setnull(); continue; case CODE_VAL|RET_INT: args[numargs++].setint(int(*code++)); continue; case CODE_VALI|RET_INT: args[numargs++].setint(int(op)>>8); continue; case CODE_VAL|RET_FLOAT: args[numargs++].setfloat(*(float *)code++); continue; case CODE_VALI|RET_FLOAT: args[numargs++].setfloat(float(int(op)>>8)); continue; case CODE_FORCE|RET_STR: forcestr(args[numargs-1]); continue; case CODE_FORCE|RET_INT: forceint(args[numargs-1]); continue; case CODE_FORCE|RET_FLOAT: forcefloat(args[numargs-1]); continue; case CODE_RESULT|RET_NULL: case CODE_RESULT|RET_STR: case CODE_RESULT|RET_INT: case CODE_RESULT|RET_FLOAT: litval: freearg(result); result = args[0]; forcearg(result, op&CODE_RET_MASK); args[0].setnull(); freeargs(args, numargs, 0); continue; case CODE_BLOCK: { uint len = op>>8; args[numargs++].setcode(code); code += len; continue; } case CODE_COMPILE: { tagval &arg = args[numargs-1]; vector buf; switch(arg.type) { case VAL_INT: buf.reserve(8); buf.add(CODE_NOP); compileint(buf, arg.i); buf.add(CODE_RESULT); buf.add(CODE_EXIT); break; case VAL_FLOAT: buf.reserve(8); buf.add(CODE_NOP); compilefloat(buf, arg.f); buf.add(CODE_RESULT); buf.add(CODE_EXIT); break; case VAL_STR: case VAL_MACRO: buf.reserve(64); compilemain(buf, arg.s); freearg(arg); break; default: buf.reserve(8); buf.add(CODE_NOP); compilenull(buf); buf.add(CODE_RESULT); buf.add(CODE_EXIT); break; } arg.setcode(buf.getbuf()+1); buf.disown(); continue; } case CODE_IDENT: args[numargs++].setident(identmap[op>>8]); continue; case CODE_IDENTU: { tagval &arg = args[numargs-1]; ident *id = newident(arg.type == VAL_STR || arg.type == VAL_MACRO ? arg.s : "//dummy", IDF_UNKNOWN); freearg(arg); arg.setident(id); continue; } case CODE_LOOKUPU|RET_STR: #define LOOKUPU(aval, sval, ival, fval, nval) { \ tagval &arg = args[numargs-1]; \ if(arg.type != VAL_STR && arg.type != VAL_MACRO) continue; \ id = idents.access(arg.s); \ if(id) switch(id->type) \ { \ case ID_ALIAS: if(id->flags&IDF_UNKNOWN) break; freearg(arg); aval; continue; \ case ID_SVAR: freearg(arg); sval; continue; \ case ID_VAR: freearg(arg); ival; continue; \ case ID_FVAR: freearg(arg); fval; continue; \ } \ debugcode("unknown alias lookup: %s", arg.s); \ freearg(arg); \ nval; \ continue; \ } LOOKUPU(arg.setstr(newstring(id->getstr())), arg.setstr(newstring(*id->storage.s)), arg.setstr(newstring(intstr(*id->storage.i))), arg.setstr(newstring(floatstr(*id->storage.f))), arg.setstr(newstring(""))); case CODE_LOOKUP|RET_STR: #define LOOKUP(aval) { \ id = identmap[op>>8]; \ if(id->flags&IDF_UNKNOWN) debugcode("unknown alias lookup: %s", id->name); \ aval; \ continue; \ } LOOKUP(args[numargs++].setstr(newstring(id->getstr()))); case CODE_LOOKUPU|RET_INT: LOOKUPU(arg.setint(id->getint()), arg.setint(parseint(*id->storage.s)), arg.setint(*id->storage.i), arg.setint(int(*id->storage.f)), arg.setint(0)); case CODE_LOOKUP|RET_INT: LOOKUP(args[numargs++].setint(id->getint())); case CODE_LOOKUPU|RET_FLOAT: LOOKUPU(arg.setfloat(id->getfloat()), arg.setfloat(parsefloat(*id->storage.s)), arg.setfloat(float(*id->storage.i)), arg.setfloat(*id->storage.f), arg.setfloat(0.0f)); case CODE_LOOKUP|RET_FLOAT: LOOKUP(args[numargs++].setfloat(id->getfloat())); case CODE_LOOKUPU|RET_NULL: LOOKUPU(id->getval(arg), arg.setstr(newstring(*id->storage.s)), arg.setint(*id->storage.i), arg.setfloat(*id->storage.f), arg.setnull()); case CODE_LOOKUP|RET_NULL: LOOKUP(id->getval(args[numargs++])); case CODE_SVAR|RET_STR: case CODE_SVAR|RET_NULL: args[numargs++].setstr(newstring(*identmap[op>>8]->storage.s)); continue; case CODE_SVAR|RET_INT: args[numargs++].setint(parseint(*identmap[op>>8]->storage.s)); continue; case CODE_SVAR|RET_FLOAT: args[numargs++].setfloat(parsefloat(*identmap[op>>8]->storage.s)); continue; case CODE_SVAR1: setsvarchecked(identmap[op>>8], args[0].s); freeargs(args, numargs, 0); continue; case CODE_IVAR|RET_INT: case CODE_IVAR|RET_NULL: args[numargs++].setint(*identmap[op>>8]->storage.i); continue; case CODE_IVAR|RET_STR: args[numargs++].setstr(newstring(intstr(*identmap[op>>8]->storage.i))); continue; case CODE_IVAR|RET_FLOAT: args[numargs++].setfloat(float(*identmap[op>>8]->storage.i)); continue; case CODE_IVAR1: setvarchecked(identmap[op>>8], args[0].i); numargs = 0; continue; case CODE_IVAR2: setvarchecked(identmap[op>>8], (args[0].i<<16)|(args[1].i<<8)); numargs = 0; continue; case CODE_IVAR3: setvarchecked(identmap[op>>8], (args[0].i<<16)|(args[1].i<<8)|args[2].i); numargs = 0; continue; case CODE_FVAR|RET_FLOAT: case CODE_FVAR|RET_NULL: args[numargs++].setfloat(*identmap[op>>8]->storage.f); continue; case CODE_FVAR|RET_STR: args[numargs++].setstr(newstring(floatstr(*identmap[op>>8]->storage.f))); continue; case CODE_FVAR|RET_INT: args[numargs++].setint(int(*identmap[op>>8]->storage.f)); continue; case CODE_FVAR1: setfvarchecked(identmap[op>>8], args[0].f); numargs = 0; continue; case CODE_COM|RET_NULL: case CODE_COM|RET_STR: case CODE_COM|RET_FLOAT: case CODE_COM|RET_INT: id = identmap[op>>8]; #ifndef STANDALONE callcom: #endif #define CALLCOM \ switch(numargs) \ { \ case 0: ((comfun)id->fun)(); break; \ case 1: ((comfun1)id->fun)(ARG(0)); break; \ case 2: ((comfun2)id->fun)(ARG(0), ARG(1)); break; \ case 3: ((comfun3)id->fun)(ARG(0), ARG(1), ARG(2)); break; \ case 4: ((comfun4)id->fun)(ARG(0), ARG(1), ARG(2), ARG(3)); break; \ case 5: ((comfun5)id->fun)(ARG(0), ARG(1), ARG(2), ARG(3), ARG(4)); break; \ case 6: ((comfun6)id->fun)(ARG(0), ARG(1), ARG(2), ARG(3), ARG(4), ARG(5)); break; \ case 7: ((comfun7)id->fun)(ARG(0), ARG(1), ARG(2), ARG(3), ARG(4), ARG(5), ARG(6)); break; \ case 8: ((comfun8)id->fun)(ARG(0), ARG(1), ARG(2), ARG(3), ARG(4), ARG(5), ARG(6), ARG(7)); break; \ default: fatal("builtin declared with too many args"); \ } forcenull(result); #define ARG(n) (id->argmask&(1<>8]; args[numargs].setint(addreleaseaction(conc(args, numargs, true, id->name)) ? 1 : 0); numargs++; goto callcom; #endif case CODE_COMV|RET_NULL: case CODE_COMV|RET_STR: case CODE_COMV|RET_FLOAT: case CODE_COMV|RET_INT: id = identmap[op>>8]; forcenull(result); ((comfunv)id->fun)(args, numargs); goto forceresult; case CODE_COMC|RET_NULL: case CODE_COMC|RET_STR: case CODE_COMC|RET_FLOAT: case CODE_COMC|RET_INT: id = identmap[op>>8]; forcenull(result); { vector buf; ((comfun1)id->fun)(conc(buf, args, numargs, true)); } goto forceresult; case CODE_CONC|RET_NULL: case CODE_CONC|RET_STR: case CODE_CONC|RET_FLOAT: case CODE_CONC|RET_INT: case CODE_CONCW|RET_NULL: case CODE_CONCW|RET_STR: case CODE_CONCW|RET_FLOAT: case CODE_CONCW|RET_INT: { int numconc = op>>8; char *s = conc(&args[numargs-numconc], numconc, (op&CODE_OP_MASK)==CODE_CONC); freeargs(args, numargs, numargs-numconc); args[numargs++].setstr(s); forcearg(args[numargs-1], op&CODE_RET_MASK); continue; } case CODE_CONCM|RET_NULL: case CODE_CONCM|RET_STR: case CODE_CONCM|RET_FLOAT: case CODE_CONCM|RET_INT: { int numconc = op>>8; char *s = conc(&args[numargs-numconc], numconc, false); freeargs(args, numargs, numargs-numconc); result.setstr(s); forcearg(result, op&CODE_RET_MASK); continue; } case CODE_ALIAS: setalias(*identmap[op>>8], args[--numargs]); freeargs(args, numargs, 0); continue; case CODE_ALIASU: forcestr(args[0]); setalias(args[0].s, args[--numargs]); freeargs(args, numargs, 0); continue; case CODE_CALL|RET_NULL: case CODE_CALL|RET_STR: case CODE_CALL|RET_FLOAT: case CODE_CALL|RET_INT: #define CALLALIAS(offset) { \ identstack argstack[MAXARGS]; \ for(int i = 0; i < numargs-offset; i++) \ pusharg(*argidents[i], args[i+offset], argstack[i]); \ int oldargs = _numargs; \ _numargs = numargs-offset; \ int oldflags = identflags; \ identflags |= id->flags&IDF_OVERRIDDEN; \ identlink aliaslink = { id, aliasstack }; \ aliasstack = &aliaslink; \ if(!id->code) \ { \ id->code = compilecode(id->getstr()); \ id->code[0] += 0x100; \ } \ uint *code = id->code; \ code[0] += 0x100; \ runcode(code+1, result); \ code[0] -= 0x100; \ if(!(code[0]>>8)) delete[] code; \ aliasstack = aliaslink.next; \ identflags = oldflags; \ for(int i = 0; i < numargs-offset; i++) \ poparg(*argidents[i]); \ forcearg(result, op&CODE_RET_MASK); \ _numargs = oldargs; \ numargs = 0; \ } forcenull(result); id = identmap[op>>8]; if(id->flags&IDF_UNKNOWN) { debugcode("unknown command: %s", id->name); goto forceresult; } CALLALIAS(0); continue; case CODE_CALLU|RET_NULL: case CODE_CALLU|RET_STR: case CODE_CALLU|RET_FLOAT: case CODE_CALLU|RET_INT: if(args[0].type != VAL_STR) goto litval; id = idents.access(args[0].s); if(!id) { noid: if(isinteger(args[0].s)) goto litval; debugcode("unknown command: %s", args[0].s); forcenull(result); goto forceresult; } forcenull(result); switch(id->type) { case ID_COMMAND: { int i = 1, maxargs = MAXARGS; for(const char *fmt = id->args; *fmt && i < maxargs; fmt++, i++) switch(*fmt) { case 'i': if(numargs <= i) args[numargs++].setint(0); else forceint(args[i]); break; case 'f': if(numargs <= i) args[numargs++].setfloat(0.0f); else forcefloat(args[i]); break; case 's': if(numargs <= i) args[numargs++].setstr(newstring("")); else forcestr(args[i]); break; case 't': if(numargs <= i) args[numargs++].setnull(); break; case 'e': { vector buf; buf.reserve(64); compilemain(buf, numargs <= i ? "" : args[i].getstr()); freearg(args[i]); args[i].setcode(buf.getbuf()+1); buf.disown(); break; } case 'r': if(numargs <= i) args[numargs++].setident(newident("//dummy", IDF_UNKNOWN)); else { ident *id = newident(args[i].type==VAL_STR ? args[i].s : "//dummy", IDF_UNKNOWN); freearg(args[i]); args[i].setident(id); } break; #ifndef STANDALONE case 'D': args[numargs].setint(addreleaseaction(conc(args, numargs, true)) ? 1 : 0); numargs++; break; #endif case 'C': { vector buf; ((comfun1)id->fun)(conc(buf, args+1, numargs-1, true)); goto forceresult; } case 'V': ((comfunv)id->fun)(args+1, numargs-1); goto forceresult; case '1': case '2': case '3': case '4': if(numargs <= i) { fmt -= *fmt-'0'+1; maxargs = numargs; } break; } #define ARG(n) (id->argmask&(1<flags&IDF_HEX && numargs > 2) { val = (val << 16) | forceint(args[2]); if(numargs > 3) val |= forceint(args[3]); } setvarchecked(id, val); } goto forceresult; case ID_FVAR: if(numargs <= 1) printvar(id); else setfvarchecked(id, forcefloat(args[1])); goto forceresult; case ID_SVAR: if(numargs <= 1) printvar(id); else setsvarchecked(id, forcestr(args[1])); goto forceresult; case ID_ALIAS: if(id->valtype==VAL_NULL) goto noid; freearg(args[0]); CALLALIAS(1); continue; default: goto forceresult; } } } exit: commandret = prevret; return code; } void executeret(const uint *code, tagval &result) { runcode(code, result); } void executeret(const char *p, tagval &result) { vector code; code.reserve(64); compilemain(code, p, VAL_ANY); runcode(code.getbuf()+1, result); } char *executeret(const char *p) { tagval result; executeret(p, result); if(result.type == VAL_NULL) return NULL; forcestr(result); return result.s; } int execute(const uint *code) { tagval result; runcode(code, result); int i = result.getint(); freearg(result); return i; } int execute(const char *p) { vector code; code.reserve(64); compilemain(code, p, VAL_INT); tagval result; runcode(code.getbuf()+1, result); int i = result.getint(); freearg(result); return i; } bool execfile(const char *cfgfile, bool msg) { /*const char *paths[] = {"", "data/"}; string s; loopi(sizeof(paths)/sizeof(paths[0])) { formatstring(s)("%s%s", paths[i], cfgfile); char *buf = loadfile(path(s), NULL); if(buf) { execute(buf); delete[] buf; return true; } } if(msg) conoutf(CON_ERROR, "could not read \"%s\"", cfgfile); return false; */ string s; copystring(s, cfgfile); char *buf = loadfile(path(s), NULL); if(!buf) { if(msg) conoutf(CON_ERROR, "could not read \"%s\"", cfgfile); return false; } const char *oldsourcefile = sourcefile, *oldsourcestr = sourcestr; sourcefile = cfgfile; sourcestr = buf; execute(buf); sourcefile = oldsourcefile; sourcestr = oldsourcestr; delete[] buf; return true; } #ifndef STANDALONE bool sortidents(ident *x, ident *y) { return strcmp(x->name, y->name) < 0; } void writeescapedstring(stream *f, const char *s) { f->putchar('"'); for(; *s; s++) switch(*s) { case '\n': f->write("^n", 2); break; case '\t': f->write("^t", 2); break; case '\f': f->write("^f", 2); break; case '"': f->write("^\"", 2); break; default: f->putchar(*s); break; } f->putchar('"'); } static bool validatealias(const char *s) { int parens = 0, braks = 0; for(; *s; s++) switch(*s) { case '(': parens++; break; case ')': if(!parens) return false; parens--; break; case '[': braks++; break; case ']': if(!braks) return false; braks--; break; case '"': s = parsestring(s + 1); if(*s != '"') return false; break; case '/': if(s[1] == '/') return false; break; case '\f': return false; } if(braks || parens) return false; return true; } void writecfg(const char *name) { defformatstring(confname)("config_%s.cfg", game::gameident()); stream *f = openutf8file(path((name && name[0]) ? name : confname, true), "wb"); if(!f) return; f->printf("// automatically written on exit, DO NOT MODIFY\n// delete this file to have data/defaults.cfg and data/%s/defaults.cfg overwrite these settings\n// modify settings in game, or put settings in %s to override anything\n\n", game::gameident(), game::autoexec()); f->printf("if (&& (! $ignoreconfver) (!= $confver %i)) [\n\tsleep 500 [showgui keepconf]; setdefaults\n] [\n\n", confver); writecrosshairs(f); vector ids; enumerate(idents, ident, id, ids.add(&id)); ids.sort(sortidents); loopv(ids) { ident &id = *ids[i]; if(id.flags&IDF_PERSIST) switch(id.type) { case ID_VAR: f->printf("%s %d\n", id.name, *id.storage.i); break; case ID_FVAR: f->printf("%s %s\n", id.name, floatstr(*id.storage.f)); break; case ID_SVAR: f->printf("%s ", id.name); writeescapedstring(f, *id.storage.s); f->putchar('\n'); break; } } f->printf("\n"); writebinds(f); f->printf("\n"); loopv(ids) { ident &id = *ids[i]; if(id.type==ID_ALIAS && id.flags&IDF_PERSIST && !(id.flags&IDF_OVERRIDDEN)) switch(id.valtype) { case VAL_STR: if(!id.val.s[0]) break; if(!validatealias(id.val.s)) { f->printf("\"%s\" = ", id.name); writeescapedstring(f, id.val.s); f->putchar('\n'); break; } case VAL_FLOAT: case VAL_INT: f->printf("\"%s\" = [%s]\n", id.name, id.getstr()); break; } } f->printf("\n"); writecompletions(f); f->printf("\n]\n\n"); game::writeclientinfo(f); delete f; } COMMAND(writecfg, "s"); #endif // below the commands that implement a small imperative language. thanks to the semantics of // () and [] expressions, any control construct can be defined trivially. static string retbuf[3]; static int retidx = 0; const char *intstr(int v) { retidx = (retidx + 1)%3; formatstring(retbuf[retidx])("%d", v); return retbuf[retidx]; } void intret(int v) { commandret->setint(v); } const char *floatstr(float v) { retidx = (retidx + 1)%3; formatstring(retbuf[retidx])(v==int(v) ? "%.1f" : "%.7g", v); return retbuf[retidx]; } void floatret(float v) { commandret->setfloat(v); } #undef ICOMMANDNAME #define ICOMMANDNAME(name) _stdcmd static inline bool getbool(const tagval &v) { switch(v.type) { case VAL_NULL: return false; case VAL_FLOAT: return v.f!=0; case VAL_INT: return v.i!=0; case VAL_STR: case VAL_MACRO: return v.s[0] && (!isinteger(v.s) || parseint(v.s)); default: return false; } } ICOMMAND(exists, "r", (ident *id), intret(! (id->flags & IDF_UNKNOWN))); ICOMMAND(if, "tee", (tagval *cond, uint *t, uint *f), executeret(getbool(*cond) ? t : f, *commandret)); ICOMMAND(?, "ttt", (tagval *cond, tagval *t, tagval *f), result(*(getbool(*cond) ? t : f))); ICOMMAND(loop, "rie", (ident *id, int *n, uint *body), { if(*n <= 0 || id->type!=ID_ALIAS) return; identstack stack; loopi(*n) { if(i) { if(id->valtype != VAL_INT) { if(id->valtype == VAL_STR) delete[] id->val.s; freecode(*id); id->valtype = VAL_INT; } id->val.i = i; } else { tagval zero; zero.setint(0); pusharg(*id, zero, stack); id->flags &= ~IDF_UNKNOWN; } execute(body); } poparg(*id); }); ICOMMAND(loopwhile, "riee", (ident *id, int *n, uint *cond, uint *body), { if(*n <= 0 || id->type!=ID_ALIAS) return; identstack stack; loopi(*n) { if(i) { if(id->valtype != VAL_INT) { if(id->valtype == VAL_STR) delete[] id->val.s; freecode(*id); id->valtype = VAL_INT; } id->val.i = i; } else { tagval zero; zero.setint(0); pusharg(*id, zero, stack); id->flags &= ~IDF_UNKNOWN; } if(!execute(cond)) break; execute(body); } poparg(*id); }); ICOMMAND(while, "ee", (uint *cond, uint *body), while(execute(cond)) execute(body)); // can't get any simpler than this :) void concat(tagval *v, int n) { commandret->setstr(conc(v, n, true)); } void concatword(tagval *v, int n) { commandret->setstr(conc(v, n, false)); } void result(tagval &v) { *commandret = v; v.type = VAL_NULL; } void result(const char *s) { commandret->setstr(newstring(s)); } void format(tagval *args, int numargs) { vector s; const char *f = args[0].getstr(); while(*f) { int c = *f++; if(c == '%') { int i = *f++; if(i >= '1' && i <= '9') { i -= '0'; const char *sub = i < numargs ? args[i].getstr() : ""; while(*sub) s.add(*sub++); } else s.add(i); } else s.add(c); } s.add('\0'); result(s.getbuf()); } #define whitespaceskip s += strspn(s, "\n\t ") #define elementskip *s=='"' ? (++s, s += strcspn(s, "\"\n\0"), s += *s=='"') : s += strcspn(s, "\n\t \0") void explodelist(const char *s, vector &elems) { whitespaceskip; while(*s) { const char *elem = s; elementskip; elems.add(*elem=='"' ? newstring(elem+1, s-elem-(s[-1]=='"' ? 2 : 1)) : newstring(elem, s-elem)); whitespaceskip; } } char *indexlist(const char *s, int pos) { whitespaceskip; loopi(pos) { elementskip; whitespaceskip; if(!*s) break; } const char *e = s; elementskip; if(*e=='"') { e++; if(s[-1]=='"') --s; } return newstring(e, s-e); } int listlen(const char *s) { int n = 0; whitespaceskip; for(; *s; n++) elementskip, whitespaceskip; return n; } void at(char *s, int *pos) { commandret->setstr(indexlist(s, *pos)); } void substr(char *s, int *start, char *count) { int len = strlen(s), offset = clamp(*start, 0, len); commandret->setstr(newstring(&s[offset], count[0] ? clamp(parseint(count), 0, len - offset) : len - offset)); } void sublist(char *s, int *start, char *count) { int offset = max(*start, 0), len = count[0] ? max(parseint(count), 0) : -1; if(offset > 0) { loopi(offset) { whitespaceskip; elementskip; if(!*s) break; } whitespaceskip; } if(len < 0) { commandret->setstr(newstring(s)); return; } const char *e = s; loopi(len) { whitespaceskip; elementskip; if(!*s) break; } commandret->setstr(newstring(e, s - e)); } void getalias_(char *s) { result(getalias(s)); } ICOMMAND(exec, "s", (char *file), execfile(file)); ICOMMAND(result, "t", (tagval *v), { *commandret = *v; v->type = VAL_NULL; }); COMMAND(concat, "V"); COMMAND(concatword, "V"); COMMAND(format, "V"); COMMAND(at, "si"); COMMAND(substr, "sis"); COMMAND(sublist, "sis"); ICOMMAND(listlen, "s", (char *s), intret(listlen(s))); COMMANDN(getalias, getalias_, "s"); ICOMMAND(getvarmin, "s", (char *s), intret(getvarmin(s))); ICOMMAND(getvarmax, "s", (char *s), intret(getvarmax(s))); ICOMMAND(getfvarmin, "s", (char *s), floatret(getfvarmin(s))); ICOMMAND(getfvarmax, "s", (char *s), floatret(getfvarmax(s))); ICOMMAND(isdir, "s", (char *dir), intret(isdir(dir))); void looplist(ident *id, const char *list, const uint *body, bool search) { if(id->type!=ID_ALIAS) { if(search) intret(-1); return; } identstack stack; int n = 0; for(const char *s = list;;) { whitespaceskip; if(!*s) { if(search) intret(-1); break; } const char *start = s; elementskip; const char *end = s; if(*start=='"') { start++; if(end[-1]=='"') --end; } char *val = newstring(start, end-start); if(n++) { if(id->type == VAL_STR) delete[] id->val.s; else id->valtype = VAL_STR; freecode(*id); id->val.s = val; } else { tagval t; t.setstr(val); pusharg(*id, t, stack); id->flags &= ~IDF_UNKNOWN; } if(execute(body) && search) { intret(n-1); break; } } if(n) poparg(*id); } void prettylist(const char *s, const char *conj) { vector p; whitespaceskip; for(int len = listlen(s), n = 0; *s; n++) { const char *elem = s; elementskip; p.put(elem, s - elem); if(n+1 < len) { if(len > 2 || !conj[0]) p.add(','); if(n+2 == len && conj[0]) { p.add(' '); p.put(conj, strlen(conj)); } p.add(' '); } whitespaceskip; } p.add('\0'); result(p.getbuf()); } COMMAND(prettylist, "ss"); int listincludes(const char *list, const char *needle, int needlelen) { const char *s = list; whitespaceskip; int offset = 0; while(*s) { const char *elem = s; elementskip; int len = s-elem; if(*elem=='"') { elem++; len -= s[-1]=='"' ? 2 : 1; } if(needlelen == len && !strncmp(needle, elem, len)) return offset; whitespaceskip; offset++; } return -1; } char *listdel(const char *s, const char *del) { vector p; whitespaceskip; while(*s) { const char *elem = s, *pelem = elem; elementskip; int len = s-elem, plen = len; if(*elem=='"') { elem++; len -= s[-1]=='"' ? 2 : 1; } if(listincludes(del, elem, len) < 0) { if(!p.empty()) p.add(' '); p.put(pelem, plen); } whitespaceskip; } p.add('\0'); return newstring(p.getbuf()); } ICOMMAND(listdel, "ss", (char *list, char *del), commandret->setstr(listdel(list, del))); ICOMMAND(indexof, "ss", (char *list, char *elem), intret(listincludes(list, elem, strlen(elem)))); ICOMMAND(listfind, "rse", (ident *id, char *list, uint *body), looplist(id, list, body, true)); ICOMMAND(looplist, "rse", (ident *id, char *list, uint *body), looplist(id, list, body, false)); ICOMMAND(loopfiles, "rsse", (ident *id, char *dir, char *ext, uint *body), { if(id->type!=ID_ALIAS) return; identstack stack; vector files; listfiles(dir, ext[0] ? ext : NULL, files); loopv(files) { char *file = files[i]; bool redundant = false; loopj(i) if(!strcmp(files[j], file)) { redundant = true; break; } if(redundant) { delete[] file; continue; } if(i) { if(id->type == VAL_STR) delete[] id->val.s; else id->valtype = VAL_STR; id->val.s = file; } else { tagval t; t.setstr(file); pusharg(*id, t, stack); id->flags &= ~IDF_UNKNOWN; } execute(body); } if(files.length()) poparg(*id); }); //assume directories don't have extensions - AKA a hack ICOMMAND(loopdir, "rse", (ident *id, char *dir, uint *body), { if(id->type != ID_ALIAS) return; identstack stack; vector files; listfiles(dir, NULL, files); loopv(files) { char *t = strstr(files[i], "."); if(t) { delete files[i]; files.remove(i); i--; } else { loopj(i) { if(!strcmp(files[i], files[j])) { delete[] files[i]; files.remove(i); i--; break; } } } } loopv(files) { if(i) { if(id->valtype == VAL_STR) delete[] id->val.s; id->val.s = files[i]; } else { tagval t; t.setstr(files[i]); pusharg(*id, t, stack); id->flags &= ~IDF_UNKNOWN; } execute(body); } }); ICOMMAND(+, "ii", (int *a, int *b), intret(*a + *b)); ICOMMAND(*, "ii", (int *a, int *b), intret(*a * *b)); ICOMMAND(-, "ii", (int *a, int *b), intret(*a - *b)); ICOMMAND(+f, "ff", (float *a, float *b), floatret(*a + *b)); ICOMMAND(*f, "ff", (float *a, float *b), floatret(*a * *b)); ICOMMAND(-f, "ff", (float *a, float *b), floatret(*a - *b)); ICOMMAND(=, "ii", (int *a, int *b), intret((int)(*a == *b))); ICOMMAND(!=, "ii", (int *a, int *b), intret((int)(*a != *b))); ICOMMAND(<, "ii", (int *a, int *b), intret((int)(*a < *b))); ICOMMAND(>, "ii", (int *a, int *b), intret((int)(*a > *b))); ICOMMAND(<=, "ii", (int *a, int *b), intret((int)(*a <= *b))); ICOMMAND(>=, "ii", (int *a, int *b), intret((int)(*a >= *b))); ICOMMAND(=f, "ff", (float *a, float *b), intret((int)(*a == *b))); ICOMMAND(!=f, "ff", (float *a, float *b), intret((int)(*a != *b))); ICOMMAND(f, "ff", (float *a, float *b), intret((int)(*a > *b))); ICOMMAND(<=f, "ff", (float *a, float *b), intret((int)(*a <= *b))); ICOMMAND(>=f, "ff", (float *a, float *b), intret((int)(*a >= *b))); ICOMMAND(^, "ii", (int *a, int *b), intret(*a ^ *b)); ICOMMAND(!, "i", (int *a), intret(*a == 0)); ICOMMAND(&, "ii", (int *a, int *b), intret(*a & *b)); ICOMMAND(|, "ii", (int *a, int *b), intret(*a | *b)); ICOMMAND(~, "i", (int *a), intret(~*a)); ICOMMAND(^~, "ii", (int *a, int *b), intret(*a ^ ~*b)); ICOMMAND(&~, "ii", (int *a, int *b), intret(*a & ~*b)); ICOMMAND(|~, "ii", (int *a, int *b), intret(*a | ~*b)); ICOMMAND(<<, "ii", (int *a, int *b), intret(*a << *b)); ICOMMAND(>>, "ii", (int *a, int *b), intret(*a >> *b)); ICOMMAND(&&, "e1V", (tagval *args, int numargs), { int val = 1; loopi(numargs) { val = execute(args[i].code); if(!val) break; } intret(val); }); ICOMMAND(||, "e1V", (tagval *args, int numargs), { int val = 0; loopi(numargs) { val = execute(args[i].code); if(val) break; } intret(val); }); ICOMMAND(div, "ii", (int *a, int *b), intret(*b ? *a / *b : 0)); ICOMMAND(mod, "ii", (int *a, int *b), intret(*b ? *a % *b : 0)); ICOMMAND(divf, "ff", (float *a, float *b), floatret(*b ? *a / *b : 0)); ICOMMAND(modf, "ff", (float *a, float *b), floatret(*b ? fmod(*a, *b) : 0)); ICOMMAND(sin, "f", (float *a), floatret(sin(*a*RAD))); ICOMMAND(cos, "f", (float *a), floatret(cos(*a*RAD))); ICOMMAND(tan, "f", (float *a), floatret(tan(*a*RAD))); ICOMMAND(asin, "f", (float *a), floatret(asin(*a)/RAD)); ICOMMAND(acos, "f", (float *a), floatret(acos(*a)/RAD)); ICOMMAND(atan, "f", (float *a), floatret(atan(*a)/RAD)); ICOMMAND(sqrt, "f", (float *a), floatret(sqrt(*a))); ICOMMAND(pow, "ff", (float *a, float *b), floatret(pow(*a, *b))); ICOMMAND(loge, "f", (float *a), floatret(log(*a))); ICOMMAND(log2, "f", (float *a), floatret(log(*a)/M_LN2)); ICOMMAND(log10, "f", (float *a), floatret(log10(*a))); ICOMMAND(exp, "f", (float *a), floatret(exp(*a))); ICOMMAND(min, "V", (tagval *args, int numargs), { int val = numargs > 0 ? args[numargs - 1].getint() : 0; loopi(numargs - 1) val = min(val, args[i].getint()); intret(val); }); ICOMMAND(max, "V", (tagval *args, int numargs), { int val = numargs > 0 ? args[numargs - 1].getint() : 0; loopi(numargs - 1) val = max(val, args[i].getint()); intret(val); }); ICOMMAND(minf, "V", (tagval *args, int numargs), { float val = numargs > 0 ? args[numargs - 1].getfloat() : 0.0f; loopi(numargs - 1) val = min(val, args[i].getfloat()); floatret(val); }); ICOMMAND(maxf, "V", (tagval *args, int numargs), { float val = numargs > 0 ? args[numargs - 1].getfloat() : 0.0f; loopi(numargs - 1) val = max(val, args[i].getfloat()); floatret(val); }); ICOMMAND(abs, "i", (int *n), intret(abs(*n))); ICOMMAND(absf, "f", (float *n), floatret(fabs(*n))); ICOMMAND(cond, "ee2V", (tagval *args, int numargs), { for(int i = 0; i < numargs; i += 2) { if(execute(args[i].code)) { if(i+1 < numargs) executeret(args[i+1].code, *commandret); break; } } }); #define CASECOMMAND(name, fmt, type, acc, compare) \ ICOMMAND(name, fmt "te2V", (tagval *args, int numargs), \ { \ type val = acc; \ int i; \ for(i = 1; i+1 < numargs; i += 2) \ { \ if(compare) \ { \ executeret(args[i+1].code, *commandret); \ return; \ } \ } \ }) CASECOMMAND(case, "i", int, args[0].getint(), args[i].type == VAL_NULL || args[i].getint() == val); CASECOMMAND(casef, "f", float, args[0].getfloat(), args[i].type == VAL_NULL || args[i].getfloat() == val); CASECOMMAND(cases, "s", const char *, args[0].getstr(), args[i].type == VAL_NULL || !strcmp(args[i].getstr(), val)); ICOMMAND(rnd, "ii", (int *a, int *b), intret(*a - *b > 0 ? rnd(*a - *b) + *b : *b)); ICOMMAND(strcmp, "ss", (char *a, char *b), intret(strcmp(a,b)==0)); ICOMMAND(=s, "ss", (char *a, char *b), intret(strcmp(a,b)==0)); ICOMMAND(!=s, "ss", (char *a, char *b), intret(strcmp(a,b)!=0)); ICOMMAND(s, "ss", (char *a, char *b), intret(strcmp(a,b)>0)); ICOMMAND(<=s, "ss", (char *a, char *b), intret(strcmp(a,b)<=0)); ICOMMAND(>=s, "ss", (char *a, char *b), intret(strcmp(a,b)>=0)); ICOMMAND(echo, "C", (char *s), conoutf("\f1%s", s)); ICOMMAND(error, "C", (char *s), conoutf(CON_ERROR, s)); ICOMMAND(strstr, "ss", (char *a, char *b), { char *s = strstr(a, b); intret(s ? s-a : -1); }); ICOMMAND(strlen, "s", (char *s), intret(strlen(s))); char *strreplace(const char *s, const char *oldval, const char *newval) { vector buf; int oldlen = strlen(oldval); if(!oldlen) return newstring(s); for(;;) { const char *found = strstr(s, oldval); if(found) { while(s < found) buf.add(*s++); for(const char *n = newval; *n; n++) buf.add(*n); s = found + oldlen; } else { while(*s) buf.add(*s++); buf.add('\0'); return newstring(buf.getbuf(), buf.length()); } } } ICOMMAND(strreplace, "sss", (char *s, char *o, char *n), commandret->setstr(strreplace(s, o, n))); #ifndef STANDALONE struct sleepcmd { int delay, millis, flags; char *command; }; vector sleepcmds; void addsleep(int *msec, char *cmd) { sleepcmd &s = sleepcmds.add(); s.delay = max(*msec, 1); s.millis = lastmillis; s.command = newstring(cmd); s.flags = identflags; } COMMANDN(sleep, addsleep, "is"); void checksleep(int millis) { loopv(sleepcmds) { sleepcmd &s = sleepcmds[i]; if(millis - s.millis >= s.delay) { char *cmd = s.command; // execute might create more sleep commands s.command = NULL; int oldflags = identflags; identflags = s.flags; execute(cmd); identflags = oldflags; delete[] cmd; if(sleepcmds.inrange(i) && !sleepcmds[i].command) sleepcmds.remove(i--); } } } void clearsleep(bool clearoverrides) { int len = 0; loopv(sleepcmds) if(sleepcmds[i].command) { if(clearoverrides && !(sleepcmds[i].flags&IDF_OVERRIDDEN)) sleepcmds[len++] = sleepcmds[i]; else delete[] sleepcmds[i].command; } sleepcmds.shrink(len); } void clearsleep_(int *clearoverrides) { clearsleep(*clearoverrides!=0 || identflags&IDF_OVERRIDDEN); } COMMANDN(clearsleep, clearsleep_, "i"); #endif sandboxgamemaker-2.7.1+dfsg/src/engine/iqm.h0000664000175000017500000003554211637730516020667 0ustar showardshowardstruct iqm; struct iqmheader { char magic[16]; uint version; uint filesize; uint flags; uint num_text, ofs_text; uint num_meshes, ofs_meshes; uint num_vertexarrays, num_vertexes, ofs_vertexarrays; uint num_triangles, ofs_triangles, ofs_adjacency; uint num_joints, ofs_joints; uint num_poses, ofs_poses; uint num_anims, ofs_anims; uint num_frames, num_framechannels, ofs_frames, ofs_bounds; uint num_comment, ofs_comment; uint num_extensions, ofs_extensions; }; struct iqmmesh { uint name; uint material; uint first_vertex, num_vertexes; uint first_triangle, num_triangles; }; enum { IQM_POSITION = 0, IQM_TEXCOORD = 1, IQM_NORMAL = 2, IQM_TANGENT = 3, IQM_BLENDINDEXES = 4, IQM_BLENDWEIGHTS = 5, IQM_COLOR = 6, IQM_CUSTOM = 0x10 }; enum { IQM_BYTE = 0, IQM_UBYTE = 1, IQM_SHORT = 2, IQM_USHORT = 3, IQM_INT = 4, IQM_UINT = 5, IQM_HALF = 6, IQM_FLOAT = 7, IQM_DOUBLE = 8, }; struct iqmtriangle { uint vertex[3]; }; struct iqmjoint { uint name; int parent; vec pos; quat orient; vec size; }; struct iqmpose { int parent; uint mask; vec offsetpos; vec4 offsetorient; vec offsetsize; vec scalepos; vec4 scaleorient; vec scalesize; }; struct iqmanim { uint name; uint first_frame, num_frames; float framerate; uint flags; }; struct iqmvertexarray { uint type; uint flags; uint format; uint size; uint offset; }; struct iqm : skelmodel, skelloader { iqm(const char *name) : skelmodel(name) {} static const char *formatname() { return "iqm"; } int type() const { return MDL_IQM; } struct iqmmeshgroup : skelmeshgroup { iqmmeshgroup() { } bool loadiqmmeshes(const char *filename, const iqmheader &hdr, uchar *buf) { lilswap((uint *)&buf[hdr.ofs_vertexarrays], hdr.num_vertexarrays*sizeof(iqmvertexarray)/sizeof(uint)); lilswap((uint *)&buf[hdr.ofs_triangles], hdr.num_triangles*sizeof(iqmtriangle)/sizeof(uint)); lilswap((uint *)&buf[hdr.ofs_meshes], hdr.num_meshes*sizeof(iqmmesh)/sizeof(uint)); lilswap((uint *)&buf[hdr.ofs_joints], hdr.num_joints*sizeof(iqmjoint)/sizeof(uint)); const char *str = hdr.ofs_text ? (char *)&buf[hdr.ofs_text] : ""; float *vpos = NULL, *vnorm = NULL, *vtan = NULL, *vtc = NULL; uchar *vindex = NULL, *vweight = NULL; iqmvertexarray *vas = (iqmvertexarray *)&buf[hdr.ofs_vertexarrays]; loopi(hdr.num_vertexarrays) { iqmvertexarray &va = vas[i]; switch(va.type) { case IQM_POSITION: if(va.format != IQM_FLOAT || va.size != 3) return false; vpos = (float *)&buf[va.offset]; lilswap(vpos, 3*hdr.num_vertexes); break; case IQM_NORMAL: if(va.format != IQM_FLOAT || va.size != 3) return false; vnorm = (float *)&buf[va.offset]; lilswap(vnorm, 3*hdr.num_vertexes); break; case IQM_TANGENT: if(va.format != IQM_FLOAT || va.size != 4) return false; vtan = (float *)&buf[va.offset]; lilswap(vtan, 4*hdr.num_vertexes); break; case IQM_TEXCOORD: if(va.format != IQM_FLOAT || va.size != 2) return false; vtc = (float *)&buf[va.offset]; lilswap(vtc, 2*hdr.num_vertexes); break; case IQM_BLENDINDEXES: if(va.format != IQM_UBYTE || va.size != 4) return false; vindex = (uchar *)&buf[va.offset]; break; case IQM_BLENDWEIGHTS: if(va.format != IQM_UBYTE || va.size != 4) return false; vweight = (uchar *)&buf[va.offset]; break; } } iqmtriangle *tris = (iqmtriangle *)&buf[hdr.ofs_triangles]; iqmmesh *imeshes = (iqmmesh *)&buf[hdr.ofs_meshes]; iqmjoint *joints = (iqmjoint *)&buf[hdr.ofs_joints]; if(hdr.num_joints) { if(skel->numbones <= 0) { skel->numbones = hdr.num_joints; skel->bones = new boneinfo[skel->numbones]; loopi(hdr.num_joints) { iqmjoint &j = joints[i]; boneinfo &b = skel->bones[i]; if(!b.name) b.name = newstring(&str[j.name]); b.parent = j.parent; if(skel->shared <= 1) { j.pos.y = -j.pos.y; j.orient.x = -j.orient.x; j.orient.z = -j.orient.z; j.orient.normalize(); b.base = dualquat(j.orient, j.pos); if(b.parent >= 0) b.base.mul(skel->bones[b.parent].base, dualquat(b.base)); (b.invbase = b.base).invert(); } } } if(skel->shared <= 1) skel->linkchildren(); } loopi(hdr.num_meshes) { iqmmesh &im = imeshes[i]; skelmesh *m = new skelmesh; m->group = this; meshes.add(m); m->name = newstring(&str[im.name]); m->numverts = im.num_vertexes; if(m->numverts) { m->verts = new vert[m->numverts]; if(vtan) m->bumpverts = new bumpvert[m->numverts]; } loopj(im.num_vertexes) { int fj = j + im.first_vertex; vert &v = m->verts[j]; loopk(3) v.pos[k] = vpos[3*fj + k]; v.pos.y = -v.pos.y; v.u = vtc[2*fj + 0]; v.v = vtc[2*fj + 1]; if(vnorm) { loopk(3) v.norm[k] = vnorm[3*fj + k]; v.norm.y = -v.norm.y; if(vtan) { bumpvert &bv = m->bumpverts[j]; loopk(3) bv.tangent[k] = vtan[4*fj + k]; bv.tangent.y = -bv.tangent.y; bv.bitangent = vtan[4*fj + 3]; } } blendcombo c; int sorted = 0; if(vindex && vweight) loopk(4) sorted = c.addweight(sorted, vweight[4*fj + k], vindex[4*fj + k]); c.finalize(sorted); v.blend = m->addblendcombo(c); } m->numtris = im.num_triangles; if(m->numtris) m->tris = new tri[m->numtris]; loopj(im.num_triangles) { int fj = j + im.first_triangle; loopk(3) m->tris[j].vert[k] = tris[fj].vertex[k] - im.first_vertex; } if(!m->numtris || !m->numverts) { conoutf("empty mesh in %s", filename); meshes.removeobj(m); delete m; } } sortblendcombos(); return true; } bool loadiqmanims(const char *filename, const iqmheader &hdr, uchar *buf) { lilswap((uint *)&buf[hdr.ofs_poses], hdr.num_poses*sizeof(iqmpose)/sizeof(uint)); lilswap((uint *)&buf[hdr.ofs_anims], hdr.num_anims*sizeof(iqmanim)/sizeof(uint)); lilswap((ushort *)&buf[hdr.ofs_frames], hdr.num_frames*hdr.num_framechannels); const char *str = hdr.ofs_text ? (char *)&buf[hdr.ofs_text] : ""; iqmpose *poses = (iqmpose *)&buf[hdr.ofs_poses]; iqmanim *anims = (iqmanim *)&buf[hdr.ofs_anims]; ushort *frames = (ushort *)&buf[hdr.ofs_frames]; loopi(hdr.num_anims) { iqmanim &a = anims[i]; string name; copystring(name, filename); concatstring(name, ":"); concatstring(name, &str[a.name]); conoutf("%s", name); skelanimspec *sa = skel->findskelanim(name); if(sa) continue; sa = &skel->addskelanim(name); sa->frame = skel->numframes; sa->range = a.num_frames; dualquat *animbones = new dualquat[(skel->numframes+a.num_frames)*skel->numbones]; if(skel->bones) { memcpy(animbones, skel->framebones, skel->numframes*skel->numbones*sizeof(dualquat)); delete[] skel->framebones; } skel->framebones = animbones; animbones += skel->numframes*skel->numbones; skel->numframes += a.num_frames; ushort *animdata = &frames[a.first_frame*hdr.num_framechannels]; loopj(a.num_frames) { dualquat *frame = &animbones[j*skel->numbones]; loopk(skel->numbones) { iqmpose &p = poses[k]; vec pos; quat orient; pos.x = p.offsetpos.x; if(p.mask&0x01) pos.x += *animdata++ * p.scalepos.x; pos.y = -p.offsetpos.y; if(p.mask&0x02) pos.y -= *animdata++ * p.scalepos.y; pos.z = p.offsetpos.z; if(p.mask&0x04) pos.z += *animdata++ * p.scalepos.z; orient.x = -p.offsetorient.x; if(p.mask&0x08) orient.x -= *animdata++ * p.scaleorient.x; orient.y = p.offsetorient.y; if(p.mask&0x10) orient.y += *animdata++ * p.scaleorient.y; orient.z = -p.offsetorient.z; if(p.mask&0x20) orient.z -= *animdata++ * p.scaleorient.z; orient.w = p.offsetorient.w; if(p.mask&0x40) orient.w += *animdata++ * p.scaleorient.w; orient.normalize(); if(p.mask&0x380) { if(p.mask&0x80) animdata++; if(p.mask&0x100) animdata++; if(p.mask&0x200) animdata++; } frame[k] = dualquat(orient, pos); if(adjustments.inrange(k)) adjustments[k].adjust(frame[k]); boneinfo &b = skel->bones[k]; frame[k].mul(b.invbase); if(b.parent >= 0) frame[k].mul(skel->bones[b.parent].base, dualquat(frame[k])); frame[k].fixantipodal(skel->framebones[k]); } } } return true; } bool loadiqm(const char *filename, bool doloadmesh, bool doloadanim) { stream *f = openfile(filename, "rb"); if(!f) return false; uchar *buf = NULL; iqmheader hdr; if(f->read(&hdr, sizeof(hdr)) != sizeof(hdr) || memcmp(hdr.magic, "INTERQUAKEMODEL", sizeof(hdr.magic))) goto error; lilswap(&hdr.version, (sizeof(hdr) - sizeof(hdr.magic))/sizeof(uint)); if(hdr.version != 2) goto error; if(hdr.filesize > (16<<20)) goto error; // sanity check... don't load files bigger than 16 MB buf = new uchar[hdr.filesize]; if(f->read(buf + sizeof(hdr), hdr.filesize - sizeof(hdr)) != int(hdr.filesize - sizeof(hdr))) goto error; if(doloadmesh && !loadiqmmeshes(filename, hdr, buf)) goto error; if(doloadanim && !loadiqmanims(filename, hdr, buf)) goto error; delete[] buf; delete f; return true; error: if(buf) delete[] buf; delete f; return false; } bool loadmesh(const char *filename) { name = newstring(filename); return loadiqm(filename, true, false); } skelanimspec *loadanim(const char *animname) { const char *sep = strchr(animname, ':'); skelanimspec *sa = skel->findskelanim(animname, sep ? '\0' : ':'); if(!sa) { string filename; copystring(filename, animname); if(sep) filename[sep - animname] = '\0'; if(loadiqm(filename, false, true)) sa = skel->findskelanim(animname, sep ? '\0' : ':'); } return sa; } }; meshgroup *loadmeshes(char *name, va_list args) { iqmmeshgroup *group = new iqmmeshgroup; group->shareskeleton(va_arg(args, char *)); if(!group->loadmesh(name)) { delete group; return NULL; } return group; } bool loaddefaultparts() { skelpart &mdl = *new skelpart; parts.add(&mdl); mdl.model = this; mdl.index = 0; mdl.pitchscale = mdl.pitchoffset = mdl.pitchmin = mdl.pitchmax = 0; adjustments.setsize(0); const char *fname = loadname + strlen(loadname); do --fname; while(fname >= loadname && *fname!='/' && *fname!='\\'); fname++; defformatstring(meshname)("packages/models/%s/%s.iqm", loadname, fname); mdl.meshes = sharemeshes(path(meshname), NULL); if(!mdl.meshes) return false; mdl.initanimparts(); mdl.initskins(); return true; } bool load() { if(loaded) return true; formatstring(dir)("packages/models/%s", loadname); defformatstring(cfgname)("packages/models/%s/iqm.cfg", loadname); loading = this; identflags &= ~IDF_PERSIST; if(execfile(cfgname, false) && parts.length()) // configured iqm, will call the iqm* commands below { identflags |= IDF_PERSIST; loading = NULL; loopv(parts) if(!parts[i]->meshes) return false; } else // iqm without configuration, try default tris and skin { identflags |= IDF_PERSIST; if(!loaddefaultparts()) { loading = NULL; return false; } loading = NULL; } scale /= 4; parts[0]->translate = translate; loopv(parts) { skelpart *p = (skelpart *)parts[i]; p->endanimparts(); p->meshes->shared++; } preloadshaders(); return loaded = true; } }; skelcommands iqmcommands; sandboxgamemaker-2.7.1+dfsg/src/engine/pch.cpp0000664000175000017500000000002711400572336021164 0ustar showardshoward#include "engine.h" sandboxgamemaker-2.7.1+dfsg/src/engine/world.h0000664000175000017500000000321111642642476021217 0ustar showardshoward enum // hardcoded texture numbers { DEFAULT_SKY = 0, DEFAULT_GEOM }; enum { MAP_OCTA = 0, MAP_PAS }; #define MAPVERSION 32 // bump if map format changes, see worldio.cpp #define PASMAPVERSION 6 struct octaheader { char magic[4]; // "OCTA" int version; // any >8bit quantity is little endian int headersize; // sizeof(header) int worldsize; int numents; int numpvs; int lightmaps; int blendmap; int numvars; int numvslots; }; struct compatheader // map file format header { char magic[4]; // "OCTA" int version; // any >8bit quantity is little endian int headersize; // sizeof(header) int worldsize; int numents; int numpvs; int lightmaps; int lightprecision, lighterror, lightlod; uchar ambient; uchar watercolour[3]; uchar blendmap; uchar lerpangle, lerpsubdiv, lerpsubdivsize; uchar bumperror; uchar skylight[3]; uchar lavacolour[3]; uchar waterfallcolour[3]; uchar reserved[10]; char maptitle[128]; }; #define WATER_AMPLITUDE 0.4f #define WATER_OFFSET 1.1f enum { MATSURF_NOT_VISIBLE = 0, MATSURF_VISIBLE, MATSURF_EDIT_ONLY }; #define TEX_SCALE 8.0f struct vertexff { vec pos; bvec norm; uchar reserved; float u, v; float lmu, lmv; }; struct vertex { vec pos; bvec norm; uchar reserved; float u, v; short lmu, lmv; bvec tangent; uchar bitangent; }; #define VTXSIZE (renderpath==R_FIXEDFUNCTION ? sizeof(vertexff) : sizeof(vertex)) sandboxgamemaker-2.7.1+dfsg/src/engine/blend.cpp0000664000175000017500000005706611527772736021535 0ustar showardshoward#include "engine.h" enum { BM_BRANCH = 0, BM_SOLID, BM_IMAGE }; struct BlendMapBranch; struct BlendMapSolid; struct BlendMapImage; struct BlendMapNode { union { BlendMapBranch *branch; BlendMapSolid *solid; BlendMapImage *image; }; void cleanup(int type); void splitsolid(uchar &type, uchar val); }; struct BlendMapBranch { uchar type[4]; BlendMapNode children[4]; ~BlendMapBranch() { loopi(4) children[i].cleanup(type[i]); } uchar shrink(BlendMapNode &child, int quadrant); }; struct BlendMapSolid { uchar val; BlendMapSolid(uchar val) : val(val) {} }; #define BM_SCALE 1 #define BM_IMAGE_SIZE 64 struct BlendMapImage { uchar data[BM_IMAGE_SIZE*BM_IMAGE_SIZE]; }; void BlendMapNode::cleanup(int type) { switch(type) { case BM_BRANCH: delete branch; break; case BM_IMAGE: delete image; break; } } #define DEFBMSOLIDS(n) n, n+1, n+2, n+3, n+4, n+5, n+6, n+7, n+8, n+9, n+10, n+11, n+12, n+13, n+14, n+15 static BlendMapSolid bmsolids[256] = { DEFBMSOLIDS(0x00), DEFBMSOLIDS(0x10), DEFBMSOLIDS(0x20), DEFBMSOLIDS(0x30), DEFBMSOLIDS(0x40), DEFBMSOLIDS(0x50), DEFBMSOLIDS(0x60), DEFBMSOLIDS(0x70), DEFBMSOLIDS(0x80), DEFBMSOLIDS(0x90), DEFBMSOLIDS(0xA0), DEFBMSOLIDS(0xB0), DEFBMSOLIDS(0xC0), DEFBMSOLIDS(0xD0), DEFBMSOLIDS(0xE0), DEFBMSOLIDS(0xF0), }; void BlendMapNode::splitsolid(uchar &type, uchar val) { cleanup(type); type = BM_BRANCH; branch = new BlendMapBranch; loopi(4) { branch->type[i] = BM_SOLID; branch->children[i].solid = &bmsolids[val]; } } uchar BlendMapBranch::shrink(BlendMapNode &child, int quadrant) { loopi(4) if(i != quadrant) children[i].cleanup(type[i]); uchar childtype = type[quadrant]; child = children[quadrant]; type[quadrant] = BM_SOLID; children[quadrant].solid = &bmsolids[0]; return childtype; } struct BlendMapRoot : BlendMapNode { uchar type; BlendMapRoot() : type(BM_SOLID) { solid = &bmsolids[0xFF]; } BlendMapRoot(uchar type, const BlendMapNode &node) : BlendMapNode(node), type(type) {} void cleanup() { BlendMapNode::cleanup(type); } void shrink(int quadrant) { if(type == BM_BRANCH) { BlendMapRoot oldroot = *this; type = branch->shrink(*this, quadrant); oldroot.cleanup(); } } }; static BlendMapRoot blendmap; struct BlendMapCache { BlendMapRoot node; int scale; ivec origin; }; BlendMapCache *newblendmapcache() { return new BlendMapCache; } void freeblendmapcache(BlendMapCache *&cache) { delete cache; cache = NULL; } bool setblendmaporigin(BlendMapCache *cache, const ivec &o, int size) { if(blendmap.type!=BM_BRANCH) { cache->node = blendmap; cache->scale = worldscale-BM_SCALE; cache->origin = ivec(0, 0, 0); return cache->node.solid!=&bmsolids[0xFF]; } BlendMapBranch *bm = blendmap.branch; int bmscale = worldscale-BM_SCALE, bmsize = 1<>BM_SCALE, y = o.y>>BM_SCALE, x1 = max(x-1, 0), y1 = max(y-1, 0), x2 = min(((o.x + size + (1<>BM_SCALE) + 1, bmsize), y2 = min(((o.y + size + (1<>BM_SCALE) + 1, bmsize), diff = (x1^x2)|(y1^y2); if(diff < bmsize) while(!(diff&(1<<(bmscale-1)))) { bmscale--; int n = (((y1>>bmscale)&1)<<1) | ((x1>>bmscale)&1); if(bm->type[n]!=BM_BRANCH) { cache->node = BlendMapRoot(bm->type[n], bm->children[n]); cache->scale = bmscale; cache->origin = ivec(x1&(~0U<node.solid!=&bmsolids[0xFF]; } bm = bm->children[n].branch; } cache->node.type = BM_BRANCH; cache->node.branch = bm; cache->scale = bmscale; cache->origin = ivec(x1&(~0U<node.solid!=&bmsolids[0xFF]; } static uchar lookupblendmap(int x, int y, BlendMapBranch *bm, int bmscale) { for(;;) { bmscale--; int n = (((y>>bmscale)&1)<<1) | ((x>>bmscale)&1); switch(bm->type[n]) { case BM_SOLID: return bm->children[n].solid->val; case BM_IMAGE: return bm->children[n].image->data[(y&((1<children[n].branch; } } uchar lookupblendmap(BlendMapCache *cache, const vec &pos) { if(cache->node.type==BM_SOLID) return cache->node.solid->val; uchar vals[4], *val = vals; float bx = pos.x/(1<origin.x, ry = iy-cache->origin.y; loop(vy, 2) loop(vx, 2) { int cx = clamp(rx+vx, 0, (1<scale)-1), cy = clamp(ry+vy, 0, (1<scale)-1); if(cache->node.type==BM_IMAGE) *val++ = cache->node.image->data[cy*BM_IMAGE_SIZE + cx]; else *val++ = lookupblendmap(cx, cy, cache->node.branch, cache->scale); } float fx = bx - ix, fy = by - iy; return uchar((1-fy)*((1-fx)*vals[0] + fx*vals[1]) + fy*((1-fx)*vals[2] + fx*vals[3])); } static void fillblendmap(uchar &type, BlendMapNode &node, int size, uchar val, int x1, int y1, int x2, int y2) { if(max(x1, y1) <= 0 && min(x2, y2) >= size) { node.cleanup(type); type = BM_SOLID; node.solid = &bmsolids[val]; return; } if(type==BM_BRANCH) { size /= 2; if(y1 < size) { if(x1 < size) fillblendmap(node.branch->type[0], node.branch->children[0], size, val, x1, y1, min(x2, size), min(y2, size)); if(x2 > size) fillblendmap(node.branch->type[1], node.branch->children[1], size, val, max(x1-size, 0), y1, x2-size, min(y2, size)); } if(y2 > size) { if(x1 < size) fillblendmap(node.branch->type[2], node.branch->children[2], size, val, x1, max(y1-size, 0), min(x2, size), y2-size); if(x2 > size) fillblendmap(node.branch->type[3], node.branch->children[3], size, val, max(x1-size, 0), max(y1-size, 0), x2-size, y2-size); } loopi(4) if(node.branch->type[i]!=BM_SOLID || node.branch->children[i].solid->val!=val) return; node.cleanup(type); type = BM_SOLID; node.solid = &bmsolids[val]; return; } else if(type==BM_SOLID) { uchar oldval = node.solid->val; if(oldval==val) return; if(size > BM_IMAGE_SIZE) { node.splitsolid(type, oldval); fillblendmap(type, node, size, val, x1, y1, x2, y2); return; } type = BM_IMAGE; node.image = new BlendMapImage; memset(node.image->data, oldval, sizeof(node.image->data)); } uchar *dst = &node.image->data[y1*BM_IMAGE_SIZE + x1]; loopi(y2-y1) { memset(dst, val, x2-x1); dst += BM_IMAGE_SIZE; } } void fillblendmap(int x, int y, int w, int h, uchar val) { int bmsize = worldsize>>BM_SCALE, x1 = clamp(x, 0, bmsize), y1 = clamp(y, 0, bmsize), x2 = clamp(x+w, 0, bmsize), y2 = clamp(y+h, 0, bmsize); if(max(x1, y1) >= bmsize || min(x2, y2) <= 0 || x1>=x2 || y1>=y2) return; fillblendmap(blendmap.type, blendmap, bmsize, val, x1, y1, x2, y2); } static void invertblendmap(uchar &type, BlendMapNode &node, int size, int x1, int y1, int x2, int y2) { if(type==BM_BRANCH) { size /= 2; if(y1 < size) { if(x1 < size) invertblendmap(node.branch->type[0], node.branch->children[0], size, x1, y1, min(x2, size), min(y2, size)); if(x2 > size) invertblendmap(node.branch->type[1], node.branch->children[1], size, max(x1-size, 0), y1, x2-size, min(y2, size)); } if(y2 > size) { if(x1 < size) invertblendmap(node.branch->type[2], node.branch->children[2], size, x1, max(y1-size, 0), min(x2, size), y2-size); if(x2 > size) invertblendmap(node.branch->type[3], node.branch->children[3], size, max(x1-size, 0), max(y1-size, 0), x2-size, y2-size); } return; } else if(type==BM_SOLID) { fillblendmap(type, node, size, 255-node.solid->val, x1, y1, x2, y2); } else if(type==BM_IMAGE) { uchar *dst = &node.image->data[y1*BM_IMAGE_SIZE + x1]; loopi(y2-y1) { loopj(x2-x1) dst[j] = 255-dst[j]; dst += BM_IMAGE_SIZE; } } } void invertblendmap(int x, int y, int w, int h) { int bmsize = worldsize>>BM_SCALE, x1 = clamp(x, 0, bmsize), y1 = clamp(y, 0, bmsize), x2 = clamp(x+w, 0, bmsize), y2 = clamp(y+h, 0, bmsize); if(max(x1, y1) >= bmsize || min(x2, y2) <= 0 || x1>=x2 || y1>=y2) return; invertblendmap(blendmap.type, blendmap, bmsize, x1, y1, x2, y2); } static void optimizeblendmap(uchar &type, BlendMapNode &node) { switch(type) { case BM_IMAGE: { uint val = node.image->data[0]; val |= val<<8; val |= val<<16; for(uint *data = (uint *)node.image->data, *end = &data[sizeof(node.image->data)/sizeof(uint)]; data < end; data++) if(*data != val) return; node.cleanup(type); type = BM_SOLID; node.solid = &bmsolids[val&0xFF]; break; } case BM_BRANCH: { loopi(4) optimizeblendmap(node.branch->type[i], node.branch->children[i]); if(node.branch->type[3]!=BM_SOLID) return; uint val = node.branch->children[3].solid->val; loopi(3) if(node.branch->type[i]!=BM_SOLID || node.branch->children[i].solid->val != val) return; node.cleanup(type); type = BM_SOLID; node.solid = &bmsolids[val]; break; } } } void optimizeblendmap() { optimizeblendmap(blendmap.type, blendmap); } VARF(blendpaintmode, 0, 0, 5, { if(!blendpaintmode) stoppaintblendmap(); }); static void blitblendmap(uchar &type, BlendMapNode &node, int bmx, int bmy, int bmsize, uchar *src, int sx, int sy, int sw, int sh) { if(type==BM_BRANCH) { bmsize /= 2; if(sy < bmy + bmsize) { if(sx < bmx + bmsize) blitblendmap(node.branch->type[0], node.branch->children[0], bmx, bmy, bmsize, src, sx, sy, sw, sh); if(sx + sw > bmx + bmsize) blitblendmap(node.branch->type[1], node.branch->children[1], bmx+bmsize, bmy, bmsize, src, sx, sy, sw, sh); } if(sy + sh > bmy + bmsize) { if(sx < bmx + bmsize) blitblendmap(node.branch->type[2], node.branch->children[2], bmx, bmy+bmsize, bmsize, src, sx, sy, sw, sh); if(sx + sw > bmx + bmsize) blitblendmap(node.branch->type[3], node.branch->children[3], bmx+bmsize, bmy+bmsize, bmsize, src, sx, sy, sw, sh); } return; } if(type==BM_SOLID) { uchar val = node.solid->val; if(bmsize > BM_IMAGE_SIZE) { node.splitsolid(type, val); blitblendmap(type, node, bmx, bmy, bmsize, src, sx, sy, sw, sh); return; } type = BM_IMAGE; node.image = new BlendMapImage; memset(node.image->data, val, sizeof(node.image->data)); } int x1 = clamp(sx - bmx, 0, bmsize), y1 = clamp(sy - bmy, 0, bmsize), x2 = clamp(sx+sw - bmx, 0, bmsize), y2 = clamp(sy+sh - bmy, 0, bmsize); uchar *dst = &node.image->data[y1*BM_IMAGE_SIZE + x1]; src += max(bmy - sy, 0)*sw + max(bmx - sx, 0); loopi(y2-y1) { switch(blendpaintmode) { case 1: memcpy(dst, src, x2 - x1); break; case 2: loopi(x2 - x1) dst[i] = min(dst[i], src[i]); break; case 3: loopi(x2 - x1) dst[i] = max(dst[i], src[i]); break; case 4: loopi(x2 - x1) dst[i] = min(dst[i], uchar(0xFF - src[i])); break; case 5: loopi(x2 - x1) dst[i] = max(dst[i], uchar(0xFF - src[i])); break; } dst += BM_IMAGE_SIZE; src += sw; } } void blitblendmap(uchar *src, int sx, int sy, int sw, int sh) { int bmsize = worldsize>>BM_SCALE; if(max(sx, sy) >= bmsize || min(sx+sw, sy+sh) <= 0 || min(sw, sh) <= 0) return; blitblendmap(blendmap.type, blendmap, 0, 0, bmsize, src, sx, sy, sw, sh); } void resetblendmap() { blendmap.cleanup(); blendmap.type = BM_SOLID; blendmap.solid = &bmsolids[0xFF]; } void enlargeblendmap() { if(blendmap.type == BM_SOLID) return; BlendMapBranch *branch = new BlendMapBranch; branch->type[0] = blendmap.type; branch->children[0] = blendmap; loopi(3) { branch->type[i+1] = BM_SOLID; branch->children[i+1].solid = &bmsolids[0xFF]; } blendmap.type = BM_BRANCH; blendmap.branch = branch; } void shrinkblendmap(int octant) { blendmap.shrink(octant&3); } struct BlendBrush { char *name; int w, h; uchar *data; GLuint tex; BlendBrush(const char *name, int w, int h) : name(newstring(name)), w(w), h(h), data(new uchar[w*h]), tex(0) {} ~BlendBrush() { cleanup(); delete[] name; if(data) delete[] data; } void cleanup() { if(tex) { glDeleteTextures(1, &tex); tex = 0; } } void gentex() { if(!tex) glGenTextures(1, &tex); uchar *buf = new uchar[2*(w+2)*(h+2)]; memset(buf, 0, 2*(w+2)); uchar *dst = &buf[2*(w+2)], *src = data; loopi(h) { *dst++ = 0; *dst++ = 0; loopj(w) { *dst++ = 255 - *src; *dst++ = 255 - *src++; } *dst++ = 0; *dst++ = 0; } memset(dst, 0, 2*(w+2)); createtexture(tex, w+2, h+2, buf, 3, 1, GL_LUMINANCE_ALPHA); delete[] buf; } void reorient(bool flipx, bool flipy, bool swapxy) { uchar *rdata = new uchar[w*h]; int stridex = 1, stridey = 1; if(swapxy) stridex *= h; else stridey *= w; uchar *src = data, *dst = rdata; if(flipx) { dst += (w-1)*stridex; stridex = -stridex; } if(flipy) { dst += (h-1)*stridey; stridey = -stridey; } loopi(h) { uchar *curdst = dst; loopj(w) { *curdst = *src++; curdst += stridex; } dst += stridey; } if(swapxy) swap(w, h); delete[] data; data = rdata; if(tex) gentex(); } }; static vector brushes; static int curbrush = -1; void cleanupblendmap() { loopv(brushes) brushes[i]->cleanup(); } void clearblendbrushes() { while(brushes.length()) delete brushes.pop(); curbrush = -1; } void delblendbrush(const char *name) { loopv(brushes) if(!strcmp(brushes[i]->name, name)) { delete brushes[i]; brushes.remove(i--); } curbrush = brushes.empty() ? -1 : clamp(curbrush, 0, brushes.length()-1); } void addblendbrush(const char *name, const char *imgname) { delblendbrush(name); ImageData s; if(!loadimage(imgname, s)) { conoutf(CON_ERROR, "could not load blend brush image %s", imgname); return; } if(max(s.w, s.h) > (1<<12)) { conoutf(CON_ERROR, "blend brush image size exceeded %dx%d pixels: %s", 1<<12, 1<<12, imgname); return; } BlendBrush *brush = new BlendBrush(name, s.w, s.h); uchar *dst = brush->data, *srcrow = s.data; loopi(s.h) { for(uchar *src = srcrow, *end = &srcrow[s.w*s.bpp]; src < end; src += s.bpp) *dst++ = src[0]; srcrow += s.pitch; } brushes.add(brush); if(curbrush < 0) curbrush = 0; else if(curbrush >= brushes.length()) curbrush = brushes.length()-1; } void nextblendbrush(int *dir) { curbrush += *dir < 0 ? -1 : 1; if(brushes.empty()) curbrush = -1; else if(!brushes.inrange(curbrush)) curbrush = *dir < 0 ? brushes.length()-1 : 0; } void setblendbrush(const char *name) { loopv(brushes) if(!strcmp(brushes[i]->name, name)) { curbrush = i; break; } } void getblendbrushname(int *n) { result(brushes.inrange(*n) ? brushes[*n]->name : ""); } void curblendbrush() { intret(curbrush); } COMMAND(clearblendbrushes, ""); COMMAND(delblendbrush, "s"); COMMAND(addblendbrush, "ss"); COMMAND(nextblendbrush, "i"); COMMAND(setblendbrush, "s"); COMMAND(getblendbrushname, "i"); COMMAND(curblendbrush, ""); extern int nompedit; bool canpaintblendmap(bool brush = true, bool sel = false, bool msg = true) { if(noedit(!sel, msg) || (nompedit && multiplayer())) return false; if(!blendpaintmode) { if(msg) conoutf(CON_ERROR, "operation only allowed in blend paint mode"); return false; } if(brush && !brushes.inrange(curbrush)) { if(msg) conoutf(CON_ERROR, "no blend brush selected"); return false; } return true; } void rotateblendbrush(int *val) { if(!canpaintblendmap()) return; int numrots = *val < 0 ? 3 : clamp(*val, 1, 5); BlendBrush *brush = brushes[curbrush]; brush->reorient(numrots>=2 && numrots<=4, numrots<=2 || numrots==5, (numrots&5)==1); } COMMAND(rotateblendbrush, "i"); void paintblendmap(bool msg) { if(!canpaintblendmap(true, false, msg)) return; BlendBrush *brush = brushes[curbrush]; int x = (int)floor(clamp(worldpos.x, 0.0f, float(worldsize))/(1<w), y = (int)floor(clamp(worldpos.y, 0.0f, float(worldsize))/(1<h); blitblendmap(brush->data, x, y, brush->w, brush->h); previewblends(ivec((x-1)<w+2)<h+2)<>BM_SCALE, y1 = sel.o.y>>BM_SCALE, x2 = (sel.o.x+sel.s.x*sel.grid+(1<>BM_SCALE, y2 = (sel.o.y+sel.s.y*sel.grid+(1<>BM_SCALE; fillblendmap(x1, y1, x2-x1, y2-y1, 0xFF); previewblends(ivec(x1<>BM_SCALE, y1 = sel.o.y>>BM_SCALE, x2 = (sel.o.x+sel.s.x*sel.grid+(1<>BM_SCALE, y2 = (sel.o.y+sel.s.y*sel.grid+(1<>BM_SCALE; invertblendmap(x1, y1, x2-x1, y2-y1); previewblends(ivec(x1<>BM_SCALE, worldsize>>BM_SCALE); previewblends(ivec(0, 0, 0), ivec(worldsize, worldsize, worldsize)); } COMMAND(invertblendmap, ""); void showblendmap() { if(noedit(true) || (nompedit && multiplayer())) return; previewblends(ivec(0, 0, 0), ivec(worldsize, worldsize, worldsize)); } COMMAND(showblendmap, ""); COMMAND(optimizeblendmap, ""); ICOMMAND(clearblendmap, "", (), { if(noedit(true) || (nompedit && multiplayer())) return; resetblendmap(); showblendmap(); }); void renderblendbrush() { if(!blendpaintmode || !brushes.inrange(curbrush)) return; BlendBrush *brush = brushes[curbrush]; int x1 = (int)floor(clamp(worldpos.x, 0.0f, float(worldsize))/(1<w+2)) << BM_SCALE, y1 = (int)floor(clamp(worldpos.y, 0.0f, float(worldsize))/(1<h+2)) << BM_SCALE, x2 = x1 + ((brush->w+2) << BM_SCALE), y2 = y1 + ((brush->h+2) << BM_SCALE); if(max(x1, y1) >= worldsize || min(x2, y2) <= 0 || x1>=x2 || y1>=y2) return; if(!brush->tex) brush->gentex(); renderblendbrush(brush->tex, x1, y1, x2 - x1, y2 - y1); } bool loadblendmap(stream *f, uchar &type, BlendMapNode &node) { type = f->getchar(); switch(type) { case BM_SOLID: { int val = f->getchar(); if(val<0 || val>0xFF) return false; node.solid = &bmsolids[val]; break; } case BM_IMAGE: node.image = new BlendMapImage; if(f->read(node.image->data, sizeof(node.image->data)) != sizeof(node.image->data)) return false; break; case BM_BRANCH: node.branch = new BlendMapBranch; loopi(4) { node.branch->type[i] = BM_SOLID; node.branch->children[i].solid = &bmsolids[0xFF]; } loopi(4) if(!loadblendmap(f, node.branch->type[i], node.branch->children[i])) return false; break; default: type = BM_SOLID; node.solid = &bmsolids[0xFF]; return false; } return true; } bool loadblendmap(stream *f, int info) { resetblendmap(); return loadblendmap(f, blendmap.type, blendmap); } void saveblendmap(stream *f, uchar type, BlendMapNode &node) { f->putchar(type); switch(type) { case BM_SOLID: f->putchar(node.solid->val); break; case BM_IMAGE: f->write(node.image->data, sizeof(node.image->data)); break; case BM_BRANCH: loopi(4) saveblendmap(f, node.branch->type[i], node.branch->children[i]); break; } } void saveblendmap(stream *f) { saveblendmap(f, blendmap.type, blendmap); } uchar shouldsaveblendmap() { return blendmap.solid!=&bmsolids[0xFF] ? 1 : 0; } sandboxgamemaker-2.7.1+dfsg/src/engine/depthfx.h0000664000175000017500000001525411615526106021533 0ustar showardshoward// eye space depth texture for soft particles, done at low res then blurred to prevent ugly jaggies VARP(depthfxfpscale, 1, 1<<12, 1<<16); VARP(depthfxscale, 1, 1<<6, 1<<8); VARP(depthfxblend, 1, 16, 64); VARP(depthfxpartblend, 1, 8, 64); VAR(depthfxmargin, 0, 16, 64); VAR(depthfxbias, 0, 1, 64); extern void cleanupdepthfx(); VARFP(fpdepthfx, 0, 0, 1, cleanupdepthfx()); VARP(depthfxemuprecision, 0, 1, 1); VARFP(depthfxsize, 6, 7, 12, cleanupdepthfx()); VARP(depthfx, 0, 1, 1); VARP(depthfxparts, 0, 1, 1); VARFP(depthfxrect, 0, 0, 1, cleanupdepthfx()); VARFP(depthfxfilter, 0, 1, 1, cleanupdepthfx()); VARP(blurdepthfx, 0, 1, 7); VARP(blurdepthfxsigma, 1, 50, 200); VAR(depthfxscissor, 0, 2, 2); VAR(debugdepthfx, 0, 0, 1); #define MAXDFXRANGES 4 void *depthfxowners[MAXDFXRANGES]; float depthfxranges[MAXDFXRANGES]; int numdepthfxranges = 0; vec depthfxmin(1e16f, 1e16f, 1e16f), depthfxmax(1e16f, 1e16f, 1e16f); static struct depthfxtexture : rendertarget { const GLenum *colorformats() const { static const GLenum colorfmts[] = { GL_FLOAT_RG16_NV, GL_RGB16F_ARB, GL_RGBA, GL_RGBA8, GL_RGB, GL_RGB8, GL_FALSE }; return &colorfmts[hasTF && hasFBO && fpdepthfx ? (hasNVFB && texrect() && !filter() ? 0 : 1) : 2]; } float eyedepth(const vec &p) const { return max(-mvmatrix.transformz(p), 0.0f); } void addscissorvert(const vec &v, float &sx1, float &sy1, float &sx2, float &sy2) { float w = mvpmatrix.transformw(v), x = mvpmatrix.transformx(v) / w, y = mvpmatrix.transformy(v) / w; sx1 = min(sx1, x); sy1 = min(sy1, y); sx2 = max(sx2, x); sy2 = max(sy2, y); } bool addscissorbox(const vec ¢er, float size) { float sx1, sy1, sx2, sy2; calcspherescissor(center, size, sx1, sy1, sx2, sy2); return addblurtiles(sx1, sy1, sx2, sy2); } bool addscissorbox(const vec &bbmin, const vec &bbmax) { float sx1 = 1, sy1 = 1, sx2 = -1, sy2 = -1; loopi(8) { vec v(i&1 ? bbmax.x : bbmin.x, i&2 ? bbmax.y : bbmin.y, i&4 ? bbmax.z : bbmin.z); addscissorvert(v, sx1, sy1, sx2, sy2); } return addblurtiles(sx1, sy1, sx2, sy2); } bool screenview() const { return depthfxrect!=0; } bool texrect() const { return depthfxrect && hasTR; } bool filter() const { return depthfxfilter!=0; } bool highprecision() const { return colorfmt==GL_FLOAT_RG16_NV || colorfmt==GL_RGB16F_ARB; } bool emulatehighprecision() const { return depthfxemuprecision && !depthfxfilter; } bool shouldrender() { extern void finddepthfxranges(); finddepthfxranges(); return (numdepthfxranges && scissorx1 < scissorx2 && scissory1 < scissory2) || debugdepthfx; } bool dorender() { glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); depthfxing = true; refracting = -1; extern void renderdepthobstacles(const vec &bbmin, const vec &bbmax, float scale, float *ranges, int numranges); float scale = depthfxscale; float *ranges = depthfxranges; int numranges = numdepthfxranges; if(highprecision()) { scale = depthfxfpscale; ranges = NULL; numranges = 0; } else if(emulatehighprecision()) { scale = depthfxfpscale; ranges = NULL; numranges = -3; } renderdepthobstacles(depthfxmin, depthfxmax, scale, ranges, numranges); refracting = 0; depthfxing = false; return numdepthfxranges > 0; } void dodebug(int w, int h) { if(numdepthfxranges > 0) { glColor3f(0, 1, 0); debugscissor(w, h, true); glColor3f(0, 0, 1); debugblurtiles(w, h, true); glColor3f(1, 1, 1); } } } depthfxtex; void cleanupdepthfx() { depthfxtex.cleanup(true); } void viewdepthfxtex() { if(!depthfx) return; depthfxtex.debug(); } bool depthfxing = false; bool binddepthfxtex() { if(renderpath!=R_FIXEDFUNCTION && !reflecting && !refracting && depthfx && depthfxtex.rendertex && numdepthfxranges>0) { glActiveTexture_(GL_TEXTURE2_ARB); glBindTexture(depthfxtex.target, depthfxtex.rendertex); glActiveTexture_(GL_TEXTURE0_ARB); if(depthfxtex.target==GL_TEXTURE_RECTANGLE_ARB) setenvparamf("depthfxview", SHPARAM_VERTEX, 6, 0.5f*depthfxtex.vieww, 0.5f*depthfxtex.viewh); else setenvparamf("depthfxview", SHPARAM_VERTEX, 6, 0.5f*float(depthfxtex.vieww)/depthfxtex.texw, 0.5f*float(depthfxtex.viewh)/depthfxtex.texh); return true; } return false; } void binddepthfxparams(float blend, float minblend = 0, bool allow = true, void *owner = NULL) { if(renderpath!=R_FIXEDFUNCTION && !reflecting && !refracting && depthfx && depthfxtex.rendertex && numdepthfxranges>0) { float scale = 0, offset = -1, texscale = 0; if(!depthfxtex.highprecision()) { float select[4] = { 0, 0, 0, 0 }; if(!depthfxtex.emulatehighprecision()) { loopi(numdepthfxranges) if(depthfxowners[i]==owner) { select[i] = float(depthfxscale)/blend; scale = 1.0f/blend; offset = -float(depthfxranges[i] - depthfxbias)/blend; break; } } else if(allow) { select[0] = float(depthfxfpscale)/blend; select[1] = select[0]/256; select[2] = select[1]/256; scale = 1.0f/blend; offset = 0; } setlocalparamfv("depthfxselect", SHPARAM_PIXEL, 6, select); } else if(allow) { scale = 1.0f/blend; offset = 0; texscale = float(depthfxfpscale)/blend; } setlocalparamf("depthfxparams", SHPARAM_VERTEX, 5, scale, offset, texscale, minblend); setlocalparamf("depthfxparams", SHPARAM_PIXEL, 5, scale, offset, texscale, minblend); } } void drawdepthfxtex() { if(!depthfx || renderpath==R_FIXEDFUNCTION) return; // Apple/ATI bug - fixed-function fog state can force software fallback even when fragment program is enabled glDisable(GL_FOG); depthfxtex.render(1< texmru; extern int xtraverts, xtravertsva; extern const ivec cubecoords[8]; extern const ivec facecoords[6][4]; extern const uchar fv[6][4]; extern const uchar fvmasks[64]; extern const uchar faceedgesidx[6][4]; extern bool inbetweenframes, renderedframe; extern SDL_Surface *screen; extern int zpass, glowpass; extern vector entgroup; // rendertext struct font { struct charinfo { short x, y, w, h, offsetx, offsety, advance, tex; }; char *name; vector texs; vector chars; int charoffset, defaultw, defaulth; }; #define FONTH (curfont->defaulth) #define FONTW (curfont->defaultw) #define MINRESW 640 #define MINRESH 480 extern font *curfont; // texture extern int hwtexsize, hwcubetexsize, hwmaxaniso, maxtexsize; extern int texalign(void *data, int w, int bpp); extern void cleanuptexture(Texture *t); extern void loadalphamask(Texture *t); extern void loadlayermasks(); extern Texture *cubemapload(const char *name, bool mipit = true, bool msg = true, bool transient = false); extern void drawcubemap(int size, const vec &o, float yaw, float pitch, const cubemapside &side); extern void loadshaders(); extern void setuptexparameters(int tnum, void *pixels, int clamp, int filter, GLenum format = GL_RGB, GLenum target = GL_TEXTURE_2D); extern void createtexture(int tnum, int w, int h, void *pixels, int clamp, int filter, GLenum component = GL_RGB, GLenum target = GL_TEXTURE_2D, int pw = 0, int ph = 0, int pitch = 0, bool resize = true, GLenum format = GL_FALSE); extern void blurtexture(int n, int bpp, int w, int h, uchar *dst, const uchar *src); extern void renderpostfx(); extern void initenvmaps(); extern void genenvmaps(); extern ushort closestenvmap(const vec &o); extern ushort closestenvmap(int orient, int x, int y, int z, int size); extern GLuint lookupenvmap(ushort emid); extern GLuint lookupenvmap(Slot &slot); extern bool reloadtexture(Texture &tex); extern bool reloadtexture(const char *name); extern void setuptexcompress(); extern void clearslots(); extern void compacteditvslots(); extern void compactmruvslots(); extern void compactvslots(cube *c, int n = 8); extern void compactvslot(int &index); extern int compactvslots(); extern const char *textypename(int i); extern void cleartexanims(bool clear = true); extern void reconftexanims(); // shadowmap extern int shadowmap, shadowmapcasters; extern bool shadowmapping; extern bool isshadowmapcaster(const vec &o, float rad); extern bool addshadowmapcaster(const vec &o, float xyrad, float zrad); extern bool isshadowmapreceiver(vtxarray *va); extern void rendershadowmap(); extern void pushshadowmap(); extern void popshadowmap(); extern void rendershadowmapreceivers(); extern void guessshadowdir(); // pvs extern void clearpvs(); extern bool pvsoccluded(const ivec &bborigin, const ivec &bbsize); extern bool waterpvsoccluded(int height); extern void setviewcell(const vec &p); extern void savepvs(stream *f); extern void loadpvs(stream *f, int numpvs); extern int getnumviewcells(); static inline bool pvsoccluded(const ivec &bborigin, int size) { return pvsoccluded(bborigin, ivec(size, size, size)); } // rendergl extern bool hasVBO, hasDRE, hasOQ, hasTR, hasFBO, hasDS, hasTF, hasBE, hasBC, hasCM, hasNP2, hasTC, hasTE, hasMT, hasD3, hasAF, hasVP2, hasVP3, hasPP, hasMDA, hasTE3, hasTE4, hasVP, hasFP, hasGLSL, hasGM, hasNVFB, hasSGIDT, hasSGISH, hasDT, hasSH, hasNVPCF, hasRN, hasPBO, hasFBB, hasUBO, hasBUE, hasFC, hasTEX; extern int hasstencil; extern bool envmapping, minimapping, renderedgame; extern const glmatrixf viewmatrix; extern glmatrixf mvmatrix, projmatrix, mvpmatrix, invmvmatrix, invmvpmatrix, fogmatrix, invfogmatrix, envmatrix; extern bvec fogcolor; extern void gl_checkextensions(); extern void gl_init(int w, int h, int bpp, int depth, int fsaa); extern void cleangl(); extern void rendergame(bool mainpass = false); extern void invalidatepostfx(); extern void gl_drawframe(int w, int h); extern void gl_drawmainmenu(int w, int h); extern void drawminimap(); extern void enablepolygonoffset(GLenum type); extern void disablepolygonoffset(GLenum type); extern void calcspherescissor(const vec ¢er, float size, float &sx1, float &sy1, float &sx2, float &sy2); extern int pushscissor(float sx1, float sy1, float sx2, float sy2); extern void popscissor(); extern void recomputecamera(); extern void findorientation(); extern void writecrosshairs(stream *f); // renderextras extern void render3dbox(vec &o, float tofloor, float toceil, float xradius, float yradius = 0); // octa extern cube *newcubes(uint face = F_EMPTY, int mat = MAT_AIR); extern cubeext *growcubeext(cubeext *ext, int maxverts); extern void setcubeext(cube &c, cubeext *ext); extern cubeext *newcubeext(cube &c, int maxverts = 0, bool init = true); extern void getcubevector(cube &c, int d, int x, int y, int z, ivec &p); extern void setcubevector(cube &c, int d, int x, int y, int z, const ivec &p); extern int familysize(cube &c); extern void freeocta(cube *c); extern void discardchildren(cube &c, bool fixtex = false, int depth = 0); extern void optiface(uchar *p, cube &c); extern void validatec(cube *c, int size = 0); extern bool isvalidcube(cube &c); extern ivec lu; extern int lusize; extern cube &lookupcube(int tx, int ty, int tz, int tsize = 0, ivec &ro = lu, int &rsize = lusize); extern cube *neighbourstack[32]; extern int neighbourdepth; extern cube &neighbourcube(cube &c, int orient, int x, int y, int z, int size, ivec &ro = lu, int &rsize = lusize); extern void resetclipplanes(); extern int getmippedtexture(cube &p, int orient); extern void forcemip(cube &c, bool fixtex = true); extern bool subdividecube(cube &c, bool fullcheck=true, bool brighten=true); extern void converttovectorworld(); extern int faceconvexity(ivec v[4]); extern int faceconvexity(ivec v[4], int &vis); extern int faceconvexity(vertinfo *verts, int numverts); extern int faceconvexity(cube &c, int orient); extern void calcvert(cube &c, int x, int y, int z, int size, ivec &vert, int i, bool solid = false); extern void calcvert(cube &c, int x, int y, int z, int size, vec &vert, int i, bool solid = false); extern uint faceedges(cube &c, int orient); extern bool collapsedface(cube &c, int orient); extern bool touchingface(cube &c, int orient); extern bool flataxisface(cube &c, int orient); extern bool collideface(cube &c, int orient); extern int genclipplane(cube &c, int i, vec *v, plane *clip); extern void genclipplanes(cube &c, int x, int y, int z, int size, clipplanes &p); extern bool visibleface(cube &c, int orient, int x, int y, int z, int size, uchar mat = MAT_AIR, uchar nmat = MAT_AIR, uchar matmask = MATF_VOLUME); extern int visibletris(cube &c, int orient, int x, int y, int z, int size, uchar nmat = MAT_AIR, uchar matmask = MAT_AIR); extern int visibleorient(cube &c, int orient); extern bool threeplaneintersect(plane &pl1, plane &pl2, plane &pl3, vec &dest); extern void genfaceverts(cube &c, int orient, ivec v[4]); extern int calcmergedsize(int orient, const ivec &co, int size, const vertinfo *verts, int numverts); extern void invalidatemerges(cube &c, const ivec &co, int size, bool msg); extern void calcmerges(); extern int mergefaces(int orient, facebounds *m, int sz); extern void mincubeface(cube &cu, int orient, const ivec &o, int size, const facebounds &orig, facebounds &cf, uchar nmat = MAT_AIR, uchar matmask = MATF_VOLUME); static inline uchar octantrectangleoverlap(const ivec &c, int size, const ivec &o, const ivec &s) { uchar p = 0xFF; // bitmask of possible collisions with octants. 0 bit = 0 octant, etc ivec v(c); v.add(size); if(v.z <= o.z) p &= 0xF0; // not in a -ve Z octant if(v.z >= o.z+s.z) p &= 0x0F; // not in a +ve Z octant if(v.y <= o.y) p &= 0xCC; // not in a -ve Y octant if(v.y >= o.y+s.y) p &= 0x33; // etc.. if(v.x <= o.x) p &= 0xAA; if(v.x >= o.x+s.x) p &= 0x55; return p; } static inline cubeext &ext(cube &c) { return *(c.ext ? c.ext : newcubeext(c)); } // ents extern char *entname(entity &e); extern bool haveselent(); extern undoblock *copyundoents(undoblock *u); extern void pasteundoents(undoblock *u); // octaedit extern void cancelsel(); extern void rendertexturepanel(int w, int h); extern void addundo(undoblock *u); extern void commitchanges(bool force = false); extern void rendereditcursor(); extern void tryedit(); // octarender extern vector tjoints; extern ushort encodenormal(const vec &n); extern vec decodenormal(ushort norm); extern void reduceslope(ivec &n); extern void findtjoints(); extern void octarender(); extern void allchanged(bool load = false); extern void clearvas(cube *c); extern vtxarray *newva(int x, int y, int z, int size); extern void destroyva(vtxarray *va, bool reparent = true); extern bool readva(vtxarray *va, ushort *&edata, uchar *&vdata); extern void updatevabb(vtxarray *va, bool force = false); extern void updatevabbs(bool force = false); // renderva extern void visiblecubes(bool cull = true); extern void setvfcP(float z = -1, const vec &bbmin = vec(-1, -1, -1), const vec &bbmax = vec(1, 1, 1)); extern void savevfcP(); extern void restorevfcP(); extern void rendergeom(float causticspass = 0, bool fogpass = false); extern void renderalphageom(bool fogpass = false); extern void rendermapmodels(); extern void renderreflectedgeom(bool causticspass = false, bool fogpass = false); extern void renderreflectedmapmodels(); extern void renderoutline(); extern bool rendersky(bool explicitonly = false); extern bool isfoggedsphere(float rad, const vec &cv); extern int isvisiblesphere(float rad, const vec &cv); extern bool bboccluded(const ivec &bo, const ivec &br); extern occludequery *newquery(void *owner); extern bool checkquery(occludequery *query, bool nowait = false); extern void resetqueries(); extern int getnumqueries(); extern void drawbb(const ivec &bo, const ivec &br, const vec &camera = camera1->o); #define startquery(query) { glBeginQuery_(GL_SAMPLES_PASSED_ARB, ((occludequery *)(query))->id); } #define endquery(query) \ { \ glEndQuery_(GL_SAMPLES_PASSED_ARB); \ extern int ati_oq_bug; \ if(ati_oq_bug) glFlush(); \ } // dynlight extern void updatedynlights(); extern int finddynlights(); extern void calcdynlightmask(vtxarray *va); extern int setdynlights(vtxarray *va); extern bool getdynlight(int n, vec &o, float &radius, vec &color); // material extern int showmat; extern int findmaterial(const char *name); extern void genmatsurfs(cube &c, int cx, int cy, int cz, int size, vector &matsurfs); extern void rendermatsurfs(materialsurface *matbuf, int matsurfs); extern void rendermatgrid(materialsurface *matbuf, int matsurfs); extern int optimizematsurfs(materialsurface *matbuf, int matsurfs); extern void setupmaterials(int start = 0, int len = 0); extern void rendermaterials(); extern void drawmaterial(int orient, int x, int y, int z, int csize, int rsize, float offset); extern int visiblematerial(cube &c, int orient, int x, int y, int z, int size, uchar matmask = MATF_VOLUME); // water extern int refracting; extern bool reflecting, fading, fogging; extern float reflectz; extern int reflectdist, vertwater, waterrefract, waterreflect, waterfade, caustics, waterfallrefract, waterfog, lavafog; extern bvec watercolor, waterfallcolor, lavacolor; extern void cleanreflections(); extern void queryreflections(); extern void drawreflections(); extern void renderwater(); extern void renderlava(const materialsurface &m, Texture *tex, float scale); extern void loadcaustics(bool force = false); extern void preloadwatershaders(bool force = false); // glare extern bool glaring; extern void drawglaretex(); extern void addglare(); // depthfx extern bool depthfxing; extern void drawdepthfxtex(); // server extern vector gameargs; extern void initserver(bool listen, bool dedicated); extern void cleanupserver(); extern void serverslice(bool dedicated, uint timeout); extern ENetSocket connectmaster(); extern void localclienttoserver(int chan, ENetPacket *); extern void localconnect(); extern bool serveroption(char *opt); // serverbrowser extern bool resolverwait(const char *name, ENetAddress *address); extern int connectwithtimeout(ENetSocket sock, const char *hostname, const ENetAddress &address); extern void addserver(const char *name, int port = 0, const char *password = NULL, bool keep = false); extern void writeservercfg(); // client extern void localservertoclient(int chan, ENetPacket *packet); extern void connectserv(const char *servername, int port, const char *serverpassword); extern void abortconnect(); extern void clientkeepalive(); // command extern hashset idents; extern int identflags; extern void explodelist(const char *s, vector &elems); extern char *indexlist(const char *s, int pos); extern void clearoverrides(); extern void writecfg(const char *name = NULL); extern void checksleep(int millis); extern void clearsleep(bool clearoverrides = true); // console extern void keypress(int code, bool isdown, int cooked); extern int rendercommand(int x, int y, int w); extern int renderconsole(int w, int h, int abovehud); extern void conoutf(const char *s, ...); extern void conoutf(int type, const char *s, ...); extern void resetcomplete(); extern void complete(char *s); const char *getkeyname(int code); extern const char *addreleaseaction(char *s); extern void writebinds(stream *f); extern void writecompletions(stream *f); // main extern string imagelogo; enum { NOT_INITING = 0, INIT_LOAD, INIT_RESET }; extern int initing; enum { CHANGE_GFX = 1<<0, CHANGE_SOUND = 1<<1 }; extern bool initwarning(const char *desc, int level = INIT_RESET, int type = CHANGE_GFX); extern void pushevent(const SDL_Event &e); extern bool interceptkey(int sym); extern float loadprogress; extern void renderbackground(const char *caption = NULL, Texture *mapshot = NULL, const char *mapname = NULL, const char *mapinfo = NULL, bool restore = false, bool force = false); extern void renderprogress(float bar, const char *text, GLuint tex = 0, bool background = false); extern void getfps(int &fps, int &bestdiff, int &worstdiff); extern void swapbuffers(); extern int getclockmillis(); // menu #ifndef NEWGUI extern void menuprocess(); #endif extern void addchange(const char *desc, int type); extern void clearchanges(int type); // physics extern void mousemove(int dx, int dy); extern bool pointincube(const clipplanes &p, const vec &v); extern bool overlapsdynent(const vec &o, float radius); extern void rotatebb(vec ¢er, vec &radius, int yaw); extern float shadowray(const vec &o, const vec &ray, float radius, int mode, extentity *t = NULL); struct ShadowRayCache; extern ShadowRayCache *newshadowraycache(); extern void freeshadowraycache(ShadowRayCache *&cache); extern void resetshadowraycache(ShadowRayCache *cache); extern float shadowray(ShadowRayCache *cache, const vec &o, const vec &ray, float radius, int mode, extentity *t = NULL); // world extern vector outsideents; extern void entcancel(); extern void entitiesinoctanodes(); extern void attachentities(); extern void freeoctaentities(cube &c); extern bool pointinsel(selinfo &sel, vec &o); extern const int getattrnum(int type); extern void resetmap(); extern void startmap(const char *name); // rendermodel struct mapmodelinfo { string name; model *m; }; extern void findanims(const char *pattern, vector &anims); extern void loadskin(const char *dir, const char *altdir, Texture *&skin, Texture *&masks); extern mapmodelinfo &getmminfo(int i); extern void startmodelquery(occludequery *query); extern void endmodelquery(); extern void preloadmodelshaders(); extern void preloadusedmapmodels(bool msg = false, bool bih = false); // renderparticles extern void particleinit(); extern void clearparticles(); extern void clearparticleemitters(); extern void seedparticles(); extern void updateparticles(); extern void renderparticles(bool mainpass = false); extern bool printparticles(extentity &e, char *buf); // decal extern void initdecals(); extern void cleardecals(); extern void renderdecals(bool mainpass = false); // blob enum { BLOB_STATIC = 0, BLOB_DYNAMIC }; extern int showblobs; extern void initblobs(int type = -1); extern void resetblobs(); extern void renderblob(int type, const vec &o, float radius, float fade = 1); extern void flushblobs(); // rendersky extern int explicitsky; extern double skyarea; extern void drawskybox(int farplane, bool limited); extern bool limitsky(); // 3dgui #ifndef NEWGUI extern int mainmenu; extern void clearmainmenu(); extern void g3d_render(); extern bool g3d_windowhit(bool on, bool act); // menus extern void g3d_mainmenu(); #else //new UI by neal namespace UI { extern void resetcursor(); extern bool movecursor(int &dx, int &dy); extern bool hascursor(); extern void getcursorpos(float &x, float &y); extern bool keypress(int code, bool isdown, int cooked); extern void setup(); extern void update(); extern void render(); extern void clearmainmenu(); extern int mainmenu; } #endif // sound extern void writemapsounds(stream *f); extern void clearmapsounds(); extern void checkmapsounds(); extern void updatesounds(); extern void initmumble(); extern void closemumble(); extern void updatemumble(); // grass extern void generategrass(); extern void rendergrass(); // blendmap extern int blendpaintmode; struct BlendMapCache; extern BlendMapCache *newblendmapcache(); extern void freeblendmapcache(BlendMapCache *&cache); extern bool setblendmaporigin(BlendMapCache *cache, const ivec &o, int size); extern bool hasblendmap(BlendMapCache *cache); extern uchar lookupblendmap(BlendMapCache *cache, const vec &pos); extern void resetblendmap(); extern void enlargeblendmap(); extern void shrinkblendmap(int octant); extern void optimizeblendmap(); extern void stoppaintblendmap(); extern void trypaintblendmap(); extern void renderblendbrush(GLuint tex, float x, float y, float w, float h); extern void renderblendbrush(); extern bool loadblendmap(stream *f, int info); extern void saveblendmap(stream *f); extern uchar shouldsaveblendmap(); // recorder namespace recorder { extern void stop(); extern void capture(); extern void cleanup(); } #endif #endif sandboxgamemaker-2.7.1+dfsg/src/engine/dynlight.cpp0000664000175000017500000001626311544613352022250 0ustar showardshoward#include "engine.h" VARP(ffdynlights, 0, min(5, DYNLIGHTMASK), DYNLIGHTMASK); VARP(maxdynlights, 0, min(3, MAXDYNLIGHTS), MAXDYNLIGHTS); VARP(dynlightdist, 0, 1024, 10000); struct dynlight { vec o, hud; float radius, initradius, curradius, dist; vec color, initcolor, curcolor; int fade, peak, expire, flags; physent *owner; void calcradius() { if(fade + peak > 0) { int remaining = expire - lastmillis; if(flags&DL_EXPAND) curradius = initradius + (radius - initradius) * (1.0f - remaining/float(fade + peak)); else if(!(flags&DL_FLASH) && remaining > fade) curradius = initradius + (radius - initradius) * (1.0f - float(remaining - fade)/peak); else if(flags&DL_SHRINK) curradius = (radius*remaining)/fade; else curradius = radius; } else curradius = radius; } void calccolor() { if(flags&DL_FLASH || peak <= 0) curcolor = color; else { int peaking = expire - lastmillis - fade; if(peaking <= 0) curcolor = color; else curcolor.lerp(initcolor, color, 1.0f - float(peaking)/peak); } float intensity = 1.0f; if(fade > 0) { int fading = expire - lastmillis; if(fading < fade) intensity = float(fading)/fade; } curcolor.mul(intensity); // KLUGE: this prevents nvidia drivers from trying to recompile dynlight fragment programs loopk(3) if(fmod(curcolor[k], 1.0f/256) < 0.001f) curcolor[k] += 0.001f; } }; vector dynlights; vector closedynlights; void adddynlight(const vec &o, float radius, const vec &color, int fade, int peak, int flags, float initradius, const vec &initcolor, physent *owner) { if(renderpath==R_FIXEDFUNCTION ? !ffdynlights || maxtmus<3 : !maxdynlights) return; if(o.dist(camera1->o) > dynlightdist || radius <= 0) return; int insert = 0, expire = fade + peak + lastmillis; loopvrev(dynlights) if(expire>=dynlights[i].expire) { insert = i+1; break; } dynlight d; d.o = d.hud = o; d.radius = radius; d.initradius = initradius; d.color = color; d.initcolor = initcolor; d.fade = fade; d.peak = peak; d.expire = expire; d.flags = flags; d.owner = owner; dynlights.insert(insert, d); } void cleardynlights() { int faded = -1; loopv(dynlights) if(lastmillis0) dynlights.remove(0, faded); } void removetrackeddynlights(physent *owner) { loopvrev(dynlights) if(owner ? dynlights[i].owner == owner : dynlights[i].owner != NULL) dynlights.remove(i); } void updatedynlights() { cleardynlights(); game::adddynlights(); loopv(dynlights) { dynlight &d = dynlights[i]; if(d.owner) game::dynlighttrack(d.owner, d.o, d.hud); d.calcradius(); d.calccolor(); } } int finddynlights() { closedynlights.setsize(0); if(renderpath==R_FIXEDFUNCTION ? !ffdynlights || maxtmus<3 : !maxdynlights) return 0; physent e; e.type = ENT_CAMERA; e.collidetype = COLLIDE_AABB; loopvj(dynlights) { dynlight &d = dynlights[j]; if(d.curradius <= 0) continue; d.dist = camera1->o.dist(d.o) - d.curradius; if(d.dist > dynlightdist || isfoggedsphere(d.curradius, d.o) || pvsoccluded(d.o, 2*int(d.curradius+1))) continue; if(reflecting || refracting > 0) { if(d.o.z + d.curradius < reflectz) continue; } else if(refracting < 0 && d.o.z - d.curradius > reflectz) continue; e.o = d.o; e.radius = e.xradius = e.yradius = e.eyeheight = e.aboveeye = d.curradius; if(collide(&e, vec(0, 0, 0), 0, false)) continue; int insert = 0; loopvrev(closedynlights) if(d.dist >= closedynlights[i]->dist) { insert = i+1; break; } closedynlights.insert(insert, &d); if(closedynlights.length() >= DYNLIGHTMASK) break; } if(renderpath==R_FIXEDFUNCTION && closedynlights.length() > ffdynlights) closedynlights.setsize(ffdynlights); return closedynlights.length(); } bool getdynlight(int n, vec &o, float &radius, vec &color) { if(!closedynlights.inrange(n)) return false; dynlight &d = *closedynlights[n]; o = d.o; radius = d.curradius; color = d.curcolor; return true; } void dynlightreaching(const vec &target, vec &color, vec &dir, bool hud) { vec dyncolor(0, 0, 0);//, dyndir(0, 0, 0); loopv(dynlights) { dynlight &d = dynlights[i]; if(d.curradius<=0) continue; vec ray(hud ? d.hud : d.o); ray.sub(target); float mag = ray.squaredlen(); if(mag >= d.curradius*d.curradius) continue; vec color = d.curcolor; color.mul(1 - sqrtf(mag)/d.curradius); dyncolor.add(color); //dyndir.add(ray.mul(intensity/mag)); } #if 0 if(!dyndir.iszero()) { dyndir.normalize(); float x = dyncolor.magnitude(), y = color.magnitude(); if(x+y>0) { dir.mul(x); dyndir.mul(y); dir.add(dyndir).div(x+y); if(dir.iszero()) dir = vec(0, 0, 1); else dir.normalize(); } } #endif color.add(dyncolor); } void calcdynlightmask(vtxarray *va) { uint mask = 0; int offset = 0; loopv(closedynlights) { dynlight &d = *closedynlights[i]; if(d.o.dist_to_bb(va->geommin, va->geommax) >= d.curradius) continue; mask |= (i+1)<= maxdynlights*DYNLIGHTBITS) break; } va->dynlightmask = mask; } int setdynlights(vtxarray *va) { if(closedynlights.empty() || !va->dynlightmask) return 0; static string posparams[MAXDYNLIGHTS] = { "" }, colorparams[MAXDYNLIGHTS] = { "" }, offsetparams[MAXDYNLIGHTS] = { "" }; if(!*posparams[0]) loopi(MAXDYNLIGHTS) { formatstring(posparams[i])("dynlight%dpos", i); formatstring(colorparams[i])("dynlight%dcolor", i); formatstring(offsetparams[i])("dynlight%doffset", i); } int index = 0; float scale0 = 1; vec origin0(0, 0, 0); for(uint mask = va->dynlightmask; mask; mask >>= DYNLIGHTBITS, index++) { dynlight &d = *closedynlights[(mask&DYNLIGHTMASK)-1]; float scale = 1.0f/d.curradius; vec origin = vec(d.o).mul(-scale); setenvparamf(posparams[index], SHPARAM_VERTEX, 10+index, origin.x, origin.y, origin.z, scale); if(index<=0) { scale0 = scale; origin0 = origin; } else { scale /= scale0; origin.sub(vec(origin0).mul(scale)); setenvparamf(offsetparams[index], SHPARAM_PIXEL, index-1, origin.x, origin.y, origin.z, scale); } setenvparamf(colorparams[index], SHPARAM_PIXEL, 10+index, d.curcolor.x, d.curcolor.y, d.curcolor.z); } return index; } sandboxgamemaker-2.7.1+dfsg/src/engine/water.cpp0000664000175000017500000013165211642642476021560 0ustar showardshoward#include "engine.h" VARFP(waterreflect, 0, 1, 1, { cleanreflections(); preloadwatershaders(); }); VARFP(waterrefract, 0, 1, 1, { cleanreflections(); preloadwatershaders(); }); VARFP(waterenvmap, 0, 1, 1, { cleanreflections(); preloadwatershaders(); }); VARFP(waterfallrefract, 0, 0, 1, { cleanreflections(); preloadwatershaders(); }); /* vertex water */ VARP(watersubdiv, 0, 2, 3); VARP(waterlod, 0, 1, 3); static int wx1, wy1, wx2, wy2, wsize; static float whscale, whoffset; static uchar wcol[4]; #define VERTW(vertw, defbody, body) \ static inline void def##vertw() \ { \ varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); \ defbody; \ } \ static inline void vertw(float v1, float v2, float v3) \ { \ float angle = float((v1-wx1)*(v2-wy1))*float((v1-wx2)*(v2-wy2))*whscale+whoffset; \ float s = angle - int(angle) - 0.5f; \ s *= 8 - fabs(s)*16; \ float h = WATER_AMPLITUDE*s-WATER_OFFSET; \ varray::attrib(v1, v2, v3+h); \ body; \ } #define VERTWN(vertw, defbody, body) \ static inline void def##vertw() \ { \ varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); \ defbody; \ } \ static inline void vertw(float v1, float v2, float v3) \ { \ float h = -WATER_OFFSET; \ varray::attrib(v1, v2, v3+h); \ body; \ } #define VERTWT(vertwt, defbody, body) \ VERTW(vertwt, defbody, { \ float v = angle - int(angle+0.25) - 0.25; \ v *= 8 - fabs(v)*16; \ float duv = 0.5f*v; \ body; \ }) VERTW(vertwt, { varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); }, { varray::attrib(v1/8.0f, v2/8.0f); }) VERTWN(vertwtn, { varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); }, { varray::attrib(v1/8.0f, v2/8.0f); }) VERTW(vertwc, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); }, { varray::attrib(wcol[0], wcol[1], wcol[2], clamp(int(wcol[3] + fabs(s)*0x18), 0, 255)); }) VERTWN(vertwcn, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); }, { varray::attribv<4>(wcol); }) VERTWT(vertwtc, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); }, { varray::attrib(wcol[0], wcol[1], wcol[2], int(0x33 + fabs(s)*0x18)); varray::attrib(v1+duv, v2+duv, v3+h); }) VERTWN(vertwtcn, { glColor4ub(wcol[0], wcol[1], wcol[2], 0x33); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); }, { varray::attrib(v1, v2, v3+h); }) VERTWT(vertwmtc, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD1, 3, GL_FLOAT); }, { varray::attrib(wcol[0], wcol[1], wcol[2], int(0x33 + fabs(s)*0x18)); varray::attrib(v1-duv, v2+duv, v3+h); varray::attrib(v1+duv, v2+duv, v3+h); }) VERTWN(vertwmtcn, { glColor4ub(wcol[0], wcol[1], wcol[2], 0x33); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD1, 3, GL_FLOAT); }, { varray::attrib(v1, v2, v3+h); varray::attrib(v1, v2, v3+h); }) VERTWT(vertwetc, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); }, { varray::attrib(wcol[0], wcol[1], wcol[2], int(0x33 + fabs(s)*0x18)); varray::attrib(v1+duv-camera1->o.x, v2+duv-camera1->o.y, camera1->o.z-(v3+h)); }) VERTWN(vertwetcn, { glColor4ub(wcol[0], wcol[1], wcol[2], 0x33); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); }, { varray::attrib(v1-camera1->o.x, v2-camera1->o.y, camera1->o.z-(v3+h)); }) VERTWT(vertwemtc, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD1, 3, GL_FLOAT); }, { varray::attrib(wcol[0], wcol[1], wcol[2], int(0x33 + fabs(s)*0x18)); varray::attrib(v1-duv, v2+duv, v3+h); varray::attrib(v1+duv-camera1->o.x, v2+duv-camera1->o.y, camera1->o.z-(v3+h)); }) VERTWN(vertwemtcn, { glColor4ub(wcol[0], wcol[1], wcol[2], 0x33); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD1, 3, GL_FLOAT); }, { varray::attrib(v1, v2, v3+h); varray::attrib(v1-camera1->o.x, v2-camera1->o.y, camera1->o.z-(v3+h)); }) static float lavaxk = 1.0f, lavayk = 1.0f, lavascroll = 0.0f; VERTW(vertl, { varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); }, { varray::attrib(lavaxk*(v1+lavascroll), lavayk*(v2+lavascroll)); }) VERTWN(vertln, { varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); }, { varray::attrib(lavaxk*(v1+lavascroll), lavayk*(v2+lavascroll)); }) #define renderwaterstrips(vertw, z) { \ def##vertw(); \ for(int x = wx1; xo.z < z-WATER_OFFSET; if(nowater || minimapping) { renderwaterstrips(vertwc, z); } else if(waterrefract) { if(waterreflect && !below) { renderwaterstrips(vertwmtc, z); } else if(waterenvmap && hasCM && !below) { renderwaterstrips(vertwemtc, z); } else { renderwaterstrips(vertwtc, z); } } else if(waterreflect && !below) { renderwaterstrips(vertwtc, z); } else if(waterenvmap && hasCM && !below) { renderwaterstrips(vertwetc, z); } else { renderwaterstrips(vertwc, z); } } break; } case MAT_LAVA: { whoffset = fmod(float(lastmillis/2000.0f/(2*M_PI)), 1.0f); renderwaterstrips(vertl, z); break; } } } uint calcwatersubdiv(int x, int y, int z, uint size) { float dist; if(camera1->o.x >= x && camera1->o.x < x + size && camera1->o.y >= y && camera1->o.y < y + size) dist = fabs(camera1->o.z - float(z)); else { vec t(x + size/2, y + size/2, z + size/2); dist = t.dist(camera1->o) - size*1.42f/2; } uint subdiv = watersubdiv + int(dist) / (32 << waterlod); if(subdiv >= 8*sizeof(subdiv)) subdiv = ~0; else subdiv = 1 << subdiv; return subdiv; } uint renderwaterlod(int x, int y, int z, uint size, uchar mat) { if(size <= (uint)(32 << waterlod)) { uint subdiv = calcwatersubdiv(x, y, z, size); if(subdiv < size * 2) rendervertwater(min(subdiv, size), x, y, z, size, mat); return subdiv; } else { uint subdiv = calcwatersubdiv(x, y, z, size); if(subdiv >= size) { if(subdiv < size * 2) rendervertwater(size, x, y, z, size, mat); return subdiv; } uint childsize = size / 2, subdiv1 = renderwaterlod(x, y, z, childsize, mat), subdiv2 = renderwaterlod(x + childsize, y, z, childsize, mat), subdiv3 = renderwaterlod(x + childsize, y + childsize, z, childsize, mat), subdiv4 = renderwaterlod(x, y + childsize, z, childsize, mat), minsubdiv = subdiv1; minsubdiv = min(minsubdiv, subdiv2); minsubdiv = min(minsubdiv, subdiv3); minsubdiv = min(minsubdiv, subdiv4); if(minsubdiv < size * 2) { if(minsubdiv >= size) rendervertwater(size, x, y, z, size, mat); else { if(subdiv1 >= size) rendervertwater(childsize, x, y, z, childsize, mat); if(subdiv2 >= size) rendervertwater(childsize, x + childsize, y, z, childsize, mat); if(subdiv3 >= size) rendervertwater(childsize, x + childsize, y + childsize, z, childsize, mat); if(subdiv4 >= size) rendervertwater(childsize, x, y + childsize, z, childsize, mat); } } return minsubdiv; } } #define renderwaterquad(vertwn, z) \ { \ if(varray::data.empty()) { def##vertwn(); varray::begin(GL_QUADS); } \ vertwn(x, y, z); \ vertwn(x+rsize, y, z); \ vertwn(x+rsize, y+csize, z); \ vertwn(x, y+csize, z); \ xtraverts += 4; \ } void renderflatwater(int x, int y, int z, uint rsize, uint csize, uchar mat) { switch(mat) { case MAT_WATER: if(renderpath!=R_FIXEDFUNCTION) { renderwaterquad(vertwtn, z); } else { bool below = camera1->o.z < z-WATER_OFFSET; if(nowater || minimapping) { renderwaterquad(vertwcn, z); } else if(waterrefract) { if(waterreflect && !below) { renderwaterquad(vertwmtcn, z); } else if(waterenvmap && hasCM && !below) { renderwaterquad(vertwemtcn, z); } else { renderwaterquad(vertwtcn, z); } } else if(waterreflect && !below) { renderwaterquad(vertwtcn, z); } else if(waterenvmap && hasCM && !below) { renderwaterquad(vertwetcn, z); } else { renderwaterquad(vertwcn, z); } } break; case MAT_LAVA: renderwaterquad(vertln, z); break; } } VARFP(vertwater, 0, 1, 1, allchanged()); static inline void renderwater(const materialsurface &m, int mat = MAT_WATER) { if(!vertwater || minimapping) renderflatwater(m.o.x, m.o.y, m.o.z, m.rsize, m.csize, mat); else if(renderwaterlod(m.o.x, m.o.y, m.o.z, m.csize, mat) >= (uint)m.csize * 2) rendervertwater(m.csize, m.o.x, m.o.y, m.o.z, m.csize, mat); } void renderlava(const materialsurface &m, Texture *tex, float scale) { lavaxk = 8.0f/(tex->xs*scale); lavayk = 8.0f/(tex->ys*scale); lavascroll = lastmillis/1000.0f; renderwater(m, MAT_LAVA); } /* reflective/refractive water */ #define MAXREFLECTIONS 16 struct Reflection { GLuint tex, refracttex; int height, depth, lastupdate, lastused; glmatrixf projmat; occludequery *query, *prevquery; vector matsurfs; Reflection() : tex(0), refracttex(0), height(-1), depth(0), lastused(0), query(NULL), prevquery(NULL) {} }; Reflection *findreflection(int height); VARP(reflectdist, 0, 2000, 10000); bvec watercolor(0x14, 0x46, 0x50), waterfallcolor(0, 0, 0); HVARFR(watercolour, 0, 0x144650, 0xFFFFFF, { if(!watercolour) watercolour = 0x144650; watercolor = bvec((watercolour>>16)&0xFF, (watercolour>>8)&0xFF, watercolour&0xFF); }); VARR(waterfog, 0, 150, 10000); HVARFR(waterfallcolour, 0, 0, 0xFFFFFF, { waterfallcolor = bvec((waterfallcolour>>16)&0xFF, (waterfallcolour>>8)&0xFF, waterfallcolour&0xFF); }); bvec lavacolor(0xFF, 0x40, 0x00); HVARFR(lavacolour, 0, 0xFF4000, 0xFFFFFF, { if(!lavacolour) lavacolour = 0xFF4000; lavacolor = bvec((lavacolour>>16)&0xFF, (lavacolour>>8)&0xFF, lavacolour&0xFF); }); VARR(lavafog, 0, 50, 10000); void setprojtexmatrix(Reflection &ref, bool init = true) { if(init && ref.lastupdate==totalmillis) (ref.projmat = mvpmatrix).projective(); glLoadMatrixf(ref.projmat.v); } void setuprefractTMUs() { setuptmu(0, "= T"); if(waterreflect || (waterenvmap && hasCM)) { glActiveTexture_(GL_TEXTURE1_ARB); glEnable(waterreflect ? GL_TEXTURE_2D : GL_TEXTURE_CUBE_MAP_ARB); if(!waterreflect) glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(lookupmaterialslot(MAT_WATER))); setuptmu(1, "T , P @ Ca"); glActiveTexture_(GL_TEXTURE0_ARB); } } void setupreflectTMUs() { setuptmu(0, "T , K @ Ca", "Ka * C~a"); glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_SRC_ALPHA); if(!waterreflect) { glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_CUBE_MAP_ARB); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(lookupmaterialslot(MAT_WATER))); } } void cleanupwaterTMUs(bool refract) { resettmu(0); if(refract) { if(waterrefract || (waterenvmap && hasCM)) { glActiveTexture_(GL_TEXTURE1_ARB); resettmu(1); glLoadIdentity(); glDisable(waterreflect ? GL_TEXTURE_2D : GL_TEXTURE_CUBE_MAP_ARB); glActiveTexture_(GL_TEXTURE0_ARB); } } else { glDisable(GL_BLEND); glDepthMask(GL_TRUE); } } VARR(waterspec, 0, 150, 1000); Reflection reflections[MAXREFLECTIONS]; Reflection waterfallrefraction; GLuint reflectionfb = 0, reflectiondb = 0; GLuint getwaterfalltex() { return waterfallrefraction.refracttex ? waterfallrefraction.refracttex : notexture->id; } VAR(oqwater, 0, 2, 2); extern int oqfrags; void renderwaterff() { glDisable(GL_CULL_FACE); if(minimapping) glDisable(GL_TEXTURE_2D); else if(!nowater && (waterreflect || waterrefract || (waterenvmap && hasCM))) { if(waterrefract) setuprefractTMUs(); else setupreflectTMUs(); glMatrixMode(GL_TEXTURE); } else { glDisable(GL_TEXTURE_2D); glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } float offset = -WATER_OFFSET; memcpy(wcol, watercolor.v, 3); varray::enable(); bool wasbelow = false; loopi(MAXREFLECTIONS) { Reflection &ref = reflections[i]; if(ref.height<0 || ref.lastusedo.z < ref.height + offset; if(!nowater && (waterrefract || waterreflect || (waterenvmap && hasCM)) && !minimapping) { if(hasOQ && oqfrags && oqwater && ref.query && ref.query->owner==&ref) { if(!ref.prevquery || ref.prevquery->owner!=&ref || checkquery(ref.prevquery)) { if(checkquery(ref.query)) continue; } } bool projtex = false; if(waterreflect || (waterenvmap && hasCM)) { bool tmu1 = waterrefract && (!below || !wasbelow); if(tmu1) glActiveTexture_(GL_TEXTURE1_ARB); if(!below) { if(wasbelow) { wasbelow = false; glEnable(waterreflect ? GL_TEXTURE_2D : GL_TEXTURE_CUBE_MAP_ARB); if(!waterrefract) glBlendFunc(GL_ONE, GL_SRC_ALPHA); } if(waterreflect) { glBindTexture(GL_TEXTURE_2D, ref.tex); setprojtexmatrix(ref); projtex = true; } } else if(!wasbelow) { wasbelow = true; glDisable(waterreflect ? GL_TEXTURE_2D : GL_TEXTURE_CUBE_MAP_ARB); if(!waterrefract) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } if(tmu1) glActiveTexture_(GL_TEXTURE0_ARB); } if(waterrefract) { glBindTexture(GL_TEXTURE_2D, ref.refracttex); setprojtexmatrix(ref, !projtex); } } int lastdepth = -1; loopvj(ref.matsurfs) { materialsurface &m = *ref.matsurfs[j]; if(m.depth!=lastdepth) { float depth = !waterfog ? 1.0f : min(0.75f*m.depth/waterfog, 0.95f); if(nowater || !waterrefract) depth = max(depth, nowater || (!waterreflect && (!waterenvmap || !hasCM)) || below ? 0.6f : 0.3f); wcol[3] = int(depth*255); if(!nowater && !waterrefract && ((waterreflect || (waterenvmap && hasCM)) && !below)) { if(varray::data.length()) varray::end(); colortmu(0, depth*wcol[0]/255.0f, depth*wcol[1]/255.0f, depth*wcol[2]/255.0f, 1-depth); } lastdepth = m.depth; } renderwater(m); } if(varray::data.length()) varray::end(); } varray::disable(); if(minimapping) glEnable(GL_TEXTURE_2D); else if(!nowater && (waterrefract || waterreflect || (waterenvmap && hasCM))) { if(!waterrefract && (wasbelow || !waterreflect)) { if(!waterreflect && !wasbelow) glDisable(GL_TEXTURE_CUBE_MAP_ARB); glEnable(GL_TEXTURE_2D); } cleanupwaterTMUs(waterrefract!=0); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } else { glEnable(GL_TEXTURE_2D); glDepthMask(GL_TRUE); glDisable(GL_BLEND); } glEnable(GL_CULL_FACE); } VARFP(waterfade, 0, 1, 1, { cleanreflections(); preloadwatershaders(); }); void preloadwatershaders(bool force) { static bool needwater = false; if(force) needwater = true; if(!needwater) return; useshaderbyname("waterglare"); if(waterenvmap && !waterreflect && hasCM) useshaderbyname(waterrefract ? (waterfade && hasFBO ? "waterenvfade" : "waterenvrefract") : "waterenv"); else useshaderbyname(waterrefract ? (waterfade && hasFBO ? "waterfade" : "waterrefract") : (waterreflect ? "waterreflect" : "water")); useshaderbyname(waterrefract ? (waterfade && hasFBO ? "underwaterfade" : "underwaterrefract") : "underwater"); extern int waterfallenv; if(waterfallenv && hasCM) useshaderbyname("waterfallenv"); if(waterfallrefract) useshaderbyname(waterfallenv && hasCM ? "waterfallenvrefract" : "waterfallrefract"); } void renderwater() { if(editmode && showmat && !envmapping) return; if(!rplanes) return; if(renderpath==R_FIXEDFUNCTION) { renderwaterff(); return; } glDisable(GL_CULL_FACE); glColor3ubv(watercolor.v); MSlot &s = lookupmaterialslot(MAT_WATER); glActiveTexture_(GL_TEXTURE1_ARB); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, s.sts.inrange(2) ? s.sts[2].t->id : notexture->id); glActiveTexture_(GL_TEXTURE2_ARB); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, s.sts.inrange(3) ? s.sts[3].t->id : notexture->id); if(!glaring && !minimapping) { if(waterrefract) { glActiveTexture_(GL_TEXTURE3_ARB); glEnable(GL_TEXTURE_2D); if(waterfade && hasFBO) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } else { glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_SRC_ALPHA); } } glActiveTexture_(GL_TEXTURE0_ARB); if(!glaring && waterenvmap && !waterreflect && hasCM && !minimapping) { glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_CUBE_MAP_ARB); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(s)); } setenvparamf("camera", SHPARAM_VERTEX, 0, camera1->o.x, camera1->o.y, camera1->o.z); setenvparamf("millis", SHPARAM_VERTEX, 1, lastmillis/1000.0f, lastmillis/1000.0f, lastmillis/1000.0f); #define SETWATERSHADER(which, name) \ do { \ static Shader *name##shader = NULL; \ if(!name##shader) name##shader = lookupshaderbyname(#name); \ which##shader = name##shader; \ } while(0) Shader *aboveshader = NULL; if(glaring) SETWATERSHADER(above, waterglare); else if(minimapping) aboveshader = notextureshader; else if(waterenvmap && !waterreflect && hasCM) { if(waterrefract) { if(waterfade && hasFBO) SETWATERSHADER(above, waterenvfade); else SETWATERSHADER(above, waterenvrefract); } else SETWATERSHADER(above, waterenv); } else if(waterrefract) { if(waterfade && hasFBO) SETWATERSHADER(above, waterfade); else SETWATERSHADER(above, waterrefract); } else if(waterreflect) SETWATERSHADER(above, waterreflect); else SETWATERSHADER(above, water); Shader *belowshader = NULL; if(!glaring && !minimapping) { if(waterrefract) { if(waterfade && hasFBO) SETWATERSHADER(below, underwaterfade); else SETWATERSHADER(below, underwaterrefract); } else SETWATERSHADER(below, underwater); if(waterreflect || waterrefract) glMatrixMode(GL_TEXTURE); } varray::enable(); vec ambient(max(skylightcolor[0], ambientcolor[0]), max(skylightcolor[1], ambientcolor[1]), max(skylightcolor[2], ambientcolor[2])); float offset = -WATER_OFFSET; loopi(MAXREFLECTIONS) { Reflection &ref = reflections[i]; if(ref.height<0 || ref.lastusedowner==&ref) { if(!ref.prevquery || ref.prevquery->owner!=&ref || checkquery(ref.prevquery)) { if(checkquery(ref.query)) continue; } } bool below = camera1->o.z < ref.height+offset; if(below) { if(!belowshader) continue; belowshader->set(); } else aboveshader->set(); if(!glaring && !minimapping) { if(waterreflect || waterrefract) { if(waterreflect || !waterenvmap || !hasCM) glBindTexture(GL_TEXTURE_2D, waterreflect ? ref.tex : ref.refracttex); setprojtexmatrix(ref); } if(waterrefract) { glActiveTexture_(GL_TEXTURE3_ARB); glBindTexture(GL_TEXTURE_2D, ref.refracttex); glActiveTexture_(GL_TEXTURE0_ARB); if(waterfade) { float fadeheight = ref.height+offset+(below ? -2 : 2); setlocalparamf("waterheight", SHPARAM_VERTEX, 7, fadeheight, fadeheight, fadeheight); } } } entity *lastlight = (entity *)-1; int lastdepth = -1; loopvj(ref.matsurfs) { materialsurface &m = *ref.matsurfs[j]; entity *light = (m.light && m.light->type==ET_LIGHT ? m.light : NULL); if(light!=lastlight) { if(varray::data.length()) varray::end(); const vec &lightpos = light ? light->o : vec(worldsize/2, worldsize/2, worldsize); float lightrad = light && light->attr[0] ? light->attr[0] : worldsize*8.0f; const vec &lightcol = (light ? vec(light->attr[1], light->attr[2], light->attr[3]) : vec(ambient)).div(255.0f).mul(waterspec/100.0f); setlocalparamf("lightpos", SHPARAM_VERTEX, 2, lightpos.x, lightpos.y, lightpos.z); setlocalparamf("lightcolor", SHPARAM_PIXEL, 3, lightcol.x, lightcol.y, lightcol.z); setlocalparamf("lightradius", SHPARAM_PIXEL, 4, lightrad, lightrad, lightrad); lastlight = light; } if(!glaring && !waterrefract && m.depth!=lastdepth) { if(varray::data.length()) varray::end(); float depth = !waterfog ? 1.0f : min(0.75f*m.depth/waterfog, 0.95f); depth = max(depth, !below && (waterreflect || (waterenvmap && hasCM)) ? 0.3f : 0.6f); setlocalparamf("depth", SHPARAM_PIXEL, 5, depth, 1.0f-depth); lastdepth = m.depth; } renderwater(m); } if(varray::data.length()) varray::end(); } varray::disable(); if(!glaring && !minimapping) { if(waterreflect || waterrefract) { glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } if(waterrefract) { glActiveTexture_(GL_TEXTURE3_ARB); glDisable(GL_TEXTURE_2D); if(hasFBO && renderpath!=R_FIXEDFUNCTION && waterfade) glDisable(GL_BLEND); } else { glDepthMask(GL_TRUE); glDisable(GL_BLEND); } } loopi(2) { glActiveTexture_(GL_TEXTURE1_ARB+i); glDisable(GL_TEXTURE_2D); } glActiveTexture_(GL_TEXTURE0_ARB); if(!glaring && waterenvmap && !waterreflect && hasCM && !minimapping) { glDisable(GL_TEXTURE_CUBE_MAP_ARB); glEnable(GL_TEXTURE_2D); } glEnable(GL_CULL_FACE); } void setupwaterfallrefract(GLenum tmu1, GLenum tmu2) { glActiveTexture_(tmu1); glBindTexture(GL_TEXTURE_2D, waterfallrefraction.refracttex ? waterfallrefraction.refracttex : notexture->id); glActiveTexture_(tmu2); glMatrixMode(GL_TEXTURE); setprojtexmatrix(waterfallrefraction); glMatrixMode(GL_MODELVIEW); } Reflection *findreflection(int height) { loopi(MAXREFLECTIONS) { if(reflections[i].height==height) return &reflections[i]; } return NULL; } void cleanreflection(Reflection &ref) { ref.height = -1; ref.lastupdate = 0; ref.query = ref.prevquery = NULL; ref.matsurfs.setsize(0); if(ref.tex) { glDeleteTextures(1, &ref.tex); ref.tex = 0; } if(ref.refracttex) { glDeleteTextures(1, &ref.refracttex); ref.refracttex = 0; } } void cleanreflections() { loopi(MAXREFLECTIONS) cleanreflection(reflections[i]); cleanreflection(waterfallrefraction); if(reflectionfb) { glDeleteFramebuffers_(1, &reflectionfb); reflectionfb = 0; } if(reflectiondb) { glDeleteRenderbuffers_(1, &reflectiondb); reflectiondb = 0; } } VARFP(reflectsize, 6, 8, 10, cleanreflections()); void genwatertex(GLuint &tex, GLuint &fb, GLuint &db, bool refract = false) { static const GLenum colorfmts[] = { GL_RGBA, GL_RGBA8, GL_RGB, GL_RGB8, GL_FALSE }, depthfmts[] = { GL_DEPTH_STENCIL_EXT, GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT32, GL_FALSE }; const int stencilfmts = 2; static GLenum reflectfmt = GL_FALSE, refractfmt = GL_FALSE, depthfmt = GL_FALSE, stencilfmt = GL_FALSE; static bool usingalpha = false; bool needsalpha = refract && hasFBO && renderpath!=R_FIXEDFUNCTION && waterrefract && waterfade; if(refract && usingalpha!=needsalpha) { usingalpha = needsalpha; refractfmt = GL_FALSE; } int size = 1<screen->w || size>screen->h) size /= 2; while(size>hwtexsize) size /= 2; glGenTextures(1, &tex); char *buf = new char[size*size*4]; memset(buf, 0, size*size*4); GLenum &colorfmt = refract ? refractfmt : reflectfmt; if(colorfmt && (!hasFBO || (fb && db))) { createtexture(tex, size, size, buf, 3, 1, colorfmt); delete[] buf; return; } if(hasFBO) { if(!fb) glGenFramebuffers_(1, &fb); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, fb); } int find = needsalpha ? 0 : 2; do { createtexture(tex, size, size, buf, 3, 1, colorfmt ? colorfmt : colorfmts[find]); if(!hasFBO) break; else { glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, tex, 0); if(glCheckFramebufferStatus_(GL_FRAMEBUFFER_EXT)==GL_FRAMEBUFFER_COMPLETE_EXT) break; } } while(!colorfmt && colorfmts[++find]); if(!colorfmt) colorfmt = colorfmts[find]; delete[] buf; if(hasFBO) { if(!db) { glGenRenderbuffers_(1, &db); depthfmt = stencilfmt = GL_FALSE; } if(!depthfmt) glBindRenderbuffer_(GL_RENDERBUFFER_EXT, db); find = hasstencil && hasDS ? 0 : stencilfmts; do { if(!depthfmt) glRenderbufferStorage_(GL_RENDERBUFFER_EXT, depthfmts[find], size, size); glFramebufferRenderbuffer_(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, db); if(depthfmt ? stencilfmt : findlastused) oldest = &r; } if(!ref) { if(!oldest || oldest->lastused==totalmillis) return; ref = oldest; } if(ref->height!=height) { ref->height = height; ref->prevquery = NULL; } rplanes++; ref->lastused = totalmillis; ref->matsurfs.setsize(0); ref->matsurfs.add(&m); ref->depth = m.depth; if(nowater || minimapping) return; if(waterreflect && !ref->tex) genwatertex(ref->tex, reflectionfb, reflectiondb); if(waterrefract && !ref->refracttex) genwatertex(ref->refracttex, reflectionfb, reflectiondb, true); } extern vtxarray *visibleva; extern void drawreflection(float z, bool refract); int rplanes = 0; static int lastquery = 0; void queryreflection(Reflection &ref, bool init) { if(init) { nocolorshader->set(); glDepthMask(GL_FALSE); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDisable(GL_CULL_FACE); } startquery(ref.query); loopvj(ref.matsurfs) { materialsurface &m = *ref.matsurfs[j]; float offset = 0.1f; if(m.orient==O_TOP) { offset = WATER_OFFSET + (vertwater ? WATER_AMPLITUDE*(camera1->pitch > 0 || m.depth < WATER_AMPLITUDE+0.5f ? -1 : 1) : 0); if(fabs(m.o.z-offset - camera1->o.z) < 0.5f && m.depth > WATER_AMPLITUDE+1.5f) offset += camera1->pitch > 0 ? -1 : 1; } drawmaterial(m.orient, m.o.x, m.o.y, m.o.z, m.csize, m.rsize, offset); } xtraverts += varray::end(); endquery(ref.query); } void queryreflections() { rplanes = 0; static int lastsize = 0; int size = 1<screen->w || size>screen->h) size /= 2; while(size>hwtexsize) size /= 2; if(size!=lastsize) { if(lastsize) cleanreflections(); lastsize = size; } bool shouldrefract = waterfallrefract && renderpath!=R_FIXEDFUNCTION; for(vtxarray *va = visibleva; va; va = va->next) { if(!va->matsurfs || va->occluded >= OCCLUDE_BB || va->curvfc >= VFC_FOGGED) continue; loopi(va->matsurfs) { materialsurface &m = va->matbuf[i]; if(m.material==MAT_WATER) { if(m.orient==O_TOP) addreflection(m); else if(m.orient!=O_BOTTOM && shouldrefract) addwaterfallrefraction(m); } } } loopi(MAXREFLECTIONS) { Reflection &ref = reflections[i]; if(ref.height>=0 && ref.lastused>=totalmillis && ref.matsurfs.length()) { if(waterpvsoccluded(ref.height)) ref.matsurfs.setsize(0); } } if(renderpath!=R_FIXEDFUNCTION && waterfallrefract) { Reflection &ref = waterfallrefraction; if(ref.height>=0 && ref.lastused>=totalmillis && ref.matsurfs.length()) { if(waterpvsoccluded(-1)) ref.matsurfs.setsize(0); } } lastquery = totalmillis; if((editmode && showmat && !envmapping) || !hasOQ || !oqfrags || !oqwater || nowater || minimapping) return; varray::enable(); int refs = 0; if(waterreflect || waterrefract) loopi(MAXREFLECTIONS) { Reflection &ref = reflections[i]; ref.prevquery = oqwater > 1 ? ref.query : NULL; ref.query = ref.height>=0 && ref.lastused>=totalmillis && ref.matsurfs.length() ? newquery(&ref) : NULL; if(ref.query) queryreflection(ref, !refs++); } if(renderpath!=R_FIXEDFUNCTION && waterfallrefract) { Reflection &ref = waterfallrefraction; ref.prevquery = oqwater > 1 ? ref.query : NULL; ref.query = ref.height>=0 && ref.lastused>=totalmillis && ref.matsurfs.length() ? newquery(&ref) : NULL; if(ref.query) queryreflection(ref, !refs++); } varray::disable(); if(refs) { defaultshader->set(); glDepthMask(GL_TRUE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glEnable(GL_CULL_FACE); } glFlush(); } VARP(maxreflect, 1, 1, 8); int refracting = 0; bool reflecting = false, fading = false, fogging = false; float reflectz = 1e16f; VAR(maskreflect, 0, 2, 16); void maskreflection(Reflection &ref, float offset, bool reflect, bool clear = false) { float fogc[4] = { watercolor[0]/255.0f, watercolor[1]/255.0f, watercolor[2]/255.0f, 1.0f }; bool inside = !hasFBO && vertwater && fabs(ref.height + offset - camera1->o.z) <= WATER_AMPLITUDE; if(!maskreflect || inside) { if(clear || inside) glClearColor(fogc[0], fogc[1], fogc[2], fogc[3]); glClear(GL_DEPTH_BUFFER_BIT | (clear || inside ? GL_COLOR_BUFFER_BIT : 0) | (hasstencil && hasDS ? GL_STENCIL_BUFFER_BIT : 0)); return; } glClearDepth(0); glClear(GL_DEPTH_BUFFER_BIT | (hasstencil && hasDS ? GL_STENCIL_BUFFER_BIT : 0)); glClearDepth(1); glDepthRange(1, 1); glDepthFunc(GL_ALWAYS); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); if(clear) { notextureshader->set(); glColor3f(fogc[0], fogc[1], fogc[2]); } else { nocolorshader->set(); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } if(reflect) { glPushMatrix(); glTranslatef(0, 0, 2*(ref.height+offset)); glScalef(1, 1, -1); } int border = maskreflect; varray::enable(); loopv(ref.matsurfs) { materialsurface &m = *ref.matsurfs[i]; ivec o(m.o); o[R[dimension(m.orient)]] -= border; o[C[dimension(m.orient)]] -= border; drawmaterial(m.orient, o.x, o.y, o.z, m.csize+2*border, m.rsize+2*border, -offset); } xtraverts += varray::end(); varray::disable(); if(reflect) glPopMatrix(); if(!clear) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); defaultshader->set(); glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glDepthFunc(GL_LESS); glDepthRange(0, 1); } VAR(reflectscissor, 0, 1, 1); VAR(reflectvfc, 0, 1, 1); static bool calcscissorbox(Reflection &ref, int size, vec &clipmin, vec &clipmax, int &sx, int &sy, int &sw, int &sh) { materialsurface &m0 = *ref.matsurfs[0]; int dim = dimension(m0.orient), r = R[dim], c = C[dim]; ivec bbmin = m0.o, bbmax = bbmin; bbmax[r] += m0.rsize; bbmax[c] += m0.csize; loopvj(ref.matsurfs) { materialsurface &m = *ref.matsurfs[j]; bbmin[r] = min(bbmin[r], m.o[r]); bbmin[c] = min(bbmin[c], m.o[c]); bbmax[r] = max(bbmax[r], m.o[r] + m.rsize); bbmax[c] = max(bbmax[c], m.o[c] + m.csize); bbmin[dim] = min(bbmin[dim], m.o[dim]); bbmax[dim] = max(bbmax[dim], m.o[dim]); } vec4 v[8]; float sx1 = 1, sy1 = 1, sx2 = -1, sy2 = -1; loopi(8) { vec4 &p = v[i]; mvpmatrix.transform(vec(i&1 ? bbmax.x : bbmin.x, i&2 ? bbmax.y : bbmin.y, (i&4 ? bbmax.z + WATER_AMPLITUDE : bbmin.z - WATER_AMPLITUDE) - WATER_OFFSET), p); if(p.z >= -p.w) { float x = p.x / p.w, y = p.y / p.w; sx1 = min(sx1, x); sy1 = min(sy1, y); sx2 = max(sx2, x); sy2 = max(sy2, y); } } if(sx1 >= sx2 || sy1 >= sy2) return false; loopi(8) { const vec4 &p = v[i]; if(p.z >= -p.w) continue; loopj(3) { const vec4 &o = v[i^(1<= 1 && sy2 >= 1) return false; sx1 = max(sx1, -1.0f); sy1 = max(sy1, -1.0f); sx2 = min(sx2, 1.0f); sy2 = min(sy2, 1.0f); if(reflectvfc) { clipmin.x = clamp(clipmin.x, sx1, sx2); clipmin.y = clamp(clipmin.y, sy1, sy2); clipmax.x = clamp(clipmax.x, sx1, sx2); clipmax.y = clamp(clipmax.y, sy1, sy2); } sx = int(floor((hasFBO ? 0 : screen->w-size) + (sx1+1)*0.5f*size)); sy = int(floor((hasFBO ? 0 : screen->h-size) + (sy1+1)*0.5f*size)); sw = max(int(ceil((hasFBO ? 0 : screen->w-size) + (sx2+1)*0.5f*size)) - sx, 0); sh = max(int(ceil((hasFBO ? 0 : screen->h-size) + (sy2+1)*0.5f*size)) - sy, 0); return true; } VARR(refractclear, 0, 0, 1); void drawreflections() { if((editmode && showmat && !envmapping) || nowater || minimapping) return; extern int nvidia_scissor_bug; static int lastdrawn = 0; int refs = 0, n = lastdrawn; float offset = -WATER_OFFSET; int size = 1<screen->w || size>screen->h) size /= 2; while(size>hwtexsize) size /= 2; if(waterreflect || waterrefract) loopi(MAXREFLECTIONS) { Reflection &ref = reflections[++n%MAXREFLECTIONS]; if(ref.height<0 || ref.lastusedowner==&ref) { if(!ref.prevquery || ref.prevquery->owner!=&ref || checkquery(ref.prevquery)) { if(checkquery(ref.query)) continue; } } if(!refs) { glViewport(hasFBO ? 0 : screen->w-size, hasFBO ? 0 : screen->h-size, size, size); if(hasFBO) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, reflectionfb); } refs++; ref.lastupdate = totalmillis; lastdrawn = n; vec clipmin(-1, -1, -1), clipmax(1, 1, 1); int sx, sy, sw, sh; bool scissor = reflectscissor && calcscissorbox(ref, size, clipmin, clipmax, sx, sy, sw, sh); if(scissor) glScissor(sx, sy, sw, sh); else { sx = hasFBO ? 0 : screen->w-size; sy = hasFBO ? 0 : screen->h-size; sw = sh = size; } if(waterreflect && ref.tex && camera1->o.z >= ref.height+offset) { if(hasFBO) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, ref.tex, 0); if(scissor && !nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); maskreflection(ref, offset, true); if(scissor && nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); savevfcP(); setvfcP(ref.height+offset, clipmin, clipmax); drawreflection(ref.height+offset, false); restorevfcP(); if(scissor) glDisable(GL_SCISSOR_TEST); if(!hasFBO) { glBindTexture(GL_TEXTURE_2D, ref.tex); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, sx-(screen->w-size), sy-(screen->h-size), sx, sy, sw, sh); } } if(waterrefract && ref.refracttex) { if(hasFBO) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, ref.refracttex, 0); if(scissor && !nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); maskreflection(ref, offset, false, refractclear || !waterfog || (ref.depth>=10000 && camera1->o.z >= ref.height + offset)); if(scissor && nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); if(waterfog || (renderpath!=R_FIXEDFUNCTION && waterfade && hasFBO)) { savevfcP(); setvfcP(-1, clipmin, clipmax); drawreflection(ref.height+offset, true); restorevfcP(); } if(scissor) glDisable(GL_SCISSOR_TEST); if(!hasFBO) { glBindTexture(GL_TEXTURE_2D, ref.refracttex); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, sx-(screen->w-size), sy-(screen->h-size), sx, sy, sw, sh); } } if(refs>=maxreflect) break; } if(renderpath!=R_FIXEDFUNCTION && waterfallrefract && waterfallrefraction.refracttex) { Reflection &ref = waterfallrefraction; if(ref.height<0 || ref.lastusedowner==&ref) { if(!ref.prevquery || ref.prevquery->owner!=&ref || checkquery(ref.prevquery)) { if(checkquery(ref.query)) goto nowaterfall; } } if(!refs) { glViewport(hasFBO ? 0 : screen->w-size, hasFBO ? 0 : screen->h-size, size, size); if(hasFBO) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, reflectionfb); } refs++; ref.lastupdate = totalmillis; vec clipmin(-1, -1, -1), clipmax(1, 1, 1); int sx, sy, sw, sh; bool scissor = reflectscissor && calcscissorbox(ref, size, clipmin, clipmax, sx, sy, sw, sh); if(scissor) glScissor(sx, sy, sw, sh); else { sx = hasFBO ? 0 : screen->w-size; sy = hasFBO ? 0 : screen->h-size; sw = sh = size; } if(hasFBO) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, ref.refracttex, 0); if(scissor && !nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); maskreflection(ref, -0.1f, false, !waterfog); if(scissor && nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); if(waterfog) { savevfcP(); setvfcP(-1, clipmin, clipmax); drawreflection(-1, true); restorevfcP(); } if(scissor) glDisable(GL_SCISSOR_TEST); if(!hasFBO) { glBindTexture(GL_TEXTURE_2D, ref.refracttex); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, sx-(screen->w-size), sy-(screen->h-size), sx, sy, sw, sh); } } nowaterfall: if(!refs) return; glViewport(0, 0, screen->w, screen->h); if(hasFBO) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); defaultshader->set(); } sandboxgamemaker-2.7.1+dfsg/src/engine/sound.cpp0000664000175000017500000004643411642642476021571 0ustar showardshoward// sound.cpp: basic positional sound using sdl_mixer #include "engine.h" #include "SDL_mixer.h" #define MAXVOL MIX_MAX_VOLUME bool nosound = true; struct soundsample { char *name; Mix_Chunk *chunk; soundsample() : name(NULL), chunk(NULL) {} ~soundsample() { DELETEA(name); } void cleanup() { if(chunk) { Mix_FreeChunk(chunk); chunk = NULL; } } }; struct soundslot { soundsample *sample; int volume, maxuses; }; struct soundchannel { int id; bool inuse; vec loc; soundslot *slot; extentity *ent; int radius, volume, pan; bool dirty; soundchannel(int id) : id(id) { reset(); } bool hasloc() const { return loc.x >= -1e15f; } void clearloc() { loc = vec(-1e16f, -1e16f, -1e16f); } void reset() { inuse = false; clearloc(); slot = NULL; ent = NULL; radius = 0; volume = -1; pan = -1; dirty = false; } }; vector channels; int maxchannels = 0; soundchannel &newchannel(int n, soundslot *slot, const vec *loc = NULL, extentity *ent = NULL, int radius = 0) { if(ent) { loc = &ent->o; ent->visible = true; } while(!channels.inrange(n)) channels.add(channels.length()); soundchannel &chan = channels[n]; chan.reset(); chan.inuse = true; if(loc) chan.loc = *loc; chan.slot = slot; chan.ent = ent; chan.radius = radius; return chan; } void freechannel(int n) { // Note that this can potentially be called from the SDL_mixer audio thread. // Be careful of race conditions when checking chan.inuse without locking audio. // Can't use Mix_Playing() checks due to bug with looping sounds in SDL_mixer. if(!channels.inrange(n) || !channels[n].inuse) return; soundchannel &chan = channels[n]; chan.inuse = false; if(chan.ent) chan.ent->visible = false; } void syncchannel(soundchannel &chan) { if(!chan.dirty) return; if(!Mix_FadingChannel(chan.id)) Mix_Volume(chan.id, chan.volume); Mix_SetPanning(chan.id, 255-chan.pan, chan.pan); chan.dirty = false; } void stopchannels() { loopv(channels) { soundchannel &chan = channels[i]; if(!chan.inuse) continue; Mix_HaltChannel(i); freechannel(i); } } void setmusicvol(int musicvol); VARFP(soundvol, 0, 255, 255, if(!soundvol) { stopchannels(); setmusicvol(0); }); VARFP(musicvol, 0, 128, 255, setmusicvol(soundvol ? musicvol : 0)); char *musicfile = NULL, *musicdonecmd = NULL; Mix_Music *music = NULL; SDL_RWops *musicrw = NULL; stream *musicstream = NULL; void setmusicvol(int musicvol) { if(nosound) return; if(music) Mix_VolumeMusic((musicvol*MAXVOL)/255); } void stopmusic() { if(nosound) return; DELETEA(musicfile); DELETEA(musicdonecmd); if(music) { Mix_HaltMusic(); Mix_FreeMusic(music); music = NULL; } if(musicrw) { SDL_FreeRW(musicrw); musicrw = NULL; } DELETEP(musicstream); } VARF(soundchans, 1, 32, 128, initwarning("sound configuration", INIT_RESET, CHANGE_SOUND)); VARF(soundfreq, 0, MIX_DEFAULT_FREQUENCY, 44100, initwarning("sound configuration", INIT_RESET, CHANGE_SOUND)); VARF(soundbufferlen, 128, 1024, 4096, initwarning("sound configuration", INIT_RESET, CHANGE_SOUND)); void initsound() { if(Mix_OpenAudio(soundfreq, MIX_DEFAULT_FORMAT, 2, soundbufferlen)<0) { nosound = true; conoutf(CON_ERROR, "sound init failed (SDL_mixer): %s", (size_t)Mix_GetError()); return; } Mix_AllocateChannels(soundchans); Mix_ChannelFinished(freechannel); maxchannels = soundchans; nosound = false; } void musicdone() { if(music) { Mix_HaltMusic(); Mix_FreeMusic(music); music = NULL; } if(musicrw) { SDL_FreeRW(musicrw); musicrw = NULL; } DELETEP(musicstream); DELETEA(musicfile); if(!musicdonecmd) return; char *cmd = musicdonecmd; musicdonecmd = NULL; execute(cmd); delete[] cmd; } Mix_Music *loadmusic(const char *name) { if(!musicstream) musicstream = openzipfile(name, "rb"); if(musicstream) { if(!musicrw) musicrw = musicstream->rwops(); if(!musicrw) DELETEP(musicstream); } if(musicrw) music = Mix_LoadMUS_RW(musicrw); else music = Mix_LoadMUS(findfile(name, "rb")); if(!music) { if(musicrw) { SDL_FreeRW(musicrw); musicrw = NULL; } DELETEP(musicstream); } return music; } const char *exts[] = { "", ".ogg", ".mp3", ".mid", ".mod", ".wav" }; VAR(dbgmusic, 0, 0, 1); void startmusic(char *name, char *cmd) { if(nosound || !musicvol || !soundvol) { if(dbgmusic) conoutf("aborting, sound disabled"); return;} stopmusic(); const char *paths[] = { "packages/", "", "packages/music/" }; string sn; if(*name) { loopi(sizeof(paths)/sizeof(paths[0])) { loopj(sizeof(exts)/sizeof(exts[0])) { formatstring(sn)("%s%s%s", paths[i], name, exts[j]); if(dbgmusic) conoutf("trying path: %s", sn); const char *file = path(sn); if(loadmusic(file)) { if(dbgmusic) conoutf("File found!"); DELETEA(musicfile); DELETEA(musicdonecmd); musicfile = newstring(file); if(cmd[0]) musicdonecmd = newstring(cmd); Mix_PlayMusic(music, cmd[0] ? 0 : -1); Mix_VolumeMusic((musicvol*MAXVOL)/255); intret(1); return; } } } conoutf(CON_ERROR, "could not play music: %s", name); } else if(dbgmusic) conoutf("no file name provided"); intret(0); } COMMANDN(music, startmusic, "ss"); hashtable samples; vector gamesounds, mapsounds; int findsound(const char *name, int vol, vector &sounds) { loopv(sounds) { if(!strcmp(sounds[i].sample->name, name) && (!vol || sounds[i].volume==vol)) return i; } return -1; } int addsound(const char *name, int vol, int maxuses, vector &sounds) { soundsample *s = samples.access(name); if(!s) { char *n = newstring(name); s = &samples[n]; s->name = n; s->chunk = NULL; } soundslot *oldsounds = sounds.getbuf(); int oldlen = sounds.length(); soundslot &slot = sounds.add(); // sounds.add() may relocate slot pointers if(sounds.getbuf() != oldsounds) loopv(channels) { soundchannel &chan = channels[i]; if(chan.inuse && chan.slot >= oldsounds && chan.slot < &oldsounds[oldlen]) chan.slot = &sounds[chan.slot - oldsounds]; } slot.sample = s; slot.volume = vol ? vol : 100; slot.maxuses = maxuses; return oldlen; } void registersound(char *name, int *vol) { intret(addsound(name, *vol, 0, gamesounds)); } COMMAND(registersound, "si"); void mapsound(char *name, int *vol, int *maxuses) { intret(addsound(name, *vol, *maxuses < 0 ? 0 : max(1, *maxuses), mapsounds)); } COMMAND(mapsound, "sii"); void resetchannels() { loopv(channels) if(channels[i].inuse) freechannel(i); channels.shrink(0); } void clear_sound() { closemumble(); if(nosound) return; stopmusic(); enumerate(samples, soundsample, s, s.cleanup()); Mix_CloseAudio(); resetchannels(); gamesounds.setsize(0); mapsounds.setsize(0); samples.clear(); } void clearmapsounds() { loopv(channels) if(channels[i].inuse && channels[i].ent) { Mix_HaltChannel(i); freechannel(i); } mapsounds.setsize(0); } COMMANDN(mapsoundreset, clearmapsounds, ""); void stopmapsound(extentity *e) { loopv(channels) { soundchannel &chan = channels[i]; if(chan.inuse && chan.ent == e) { Mix_HaltChannel(i); freechannel(i); } } } void checkmapsounds() { const vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; if(e.type!=ET_SOUND) continue; if(camera1->o.dist(e.o) < e.attr[1]) { if(!e.visible) playsound(e.attr[0], NULL, &e, -1); } else if(e.visible) stopmapsound(&e); } } VAR(stereo, 0, 1, 1); VARP(maxsoundradius, 0, 340, 10000); bool updatechannel(soundchannel &chan) { if(!chan.slot) return false; int vol = soundvol, pan = 255/2; if(chan.hasloc()) { vec v; float dist = chan.loc.dist(camera1->o, v); int rad = maxsoundradius; if(chan.ent) { rad = chan.ent->attr[1]; if(chan.ent->attr[2]) { rad -= chan.ent->attr[2]; dist -= chan.ent->attr[2]; } } else if(chan.radius > 0) rad = maxsoundradius ? min(maxsoundradius, chan.radius) : chan.radius; if(rad > 0) vol -= int(clamp(dist/rad, 0.0f, 1.0f)*soundvol); // simple mono distance attenuation if(stereo && (v.x != 0 || v.y != 0) && dist>0) { v.rotate_around_z(-camera1->yaw*RAD); pan = int(255.9f*(0.5f - 0.5f*v.x/v.magnitude2())); // range is from 0 (left) to 255 (right) } } vol = (vol*MAXVOL*chan.slot->volume)/255/255; vol = min(vol, MAXVOL); if(vol == chan.volume && pan == chan.pan) return false; chan.volume = vol; chan.pan = pan; chan.dirty = true; return true; } void updatesounds() { updatemumble(); if(nosound) return; checkmapsounds(); int dirty = 0; loopv(channels) { soundchannel &chan = channels[i]; if(chan.inuse && chan.hasloc() && updatechannel(chan)) dirty++; } if(dirty) { SDL_LockAudio(); // workaround for race conditions inside Mix_SetPanning loopv(channels) { soundchannel &chan = channels[i]; if(chan.inuse && chan.dirty) syncchannel(chan); } SDL_UnlockAudio(); } if(music) { if(!Mix_PlayingMusic()) musicdone(); else if(Mix_PausedMusic()) Mix_ResumeMusic(); } } VARP(maxsoundsatonce, 0, 5, 100); VAR(dbgsound, 0, 0, 1); static Mix_Chunk *loadwav(const char *name) { Mix_Chunk *c = NULL; stream *z = openzipfile(name, "rb"); if(z) { SDL_RWops *rw = z->rwops(); if(rw) { c = Mix_LoadWAV_RW(rw, 0); SDL_FreeRW(rw); } delete z; } if(!c) c = Mix_LoadWAV(findfile(name, "rb")); return c; } int playsound(int n, const vec *loc, extentity *ent, int loops, int fade, int chanid, int radius, int expire) { if(nosound || !soundvol) return -1; vector &sounds = ent ? mapsounds : gamesounds; if(!sounds.inrange(n)) { conoutf(CON_WARN, "unregistered sound: %d", n); return -1; } soundslot &slot = sounds[n]; if(loc && (maxsoundradius || radius > 0)) { // cull sounds that are unlikely to be heard int rad = radius > 0 ? (maxsoundradius ? min(maxsoundradius, radius) : radius) : maxsoundradius; if(camera1->o.dist(*loc) > 1.5f*rad) { if(channels.inrange(chanid) && channels[chanid].inuse && channels[chanid].slot == &slot) { Mix_HaltChannel(chanid); freechannel(chanid); } return -1; } } if(chanid < 0) { if(slot.maxuses) { int uses = 0; loopv(channels) if(channels[i].inuse && channels[i].slot == &slot && ++uses >= slot.maxuses) return -1; } // avoid bursts of sounds with heavy packetloss and in sp static int soundsatonce = 0, lastsoundmillis = 0; if(totalmillis == lastsoundmillis) soundsatonce++; else soundsatonce = 1; lastsoundmillis = totalmillis; if(maxsoundsatonce && soundsatonce > maxsoundsatonce) return -1; } if(!slot.sample->chunk) { if(!slot.sample->name[0]) return -1; const char *exts[] = { "", ".wav", ".ogg" }; string buf; loopi(sizeof(exts)/sizeof(exts[0])) { formatstring(buf)("packages/sounds/%s%s", slot.sample->name, exts[i]); path(buf); slot.sample->chunk = loadwav(buf); if(slot.sample->chunk) break; } if(!slot.sample->chunk) { conoutf(CON_ERROR, "failed to load sample: %s", buf); return -1; } } if(channels.inrange(chanid)) { soundchannel &chan = channels[chanid]; if(chan.inuse && chan.slot == &slot) { if(loc) chan.loc = *loc; else if(chan.hasloc()) chan.clearloc(); return chanid; } } if(fade < 0) return -1; if(dbgsound) conoutf("sound: %s", slot.sample->name); chanid = -1; loopv(channels) if(!channels[i].inuse) { chanid = i; break; } if(chanid < 0 && channels.length() < maxchannels) chanid = channels.length(); if(chanid < 0) loopv(channels) if(!channels[i].volume) { chanid = i; break; } if(chanid < 0) return -1; SDL_LockAudio(); // must lock here to prevent freechannel/Mix_SetPanning race conditions if(channels.inrange(chanid) && channels[chanid].inuse) { Mix_HaltChannel(chanid); freechannel(chanid); } soundchannel &chan = newchannel(chanid, &slot, loc, ent, radius); updatechannel(chan); int playing = -1; if(fade) { Mix_Volume(chanid, chan.volume); playing = expire >= 0 ? Mix_FadeInChannelTimed(chanid, slot.sample->chunk, loops, fade, expire) : Mix_FadeInChannel(chanid, slot.sample->chunk, loops, fade); } else playing = expire >= 0 ? Mix_PlayChannelTimed(chanid, slot.sample->chunk, loops, expire) : Mix_PlayChannel(chanid, slot.sample->chunk, loops); if(playing >= 0) syncchannel(chan); else freechannel(chanid); SDL_UnlockAudio(); return playing; } void stopsounds() { loopv(channels) if(channels[i].inuse) { Mix_HaltChannel(i); freechannel(i); } } bool stopsound(int n, int chanid, int fade) { if(!channels.inrange(chanid) || !channels[chanid].inuse || !gamesounds.inrange(n) || channels[chanid].slot != &gamesounds[n]) return false; if(dbgsound) conoutf("stopsound: %s", channels[chanid].slot->sample->name); if(!fade || !Mix_FadeOutChannel(chanid, fade)) { Mix_HaltChannel(chanid); freechannel(chanid); } return true; } int playsoundname(const char *s, const vec *loc, int vol, int loops, int fade, int chanid, int radius, int expire) { if(!vol) vol = 100; int id = findsound(s, vol, gamesounds); if(id < 0) id = addsound(s, vol, 0, gamesounds); return playsound(id, loc, NULL, loops, fade, chanid, radius, expire); } void sound(int *n) { playsound(*n); } COMMAND(sound, "i"); ICOMMAND(entsoundname, "i", (int *id), if(mapsounds.inrange(*id)) {defformatstring(s)("%s", mapsounds[*id].sample->name); result(s);} ); void writemapsounds(stream *f) { loopv(mapsounds) { f->printf("mapsound \"%s\" %d %d // %d\n", mapsounds[i].sample->name, mapsounds[i].volume, mapsounds[i].maxuses, i); } } void resetsound() { const SDL_version *v = Mix_Linked_Version(); if(SDL_VERSIONNUM(v->major, v->minor, v->patch) <= SDL_VERSIONNUM(1, 2, 8)) { conoutf(CON_ERROR, "Sound reset not available in-game due to SDL_mixer-1.2.8 bug. Please restart for changes to take effect."); return; } clearchanges(CHANGE_SOUND); if(!nosound) { enumerate(samples, soundsample, s, s.cleanup()); if(music) { Mix_HaltMusic(); Mix_FreeMusic(music); } if(musicstream) musicstream->seek(0, SEEK_SET); Mix_CloseAudio(); } initsound(); resetchannels(); if(nosound) { DELETEA(musicfile); DELETEA(musicdonecmd); music = NULL; gamesounds.setsize(0); mapsounds.setsize(0); samples.clear(); return; } if(music && loadmusic(musicfile)) { Mix_PlayMusic(music, musicdonecmd ? 0 : -1); Mix_VolumeMusic((musicvol*MAXVOL)/255); } else { DELETEA(musicfile); DELETEA(musicdonecmd); } } COMMAND(resetsound, ""); #ifdef WIN32 #include #else #include #ifdef _POSIX_SHARED_MEMORY_OBJECTS #include #include #include #include #include #endif #endif #if defined(WIN32) || defined(_POSIX_SHARED_MEMORY_OBJECTS) struct MumbleInfo { int version, timestamp; vec pos, front, top; wchar_t name[256]; }; #endif #ifdef WIN32 static HANDLE mumblelink = NULL; static MumbleInfo *mumbleinfo = NULL; #define VALID_MUMBLELINK (mumblelink && mumbleinfo) #elif defined(_POSIX_SHARED_MEMORY_OBJECTS) static int mumblelink = -1; static MumbleInfo *mumbleinfo = (MumbleInfo *)-1; #define VALID_MUMBLELINK (mumblelink >= 0 && mumbleinfo != (MumbleInfo *)-1) #endif #ifdef VALID_MUMBLELINK VARFP(mumble, 0, 1, 1, { if(mumble) initmumble(); else closemumble(); }); #else VARFP(mumble, 0, 0, 1, { if(mumble) initmumble(); else closemumble(); }); #endif void initmumble() { if(!mumble) return; #ifdef VALID_MUMBLELINK if(VALID_MUMBLELINK) return; #ifdef WIN32 mumblelink = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, "MumbleLink"); if(mumblelink) { mumbleinfo = (MumbleInfo *)MapViewOfFile(mumblelink, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(MumbleInfo)); if(mumbleinfo) wcsncpy(mumbleinfo->name, L"PA Sandbox", 256); } #elif defined(_POSIX_SHARED_MEMORY_OBJECTS) defformatstring(shmname)("/MumbleLink.%d", getuid()); mumblelink = shm_open(shmname, O_RDWR, 0); if(mumblelink >= 0) { mumbleinfo = (MumbleInfo *)mmap(NULL, sizeof(MumbleInfo), PROT_READ|PROT_WRITE, MAP_SHARED, mumblelink, 0); if(mumbleinfo != (MumbleInfo *)-1) wcsncpy(mumbleinfo->name, L"PA Sandbox", 256); } #endif if(!VALID_MUMBLELINK) closemumble(); #else conoutf(CON_ERROR, "Mumble positional audio is not available on this platform."); #endif } void closemumble() { #ifdef WIN32 if(mumbleinfo) { UnmapViewOfFile(mumbleinfo); mumbleinfo = NULL; } if(mumblelink) { CloseHandle(mumblelink); mumblelink = NULL; } #elif defined(_POSIX_SHARED_MEMORY_OBJECTS) if(mumbleinfo != (MumbleInfo *)-1) { munmap(mumbleinfo, sizeof(MumbleInfo)); mumbleinfo = (MumbleInfo *)-1; } if(mumblelink >= 0) { close(mumblelink); mumblelink = -1; } #endif } static inline vec mumblevec(const vec &v, bool pos = false) { // change from X left, Z up, Y forward to X right, Y up, Z forward // 8 cube units = 1 meter vec m(-v.x, v.z, v.y); if(pos) m.div(8); return m; } void updatemumble() { #ifdef VALID_MUMBLELINK if(!VALID_MUMBLELINK) return; static int timestamp = 0; mumbleinfo->version = 1; mumbleinfo->timestamp = ++timestamp; mumbleinfo->pos = mumblevec(player->o, true); mumbleinfo->front = mumblevec(vec(RAD*player->yaw, RAD*player->pitch)); mumbleinfo->top = mumblevec(vec(RAD*player->yaw, RAD*(player->pitch+90))); #endif } sandboxgamemaker-2.7.1+dfsg/src/engine/rendertarget.h0000664000175000017500000004704511400572336022560 0ustar showardshowardextern int rtsharefb, rtscissor, blurtile; struct rendertarget { int texw, texh, vieww, viewh; GLenum colorfmt, depthfmt, target; GLuint rendertex, renderfb, renderdb, blurtex, blurfb, blurdb; int blursize; float blursigma; float blurweights[MAXBLURRADIUS+1], bluroffsets[MAXBLURRADIUS+1]; float scissorx1, scissory1, scissorx2, scissory2; #define BLURTILES 32 #define BLURTILEMASK (0xFFFFFFFFU>>(32-BLURTILES)) uint blurtiles[BLURTILES+1]; bool initialized; rendertarget() : texw(0), texh(0), vieww(0), viewh(0), colorfmt(GL_FALSE), depthfmt(GL_FALSE), target(GL_TEXTURE_2D), rendertex(0), renderfb(0), renderdb(0), blurtex(0), blurfb(0), blurdb(0), blursize(0), blursigma(0), initialized(false) { } virtual ~rendertarget() {} virtual GLenum attachment() const { return GL_COLOR_ATTACHMENT0_EXT; } virtual const GLenum *colorformats() const { static const GLenum colorfmts[] = { GL_RGB, GL_RGB8, GL_FALSE }; return colorfmts; } virtual const GLenum *depthformats() const { static const GLenum depthfmts[] = { GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT32, GL_FALSE }; return depthfmts; } virtual bool depthtest() const { return true; } void cleanup(bool fullclean = false) { if(renderfb) { glDeleteFramebuffers_(1, &renderfb); renderfb = 0; } if(renderdb) { glDeleteRenderbuffers_(1, &renderdb); renderdb = 0; } if(rendertex) { glDeleteTextures(1, &rendertex); rendertex = 0; } texw = texh = 0; cleanupblur(); if(fullclean) colorfmt = depthfmt = GL_FALSE; } void cleanupblur() { if(blurfb) { glDeleteFramebuffers_(1, &blurfb); blurfb = 0; } if(blurtex) { glDeleteTextures(1, &blurtex); blurtex = 0; } if(blurdb) { glDeleteRenderbuffers_(1, &blurdb); blurdb = 0; } blursize = 0; blursigma = 0.0f; } void setupblur() { if(!hasFBO) return; if(!blurtex) glGenTextures(1, &blurtex); createtexture(blurtex, texw, texh, NULL, 3, 1, colorfmt, target); if(!swaptexs() || rtsharefb) return; if(!blurfb) glGenFramebuffers_(1, &blurfb); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, blurfb); glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target, blurtex, 0); if(depthtest()) { if(!blurdb) glGenRenderbuffers_(1, &blurdb); glGenRenderbuffers_(1, &blurdb); glBindRenderbuffer_(GL_RENDERBUFFER_EXT, blurdb); glRenderbufferStorage_(GL_RENDERBUFFER_EXT, depthfmt, texw, texh); glFramebufferRenderbuffer_(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, blurdb); } glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); } virtual bool shadowcompare() const { return false; } void setup(int w, int h) { if(hasFBO) { if(!renderfb) glGenFramebuffers_(1, &renderfb); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, renderfb); } if(!rendertex) glGenTextures(1, &rendertex); target = texrect() ? GL_TEXTURE_RECTANGLE_ARB : GL_TEXTURE_2D; GLenum attach = attachment(); if(hasFBO && attach == GL_DEPTH_ATTACHMENT_EXT) { glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); } const GLenum *colorfmts = colorformats(); int find = 0; do { createtexture(rendertex, w, h, NULL, 3, filter() ? 1 : 0, colorfmt ? colorfmt : colorfmts[find], target); if(!hasFBO) break; else { glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, attach, target, rendertex, 0); if(glCheckFramebufferStatus_(GL_FRAMEBUFFER_EXT)==GL_FRAMEBUFFER_COMPLETE_EXT) break; } } while(!colorfmt && colorfmts[++find]); if(!colorfmt) colorfmt = colorfmts[find]; if(attach == GL_DEPTH_ATTACHMENT_EXT && shadowcompare()) { if(hasDT && hasSH) { glTexParameteri(target, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE); glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC_ARB, GL_GEQUAL); glTexParameteri(target, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE); } else { glTexParameteri(target, GL_TEXTURE_COMPARE_SGIX, GL_TRUE); glTexParameteri(target, GL_TEXTURE_COMPARE_OPERATOR_SGIX, GL_TEXTURE_GEQUAL_R_SGIX); } } if(hasFBO && attach != GL_DEPTH_ATTACHMENT_EXT && depthtest()) { if(!renderdb) { glGenRenderbuffers_(1, &renderdb); depthfmt = GL_FALSE; } if(!depthfmt) glBindRenderbuffer_(GL_RENDERBUFFER_EXT, renderdb); const GLenum *depthfmts = depthformats(); find = 0; do { if(!depthfmt) glRenderbufferStorage_(GL_RENDERBUFFER_EXT, depthfmts[find], w, h); glFramebufferRenderbuffer_(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderdb); if(glCheckFramebufferStatus_(GL_FRAMEBUFFER_EXT)==GL_FRAMEBUFFER_COMPLETE_EXT) break; } while(!depthfmt && depthfmts[++find]); if(!depthfmt) depthfmt = depthfmts[find]; } if(hasFBO) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); texw = w; texh = h; initialized = false; } bool addblurtiles(float x1, float y1, float x2, float y2, float blurmargin = 0) { if(x1 >= 1 || y1 >= 1 || x2 <= -1 || y2 <= -1) return false; scissorx1 = min(scissorx1, max(x1, -1.0f)); scissory1 = min(scissory1, max(y1, -1.0f)); scissorx2 = max(scissorx2, min(x2, 1.0f)); scissory2 = max(scissory2, min(y2, 1.0f)); float blurerror = 2.0f*float(2*blursize + blurmargin); int tx1 = max(0, min(BLURTILES - 1, int((x1-blurerror/vieww + 1)/2 * BLURTILES))), ty1 = max(0, min(BLURTILES - 1, int((y1-blurerror/viewh + 1)/2 * BLURTILES))), tx2 = max(0, min(BLURTILES - 1, int((x2+blurerror/vieww + 1)/2 * BLURTILES))), ty2 = max(0, min(BLURTILES - 1, int((y2+blurerror/viewh + 1)/2 * BLURTILES))); uint mask = (BLURTILEMASK>>(BLURTILES - (tx2+1))) & (BLURTILEMASK< scissorx2 || y1-blurerror/viewh > scissory2) return false; if(!blurtile) return true; int tx1 = max(0, min(BLURTILES - 1, int((x1 + 1)/2 * BLURTILES))), ty1 = max(0, min(BLURTILES - 1, int((y1 + 1)/2 * BLURTILES))), tx2 = max(0, min(BLURTILES - 1, int((x2 + 1)/2 * BLURTILES))), ty2 = max(0, min(BLURTILES - 1, int((y2 + 1)/2 * BLURTILES))); uint mask = (BLURTILEMASK>>(BLURTILES - (tx2+1))) & (BLURTILEMASK<>= 8; x += 8; } while(!(mask&1)) { mask >>= 1; x++; } int xstart = x; do { mask >>= 1; x++; } while(mask&1); uint strip = (BLURTILEMASK>>(BLURTILES - x)) & (BLURTILEMASK<w-vieww; y += screen->h-viewh; } else if(!blurtex) setupblur(); if(blursize!=wantsblursize || (wantsblursize && blursigma!=wantsblursigma)) { setupblurkernel(wantsblursize, wantsblursigma, blurweights, bluroffsets); blursize = wantsblursize; blursigma = wantsblursigma; } glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); if(scissor) { glScissor(x, y, w, h); glEnable(GL_SCISSOR_TEST); } loopi(2) { setblurshader(i, target == GL_TEXTURE_RECTANGLE_ARB ? 1 : (i ? texh : texw), blursize, blurweights, bluroffsets, target); if(hasFBO) { if(!swaptexs() || rtsharefb) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target, i ? rendertex : blurtex, 0); else glBindFramebuffer_(GL_FRAMEBUFFER_EXT, i ? renderfb : blurfb); glBindTexture(target, i ? blurtex : rendertex); } rendertiles(); if(!hasFBO) glCopyTexSubImage2D(target, 0, x-(screen->w-vieww), y-(screen->h-viewh), x, y, w, h); } if(scissor) glDisable(GL_SCISSOR_TEST); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); } virtual bool swaptexs() const { return false; } virtual bool dorender() { return true; } virtual bool shouldrender() { return true; } virtual void doblur(int blursize, float blursigma) { int sx, sy, sw, sh; bool scissoring = rtscissor && scissorblur(sx, sy, sw, sh) && sw > 0 && sh > 0; if(!scissoring) { sx = sy = 0; sw = vieww; sh = viewh; } blur(blursize, blursigma, sx, sy, sw, sh, scissoring); } virtual bool scissorrender(int &x, int &y, int &w, int &h) { if(scissorx1 >= scissorx2 || scissory1 >= scissory2) { if(vieww < texw || viewh < texh) { x = y = 0; w = vieww; h = viewh; return true; } return false; } x = max(int(floor((scissorx1+1)/2*vieww)) - 2*blursize, 0); y = max(int(floor((scissory1+1)/2*viewh)) - 2*blursize, 0); w = min(int(ceil((scissorx2+1)/2*vieww)) + 2*blursize, vieww) - x; h = min(int(ceil((scissory2+1)/2*viewh)) + 2*blursize, viewh) - y; return true; } virtual bool scissorblur(int &x, int &y, int &w, int &h) { if(scissorx1 >= scissorx2 || scissory1 >= scissory2) { if(vieww < texw || viewh < texh) { x = y = 0; w = vieww; h = viewh; return true; } return false; } x = max(int(floor((scissorx1+1)/2*vieww)), 0); y = max(int(floor((scissory1+1)/2*viewh)), 0); w = min(int(ceil((scissorx2+1)/2*vieww)), vieww) - x; h = min(int(ceil((scissory2+1)/2*viewh)), viewh) - y; return true; } virtual void doclear() {} virtual bool screenview() const { return false; } virtual bool texrect() const { return false; } virtual bool filter() const { return true; } void render(int w, int h, int blursize = 0, float blursigma = 0) { w = min(w, hwtexsize); h = min(h, hwtexsize); if(texrect()) { if(w > screen->w) w = screen->w; if(h > screen->h) h = screen->h; vieww = w; viewh = h; } else if(screenview()) { while(screen->w < (w*3)/4) w /= 2; while(screen->h < (h*3)/4) h /= 2; vieww = min(w, screen->w); viewh = min(h, screen->h); } else { if(!hasFBO) { while(w > screen->w) w /= 2; while(h > screen->h) h /= 2; } vieww = w; viewh = h; } if(w!=texw || h!=texh || (texrect() ? target!=GL_TEXTURE_RECTANGLE_ARB : target!=GL_TEXTURE_2D) || (hasFBO && (swaptexs() && !rtsharefb ? !blurfb : blurfb))) cleanup(); if(!filter()) { if(blurtex) cleanupblur(); blursize = 0; } if(!rendertex) setup(w, h); scissorx2 = scissory2 = -1; scissorx1 = scissory1 = 1; memset(blurtiles, 0, sizeof(blurtiles)); if(!shouldrender()) return; if(hasFBO) { if(blursize && !blurtex) setupblur(); if(swaptexs() && blursize) { swap(rendertex, blurtex); if(!rtsharefb) { swap(renderfb, blurfb); swap(renderdb, blurdb); } } glBindFramebuffer_(GL_FRAMEBUFFER_EXT, renderfb); if(swaptexs() && blursize && rtsharefb) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, attachment(), target, rendertex, 0); glViewport(0, 0, vieww, viewh); } else glViewport(screen->w-vieww, screen->h-viewh, vieww, viewh); doclear(); int sx, sy, sw, sh; bool scissoring = rtscissor && scissorrender(sx, sy, sw, sh) && sw > 0 && sh > 0; if(scissoring) { if(!hasFBO) { sx += screen->w-vieww; sy += screen->h-viewh; } glScissor(sx, sy, sw, sh); glEnable(GL_SCISSOR_TEST); } else { sx = hasFBO ? 0 : screen->w-vieww; sy = hasFBO ? 0 : screen->h-viewh; sw = vieww; sh = viewh; } if(!depthtest()) glDisable(GL_DEPTH_TEST); bool succeeded = dorender(); if(!depthtest()) glEnable(GL_DEPTH_TEST); if(scissoring) glDisable(GL_SCISSOR_TEST); if(succeeded) { if(!hasFBO) { glBindTexture(target, rendertex); if(!initialized) { sx = screen->w-vieww; sy = screen->h-viewh; sw = vieww; sh = viewh; } glCopyTexSubImage2D(target, 0, sx-(screen->w-vieww), sy-(screen->h-viewh), sx, sy, sw, sh); } initialized = true; if(blursize) doblur(blursize, blursigma); } if(hasFBO) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); glViewport(0, 0, screen->w, screen->h); } virtual void dodebug(int w, int h) {} virtual bool flipdebug() const { return true; } void debugscissor(int w, int h, bool lines = false) { if(!rtscissor || scissorx1 >= scissorx2 || scissory1 >= scissory2) return; int sx = int(0.5f*(scissorx1 + 1)*w), sy = int(0.5f*(scissory1 + 1)*h), sw = int(0.5f*(scissorx2 - scissorx1)*w), sh = int(0.5f*(scissory2 - scissory1)*h); if(flipdebug()) { sy = h - sy; sh = -sh; } glBegin(lines ? GL_LINE_LOOP : GL_TRIANGLE_STRIP); glVertex2i(sx, sy); glVertex2i(sx + sw, sy); if(lines) glVertex2i(sx + sw, sy + sh); glVertex2i(sx, sy + sh); if(!lines) glVertex2i(sx + sw, sy + sh); glEnd(); } void debugblurtiles(int w, int h, bool lines = false) { if(!blurtile) return; float vxsz = float(w)/BLURTILES, vysz = float(h)/BLURTILES; loop(y, BLURTILES+1) { uint mask = blurtiles[y]; int x = 0; while(mask) { while(!(mask&0xFF)) { mask >>= 8; x += 8; } while(!(mask&1)) { mask >>= 1; x++; } int xstart = x; do { mask >>= 1; x++; } while(mask&1); uint strip = (BLURTILEMASK>>(BLURTILES - x)) & (BLURTILEMASK<w, screen->h)/2, h = (w*screen->h)/screen->w; (target==GL_TEXTURE_RECTANGLE_ARB ? rectshader : defaultshader)->set(); glColor3f(1, 1, 1); glEnable(target); glBindTexture(target, rendertex); float tx1 = 0, tx2 = vieww, ty1 = 0, ty2 = viewh; if(target!=GL_TEXTURE_RECTANGLE_ARB) { tx2 /= vieww; ty2 /= viewh; } if(flipdebug()) swap(ty1, ty2); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(tx1, ty1); glVertex2i(0, 0); glTexCoord2f(tx2, ty1); glVertex2i(w, 0); glTexCoord2f(tx1, ty2); glVertex2i(0, h); glTexCoord2f(tx2, ty2); glVertex2i(w, h); glEnd(); notextureshader->set(); glDisable(target); dodebug(w, h); } }; sandboxgamemaker-2.7.1+dfsg/src/engine/model.h0000664000175000017500000000605011557073134021166 0ustar showardshowardenum { MDL_MD2 = 0, MDL_MD3, MDL_MD5, MDL_OBJ, MDL_SMD, MDL_IQM, NUMMODELTYPES }; struct model { float spinyaw, spinpitch, spinroll, offsetyaw, offsetpitch, offsetroll; bool collide, ellipsecollide, shadow, alphadepth, depthoffset; float scale; vec translate; BIH *bih; vec bbcenter, bbradius, bbextend; float eyeheight, collideradius, collideheight; int batch; model() : spinyaw(0), spinpitch(0), spinroll(0), offsetyaw(0), offsetpitch(0), offsetroll(0), collide(true), ellipsecollide(false), shadow(true), alphadepth(true), depthoffset(false), scale(1.0f), translate(0, 0, 0), bih(0), bbcenter(0, 0, 0), bbradius(0, 0, 0), bbextend(0, 0, 0), eyeheight(0.9f), collideradius(0), collideheight(0), batch(-1) {} virtual ~model() { DELETEP(bih); } virtual void calcbb(int frame, vec ¢er, vec &radius) = 0; virtual void render(int anim, int basetime, int basetime2, const vec &o, float yaw, float pitch, float roll, dynent *d, modelattach *a = NULL, const vec &color = vec(0, 0, 0), const vec &dir = vec(0, 0, 0), float transparent = 1) = 0; virtual bool load() = 0; virtual const char *name() const = 0; virtual int type() const = 0; virtual BIH *setBIH() { return 0; } virtual bool envmapped() { return false; } virtual bool skeletal() const { return false; } virtual void setshader(Shader *shader) {} virtual void setenvmap(float envmapmin, float envmapmax, Texture *envmap) {} virtual void setspec(float spec) {} virtual void setambient(float ambient) {} virtual void setglow(float glow, float glowdelta, float glowpulse) {} virtual void setglare(float specglare, float glowglare) {} virtual void setalphatest(float alpha) {} virtual void setalphablend(bool blend) {} virtual void setfullbright(float fullbright) {} virtual void setcullface(bool cullface) {} virtual void preloadBIH() { if(!bih) setBIH(); } virtual void preloadshaders() {} virtual void cleanup() {} virtual void startrender() {} virtual void endrender() {} void boundbox(int frame, vec ¢er, vec &radius) { if(frame) calcbb(frame, center, radius); else { if(bbradius.iszero()) calcbb(0, bbcenter, bbradius); center = bbcenter; radius = bbradius; } radius.add(bbextend); } void collisionbox(int frame, vec ¢er, vec &radius) { boundbox(frame, center, radius); if(collideradius) { center[0] = center[1] = 0; radius[0] = radius[1] = collideradius; } if(collideheight) { center[2] = radius[2] = collideheight/2; } } float boundsphere(int frame, vec ¢er) { vec radius; boundbox(frame, center, radius); return radius.magnitude(); } float above(int frame = 0) { vec center, radius; boundbox(frame, center, radius); return center.z+radius.z; } }; sandboxgamemaker-2.7.1+dfsg/src/engine/rendermodel.cpp0000664000175000017500000007670111637730516022736 0ustar showardshoward#include "engine.h" VARP(oqdynent, 0, 1, 1); VARP(animationinterpolationtime, 0, 150, 1000); model *loadingmodel = NULL; #include "ragdoll.h" #include "animmodel.h" #include "vertmodel.h" #include "skelmodel.h" static model *(__cdecl *modeltypes[NUMMODELTYPES])(const char *); static int addmodeltype(int type, model *(__cdecl *loader)(const char *)) { modeltypes[type] = loader; return type; } #define MODELTYPE(modeltype, modelclass) \ static model *__loadmodel__##modelclass(const char *filename) \ { \ return new modelclass(filename); \ } \ static int __dummy__##modelclass = addmodeltype((modeltype), __loadmodel__##modelclass); #include "md2.h" #include "md3.h" #include "md5.h" #include "obj.h" #include "smd.h" #include "iqm.h" MODELTYPE(MDL_MD2, md2); MODELTYPE(MDL_MD3, md3); MODELTYPE(MDL_MD5, md5); MODELTYPE(MDL_OBJ, obj); MODELTYPE(MDL_SMD, smd); MODELTYPE(MDL_IQM, iqm); #define checkmdl if(!loadingmodel) { conoutf(CON_ERROR, "not loading a model"); return; } void mdlcullface(int *cullface) { checkmdl; loadingmodel->setcullface(*cullface!=0); } COMMAND(mdlcullface, "i"); void mdlcollide(int *collide) { checkmdl; loadingmodel->collide = *collide!=0; } COMMAND(mdlcollide, "i"); void mdlellipsecollide(int *collide) { checkmdl; loadingmodel->ellipsecollide = *collide!=0; } COMMAND(mdlellipsecollide, "i"); void mdlspec(int *percent) { checkmdl; float spec = 1.0f; if(*percent>0) spec = *percent/100.0f; else if(*percent<0) spec = 0.0f; loadingmodel->setspec(spec); } COMMAND(mdlspec, "i"); void mdlambient(int *percent) { checkmdl; float ambient = 0.3f; if(*percent>0) ambient = *percent/100.0f; else if(*percent<0) ambient = 0.0f; loadingmodel->setambient(ambient); } COMMAND(mdlambient, "i"); void mdlalphatest(float *cutoff) { checkmdl; loadingmodel->setalphatest(max(0.0f, min(1.0f, *cutoff))); } COMMAND(mdlalphatest, "f"); void mdlalphablend(int *blend) { checkmdl; loadingmodel->setalphablend(*blend!=0); } COMMAND(mdlalphablend, "i"); void mdlalphadepth(int *depth) { checkmdl; loadingmodel->alphadepth = *depth!=0; } COMMAND(mdlalphadepth, "i"); void mdldepthoffset(int *offset) { checkmdl; loadingmodel->depthoffset = *offset!=0; } COMMAND(mdldepthoffset, "i"); void mdlglow(int *percent, int *delta, float *pulse) { checkmdl; float glow = 3.0f, glowdelta = *delta/100.0f, glowpulse = *pulse > 0 ? *pulse/1000.0f : 0; if(*percent>0) glow = *percent/100.0f; else if(*percent<0) glow = 0.0f; glowdelta -= glow; loadingmodel->setglow(glow, glowdelta, glowpulse); } COMMAND(mdlglow, "iif"); void mdlglare(float *specglare, float *glowglare) { checkmdl; loadingmodel->setglare(*specglare, *glowglare); } COMMAND(mdlglare, "ff"); void mdlenvmap(float *envmapmax, float *envmapmin, char *envmap) { checkmdl; loadingmodel->setenvmap(*envmapmin, *envmapmax, envmap[0] ? cubemapload(envmap) : NULL); } COMMAND(mdlenvmap, "ffs"); void mdlfullbright(float *fullbright) { checkmdl; loadingmodel->setfullbright(*fullbright); } COMMAND(mdlfullbright, "f"); void mdlshader(char *shader) { checkmdl; loadingmodel->setshader(lookupshaderbyname(shader)); } COMMAND(mdlshader, "s"); void mdlspin(float *yaw, float *pitch, float *roll) { checkmdl; loadingmodel->spinyaw = *yaw; loadingmodel->spinpitch = *pitch; loadingmodel->spinroll = *roll; } COMMAND(mdlspin, "fff"); void mdlscale(int *percent) { checkmdl; float scale = 0.3f; if(*percent>0) scale = *percent/100.0f; else if(*percent<0) scale = 0.0f; loadingmodel->scale = scale; } COMMAND(mdlscale, "i"); void mdltrans(float *x, float *y, float *z) { checkmdl; loadingmodel->translate = vec(*x, *y, *z); } COMMAND(mdltrans, "fff"); void mdlyaw(float *angle) { checkmdl; loadingmodel->offsetyaw = *angle; } COMMAND(mdlyaw, "f"); void mdlpitch(float *angle) { checkmdl; loadingmodel->offsetpitch = *angle; } COMMAND(mdlpitch, "f"); void mdlroll(float *angle) { checkmdl; loadingmodel->offsetroll = *angle; } COMMAND(mdlroll, "f"); void mdlshadow(int *shadow) { checkmdl; loadingmodel->shadow = *shadow!=0; } COMMAND(mdlshadow, "i"); void mdlbb(float *rad, float *h, float *eyeheight) { checkmdl; loadingmodel->collideradius = *rad; loadingmodel->collideheight = *h; loadingmodel->eyeheight = *eyeheight; } COMMAND(mdlbb, "fff"); void mdlextendbb(float *x, float *y, float *z) { checkmdl; loadingmodel->bbextend = vec(*x, *y, *z); } COMMAND(mdlextendbb, "fff"); void mdlname() { checkmdl; result(loadingmodel->name()); } COMMAND(mdlname, ""); #define checkragdoll \ if(!loadingmodel->skeletal()) { conoutf(CON_ERROR, "not loading a skeletal model"); return; } \ skelmodel *m = (skelmodel *)loadingmodel; \ skelmodel::skelmeshgroup *meshes = (skelmodel::skelmeshgroup *)m->parts.last()->meshes; \ if(!meshes) return; \ skelmodel::skeleton *skel = meshes->skel; \ if(!skel->ragdoll) skel->ragdoll = new ragdollskel; \ ragdollskel *ragdoll = skel->ragdoll; \ if(ragdoll->loaded) return; void rdvert(float *x, float *y, float *z, float *radius) { checkragdoll; ragdollskel::vert &v = ragdoll->verts.add(); v.pos = vec(*x, *y, *z); v.radius = *radius > 0 ? *radius : 1; } COMMAND(rdvert, "ffff"); void rdeye(int *v) { checkragdoll; ragdoll->eye = *v; } COMMAND(rdeye, "i"); void rdtri(int *v1, int *v2, int *v3) { checkragdoll; ragdollskel::tri &t = ragdoll->tris.add(); t.vert[0] = *v1; t.vert[1] = *v2; t.vert[2] = *v3; } COMMAND(rdtri, "iii"); void rdjoint(int *n, int *t, char *v1, char *v2, char *v3) { checkragdoll; if(*n < 0 || *n >= skel->numbones) return; ragdollskel::joint &j = ragdoll->joints.add(); j.bone = *n; j.tri = *t; j.vert[0] = v1[0] ? parseint(v1) : -1; j.vert[1] = v2[0] ? parseint(v2) : -1; j.vert[2] = v3[0] ? parseint(v3) : -1; } COMMAND(rdjoint, "iisss"); void rdlimitdist(int *v1, int *v2, float *mindist, float *maxdist) { checkragdoll; ragdollskel::distlimit &d = ragdoll->distlimits.add(); d.vert[0] = *v1; d.vert[1] = *v2; d.mindist = *mindist; d.maxdist = max(*maxdist, *mindist); } COMMAND(rdlimitdist, "iiff"); void rdlimitrot(int *t1, int *t2, float *maxangle, float *qx, float *qy, float *qz, float *qw) { checkragdoll; ragdollskel::rotlimit &r = ragdoll->rotlimits.add(); r.tri[0] = *t1; r.tri[1] = *t2; r.maxangle = *maxangle * RAD; r.middle = matrix3x3(quat(*qx, *qy, *qz, *qw)); } COMMAND(rdlimitrot, "iifffff"); void rdanimjoints(int *on) { checkragdoll; ragdoll->animjoints = *on!=0; } COMMAND(rdanimjoints, "i"); // mapmodels vector mapmodels; void mmodel(char *name) { mapmodelinfo &mmi = mapmodels.add(); copystring(mmi.name, name); mmi.m = NULL; } void mapmodelcompat(int *rad, int *h, int *tex, char *name, char *shadow) { mmodel(name); } void mapmodelreset(int *n) { if(!(identflags&IDF_OVERRIDDEN) && !game::allowedittoggle()) return; mapmodels.shrink(clamp(*n, 0, mapmodels.length())); } mapmodelinfo &getmminfo(int i) { return mapmodels.inrange(i) ? mapmodels[i] : *(mapmodelinfo *)0; } const char *mapmodelname(int i) { return mapmodels.inrange(i) ? mapmodels[i].name : NULL; } COMMAND(mmodel, "s"); COMMANDN(mapmodel, mapmodelcompat, "iiiss"); COMMAND(mapmodelreset, "i"); ICOMMAND(mapmodelname, "i", (int *index), { result(mapmodels.inrange(*index) ? mapmodels[*index].name : ""); }); ICOMMAND(nummapmodels, "", (), { intret(mapmodels.length()); }); // model registry hashtable mdllookup; vector preloadmodels; void preloadmodel(const char *name) { if(mdllookup.access(name)) return; preloadmodels.add(newstring(name)); } void flushpreloadedmodels() { loopv(preloadmodels) { loadprogress = float(i+1)/preloadmodels.length(); loadmodel(preloadmodels[i], -1, true); } preloadmodels.deletearrays(); loadprogress = 0; } void preloadusedmapmodels(bool msg, bool bih) { vector &ents = entities::getents(); vector mapmodels; loopv(ents) { extentity &e = *ents[i]; if(e.type==ET_MAPMODEL && e.attr[1] >= 0 && mapmodels.find(e.attr[1]) < 0) mapmodels.add(e.attr[1]); } loopv(mapmodels) { loadprogress = float(i+1)/mapmodels.length(); int mmindex = mapmodels[i]; mapmodelinfo &mmi = getmminfo(mmindex); if(!&mmi) { if(msg) conoutf(CON_WARN, "could not find map model: %d", mmindex); } else if(!loadmodel(NULL, mmindex, msg)) { if(msg) conoutf(CON_WARN, "could not load model: %s", mmi.name); } else if(mmi.m && bih) mmi.m->preloadBIH(); } loadprogress = 0; } model *loadmodel(const char *name, int i, bool msg) { if(!name) { if(!mapmodels.inrange(i)) return NULL; mapmodelinfo &mmi = mapmodels[i]; if(mmi.m) return mmi.m; name = mmi.name; } model **mm = mdllookup.access(name); model *m; if(mm) m = *mm; else { if(lightmapping > 1) return NULL; if(msg) { defformatstring(filename)("packages/models/%s", name); renderprogress(loadprogress, filename); } loopi(NUMMODELTYPES) { m = modeltypes[i](name); if(!m) continue; loadingmodel = m; if(m->load()) break; DELETEP(m); } loadingmodel = NULL; if(!m) return NULL; mdllookup.access(m->name(), m); } if(mapmodels.inrange(i) && !mapmodels[i].m) mapmodels[i].m = m; return m; } void preloadmodelshaders() { if(initing) return; enumerate(mdllookup, model *, m, m->preloadshaders()); } void clear_mdls() { enumerate(mdllookup, model *, m, delete m); } void cleanupmodels() { enumerate(mdllookup, model *, m, m->cleanup()); } void clearmodel(char *name) { model **m = mdllookup.access(name); if(!m) { conoutf("model %s is not loaded", name); return; } loopv(mapmodels) if(mapmodels[i].m==*m) mapmodels[i].m = NULL; mdllookup.remove(name); (*m)->cleanup(); delete *m; conoutf("cleared model %s", name); } COMMAND(clearmodel, "s"); bool modeloccluded(const vec ¢er, float radius) { int br = int(radius*2)+1; return pvsoccluded(ivec(int(center.x-radius), int(center.y-radius), int(center.z-radius)), ivec(br, br, br)) || bboccluded(ivec(int(center.x-radius), int(center.y-radius), int(center.z-radius)), ivec(br, br, br)); } VAR(showboundingbox, 0, 0, 2); void render2dbox(vec &o, float x, float y, float z) { glBegin(GL_LINE_LOOP); glVertex3f(o.x, o.y, o.z); glVertex3f(o.x, o.y, o.z+z); glVertex3f(o.x+x, o.y+y, o.z+z); glVertex3f(o.x+x, o.y+y, o.z); glEnd(); } void render3dbox(vec &o, float tofloor, float toceil, float xradius, float yradius) { if(yradius<=0) yradius = xradius; vec c = o; c.sub(vec(xradius, yradius, tofloor)); float xsz = xradius*2, ysz = yradius*2; float h = tofloor+toceil; lineshader->set(); glDisable(GL_TEXTURE_2D); glColor3f(1, 1, 1); render2dbox(c, xsz, 0, h); render2dbox(c, 0, ysz, h); c.add(vec(xsz, ysz, 0)); render2dbox(c, -xsz, 0, h); render2dbox(c, 0, -ysz, h); xtraverts += 16; glEnable(GL_TEXTURE_2D); } void renderellipse(vec &o, float xradius, float yradius, float yaw) { lineshader->set(); glDisable(GL_TEXTURE_2D); glColor3f(0.5f, 0.5f, 0.5f); glBegin(GL_LINE_LOOP); loopi(16) { vec p(xradius*cosf(2*M_PI*i/16.0f), yradius*sinf(2*M_PI*i/16.0f), 0); p.rotate_around_z((yaw+90)*RAD); p.add(o); glVertex3fv(p.v); } glEnd(); glEnable(GL_TEXTURE_2D); } struct batchedmodel { vec pos, color, dir; int anim; float yaw, pitch, roll, transparent; int basetime, basetime2, flags; dynent *d; int attached; occludequery *query; }; struct modelbatch { model *m; int flags; vector batched; }; static vector batches; static vector modelattached; static int numbatches = -1; static occludequery *modelquery = NULL; void startmodelbatches() { numbatches = 0; modelattached.setsize(0); } modelbatch &addbatchedmodel(model *m) { modelbatch *b = NULL; if(m->batch>=0 && m->batchbatch]->m==m) b = batches[m->batch]; else { if(numbatchesbatched.setsize(0); } else b = batches.add(new modelbatch); b->m = m; b->flags = 0; m->batch = numbatches++; } return *b; } void renderbatchedmodel(model *m, batchedmodel &b) { modelattach *a = NULL; if(b.attached>=0) a = &modelattached[b.attached]; int anim = b.anim; if(shadowmapping) { anim |= ANIM_NOSKIN; if(renderpath!=R_FIXEDFUNCTION) setenvparamf("shadowintensity", SHPARAM_VERTEX, 1, b.transparent); } else { if(b.flags&MDL_FULLBRIGHT) anim |= ANIM_FULLBRIGHT; if(b.flags&MDL_GHOST) anim |= ANIM_GHOST; } m->render(anim, b.basetime, b.basetime2, b.pos, b.yaw, b.pitch, b.roll, b.d, a, b.color, b.dir, b.transparent); } struct transparentmodel { model *m; batchedmodel *batched; float dist; }; static inline bool sorttransparentmodels(const transparentmodel &x, const transparentmodel &y) { return x.dist < y.dist; } void endmodelbatches() { vector transparent; loopi(numbatches) { modelbatch &b = *batches[i]; if(b.batched.empty()) continue; if(b.flags&(MDL_SHADOW|MDL_DYNSHADOW)) { vec center, bbradius; b.m->boundbox(0/*frame*/, center, bbradius); // FIXME loopvj(b.batched) { batchedmodel &bm = b.batched[j]; if(bm.flags&(MDL_SHADOW|MDL_DYNSHADOW)) renderblob(bm.flags&MDL_DYNSHADOW ? BLOB_DYNAMIC : BLOB_STATIC, bm.d && bm.d->ragdoll ? bm.d->ragdoll->center : bm.pos, bm.d ? bm.d->radius : max(bbradius.x, bbradius.y), bm.transparent); } flushblobs(); } bool rendered = false; occludequery *query = NULL; if(b.flags&MDL_GHOST) { loopvj(b.batched) { batchedmodel &bm = b.batched[j]; if((bm.flags&(MDL_CULL_VFC|MDL_GHOST))!=MDL_GHOST || bm.query) continue; if(!rendered) { b.m->startrender(); rendered = true; } renderbatchedmodel(b.m, bm); } if(rendered) { b.m->endrender(); rendered = false; } } loopvj(b.batched) { batchedmodel &bm = b.batched[j]; if(bm.flags&(MDL_CULL_VFC|MDL_GHOST)) continue; if(bm.query!=query) { if(query) endquery(query); query = bm.query; if(query) startquery(query); } if(bm.transparent < 1 && (!query || query->owner==bm.d) && !shadowmapping) { transparentmodel &tm = transparent.add(); tm.m = b.m; tm.batched = &bm; tm.dist = camera1->o.dist(bm.d && bm.d->ragdoll ? bm.d->ragdoll->center : bm.pos); continue; } if(!rendered) { b.m->startrender(); rendered = true; } renderbatchedmodel(b.m, bm); } if(query) endquery(query); if(rendered) b.m->endrender(); } if(transparent.length()) { transparent.sort(sorttransparentmodels); model *lastmodel = NULL; occludequery *query = NULL; loopv(transparent) { transparentmodel &tm = transparent[i]; if(lastmodel!=tm.m) { if(lastmodel) lastmodel->endrender(); (lastmodel = tm.m)->startrender(); } if(query!=tm.batched->query) { if(query) endquery(query); query = tm.batched->query; if(query) startquery(query); } renderbatchedmodel(tm.m, *tm.batched); } if(query) endquery(query); if(lastmodel) lastmodel->endrender(); } numbatches = -1; } void startmodelquery(occludequery *query) { modelquery = query; } void endmodelquery() { int querybatches = 0; loopi(numbatches) { modelbatch &b = *batches[i]; if(b.batched.empty() || b.batched.last().query!=modelquery) continue; querybatches++; } if(querybatches<=1) { if(!querybatches) modelquery->fragments = 0; modelquery = NULL; return; } int minattached = modelattached.length(); startquery(modelquery); loopi(numbatches) { modelbatch &b = *batches[i]; if(b.batched.empty() || b.batched.last().query!=modelquery) continue; b.m->startrender(); do { batchedmodel &bm = b.batched.pop(); if(bm.attached>=0) minattached = min(minattached, bm.attached); renderbatchedmodel(b.m, bm); } while(b.batched.length() && b.batched.last().query==modelquery); b.m->endrender(); } endquery(modelquery); modelquery = NULL; modelattached.setsize(minattached); } VARP(maxmodelradiusdistance, 10, 200, 1000); void rendermodelquery(model *m, dynent *d, const vec ¢er, float radius) { if(fabs(camera1->o.x-center.x) < radius+1 && fabs(camera1->o.y-center.y) < radius+1 && fabs(camera1->o.z-center.z) < radius+1) { d->query = NULL; return; } d->query = newquery(d); if(!d->query) return; nocolorshader->set(); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); startquery(d->query); int br = int(radius*2)+1; drawbb(ivec(int(center.x-radius), int(center.y-radius), int(center.z-radius)), ivec(br, br, br)); endquery(d->query); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, fading ? GL_FALSE : GL_TRUE); glDepthMask(GL_TRUE); } extern int oqfrags; void rendermodel(entitylight *light, const char *mdl, int anim, const vec &o, float yaw, float pitch, float roll, int flags, dynent *d, modelattach *a, int basetime, int basetime2, float trans, int colour) { if(shadowmapping && !(flags&(MDL_SHADOW|MDL_DYNSHADOW))) return; model *m = loadmodel(mdl); if(!m) return; vec center(0, 0, 0), bbradius(0, 0, 0); float radius = 0; bool shadow = !shadowmap && !glaring && (flags&(MDL_SHADOW|MDL_DYNSHADOW)) && showblobs, doOQ = flags&MDL_CULL_QUERY && hasOQ && oqfrags && oqdynent; if(flags&(MDL_CULL_VFC|MDL_CULL_DIST|MDL_CULL_OCCLUDED|MDL_CULL_QUERY|MDL_SHADOW|MDL_DYNSHADOW)) { m->boundbox(0/*frame*/, center, bbradius); // FIXME radius = bbradius.magnitude(); if(d && d->ragdoll) { radius = max(radius, d->ragdoll->radius); center = d->ragdoll->center; } else { center.rotate_around_z(yaw*RAD); center.add(o); } if(flags&MDL_CULL_DIST && center.dist(camera1->o)/radius>maxmodelradiusdistance) return; if(flags&MDL_CULL_VFC) { if(reflecting || refracting) { if(reflecting || refracting>0) { if(center.z+radius<=reflectz) return; } else { if(fogging && center.z+radius=reflectz) return; } if(center.dist(camera1->o)-radius>reflectdist) return; } if(isfoggedsphere(radius, center)) return; if(shadowmapping && !isshadowmapcaster(center, radius)) return; } if(shadowmapping) { if(d) { if(flags&MDL_CULL_OCCLUDED && d->occluded>=OCCLUDE_PARENT) return; if(doOQ && d->occluded+1>=OCCLUDE_BB && d->query && d->query->owner==d && checkquery(d->query)) return; } if(!addshadowmapcaster(center, radius, radius)) return; } else if(flags&MDL_CULL_OCCLUDED && modeloccluded(center, radius)) { if(!reflecting && !refracting && d) { d->occluded = OCCLUDE_PARENT; if(doOQ) rendermodelquery(m, d, center, radius); } return; } else if(doOQ && d && d->query && d->query->owner==d && checkquery(d->query)) { if(!reflecting && !refracting) { if(d->occludedoccluded++; rendermodelquery(m, d, center, radius); } return; } } if(flags&MDL_NORENDER) anim |= ANIM_NORENDER; else if(showboundingbox && !shadowmapping && !reflecting && !refracting && editmode) { if(d && showboundingbox==1) { render3dbox(d->o, d->eyeheight, d->aboveeye, d->radius); renderellipse(d->o, d->xradius, d->yradius, d->yaw); } else { vec center, radius; if(showboundingbox==1) m->collisionbox(0, center, radius); else m->boundbox(0, center, radius); rotatebb(center, radius, int(yaw)); center.add(o); render3dbox(center, radius.z, radius.z, radius.x, radius.y); } } vec lightcolor(1, 1, 1), lightdir(0, 0, 1); if(!shadowmapping) { vec pos = o; if(d) { if(!reflecting && !refracting) d->occluded = OCCLUDE_NOTHING; if(!light) light = &d->light; if(flags&MDL_LIGHT && light->millis!=lastmillis) { if(d->ragdoll) { pos = d->ragdoll->center; pos.z += radius/2; } else if(d->type < ENT_CAMERA) pos.z += 0.75f*(d->eyeheight + d->aboveeye); lightreaching(pos, light->color, light->dir, (flags&MDL_LIGHT_FAST)!=0); dynlightreaching(pos, light->color, light->dir, (flags&MDL_HUD)!=0); game::lighteffects(d, light->color, light->dir); light->millis = lastmillis; } } else if(flags&MDL_LIGHT) { if(!light) { lightreaching(pos, lightcolor, lightdir, (flags&MDL_LIGHT_FAST)!=0); dynlightreaching(pos, lightcolor, lightdir, (flags&MDL_HUD)!=0); } else if(light->millis!=lastmillis) { lightreaching(pos, light->color, light->dir, (flags&MDL_LIGHT_FAST)!=0); dynlightreaching(pos, light->color, light->dir, (flags&MDL_HUD)!=0); light->millis = lastmillis; } } if(light) { lightcolor = light->color; lightdir = light->dir; } if(flags&MDL_DYNLIGHT) dynlightreaching(pos, lightcolor, lightdir, (flags&MDL_HUD)!=0); } if(a) for(int i = 0; a[i].tag; i++) { if(a[i].name) a[i].m = loadmodel(a[i].name); //if(a[i].m && a[i].m->type()!=m->type()) a[i].m = NULL; } if(!d || reflecting || refracting || shadowmapping) doOQ = false; lightcolor.mul(vec((colour >> 16) & 0xFF, (colour >> 8) & 0xFF, colour & 0xFF).div(255.0f)); if(numbatches>=0) { modelbatch &mb = addbatchedmodel(m); batchedmodel &b = mb.batched.add(); b.query = modelquery; b.pos = o; b.color = lightcolor; b.dir = lightdir; b.anim = anim; b.yaw = yaw; b.pitch = pitch; b.roll = roll; b.basetime = basetime; b.basetime2 = basetime2; b.transparent = trans; b.flags = flags & ~(MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED); if(!shadow || reflecting || refracting>0) { b.flags &= ~(MDL_SHADOW|MDL_DYNSHADOW); if((flags&MDL_CULL_VFC) && refracting<0 && center.z-radius>=reflectz) b.flags |= MDL_CULL_VFC; } mb.flags |= b.flags; b.d = d; b.attached = a ? modelattached.length() : -1; if(a) for(int i = 0;; i++) { modelattached.add(a[i]); if(!a[i].tag) break; } if(doOQ) d->query = b.query = newquery(d); return; } if(shadow && !reflecting && refracting<=0) { renderblob(flags&MDL_DYNSHADOW ? BLOB_DYNAMIC : BLOB_STATIC, d && d->ragdoll ? center : o, d ? d->radius : max(bbradius.x, bbradius.y), trans); flushblobs(); if((flags&MDL_CULL_VFC) && refracting<0 && center.z-radius>=reflectz) return; } m->startrender(); if(shadowmapping) { anim |= ANIM_NOSKIN; if(renderpath!=R_FIXEDFUNCTION) setenvparamf("shadowintensity", SHPARAM_VERTEX, 1, trans); } else { if(flags&MDL_FULLBRIGHT) anim |= ANIM_FULLBRIGHT; if(flags&MDL_GHOST) anim |= ANIM_GHOST; } if(doOQ) { d->query = newquery(d); if(d->query) startquery(d->query); } m->render(anim, basetime, basetime2, o, yaw, pitch, roll, d, a, lightcolor, lightdir, trans); if(doOQ && d->query) endquery(d->query); m->endrender(); } void abovemodel(vec &o, const char *mdl) { model *m = loadmodel(mdl); if(!m) return; o.z += m->above(0/*frame*/); } bool matchanim(const char *name, const char *pattern) { for(;; pattern++) { const char *s = name; char c; for(;; pattern++) { c = *pattern; if(!c || c=='|') break; else if(c=='*') { if(!*s || isspace(*s)) break; do s++; while(*s && !isspace(*s)); } else if(c!=*s) break; else s++; } if(!*s && (!c || c=='|')) return true; pattern = strchr(pattern, '|'); if(!pattern) break; } return false; } void findanims(const char *pattern, vector &anims) { loopi(sizeof(animnames)/sizeof(animnames[0])) if(matchanim(animnames[i], pattern)) anims.add(i); } ICOMMAND(findanims, "s", (char *name), { vector anims; findanims(name, anims); vector buf; string num; loopv(anims) { formatstring(num)("%d", anims[i]); if(i > 0) buf.add(' '); buf.put(num, strlen(num)); } buf.add('\0'); result(buf.getbuf()); }); void loadskin(const char *dir, const char *altdir, Texture *&skin, Texture *&masks) // model skin sharing { #define ifnoload(tex, path) if((tex = textureload(path, 0, true, false))==notexture) #define tryload(tex, prefix, cmd, name) \ ifnoload(tex, makerelpath(mdir, name "", prefix, cmd)) \ { \ ifnoload(tex, makerelpath(maltdir, name "", prefix, cmd)) return; \ } defformatstring(mdir)("packages/models/%s", dir); defformatstring(maltdir)("packages/models/%s", altdir); masks = notexture; tryload(skin, NULL, NULL, "skin"); tryload(masks, "", NULL, "masks"); } // convenient function that covers the usual anims for players/monsters/npcs VAR(animoverride, -1, 0, NUMANIMS-1); VAR(testanims, 0, 0, 1); VAR(testpitch, -90, 0, 90); void renderclient(dynent *d, const char *mdlname, modelattach *attachments, int hold, int attack, int attackdelay, int lastaction, int lastpain, float fade, bool ragdoll, int colour) { int anim = hold ? hold : ANIM_IDLE|ANIM_LOOP; float yaw = testanims && d==player ? 0 : d->yaw+90, pitch = testpitch && d==player ? testpitch : d->pitch; vec o = d->feetpos(); int basetime = 0; if(animoverride) anim = (animoverride<0 ? ANIM_ALL : animoverride)|ANIM_LOOP; else if(d->state==CS_DEAD) { anim = ANIM_DYING|ANIM_NOPITCH; basetime = lastpain; if(ragdoll) { if(!d->ragdoll || d->ragdoll->millis < basetime) anim |= ANIM_RAGDOLL; } else if(lastmillis-basetime>1000) anim = ANIM_DEAD|ANIM_LOOP|ANIM_NOPITCH; } else if(d->state==CS_EDITING || d->state==CS_SPECTATOR) anim = ANIM_EDIT|ANIM_LOOP; else if(d->state==CS_LAGGED) anim = ANIM_LAG|ANIM_LOOP; else { if(lastmillis-lastpain < 300) { anim = ANIM_PAIN; basetime = lastpain; } else if(lastpain < lastaction && (attack < 0 || (d->type != ENT_AI && lastmillis-lastaction < attackdelay))) { anim = attack < 0 ? -attack : attack; basetime = lastaction; } if(d->inwater && d->physstate<=PHYS_FALL) anim |= (((game::allowmove(d) && (d->move || d->strafe)) || d->vel.z+d->falling.z>0 ? ANIM_SWIM : ANIM_SINK)|ANIM_LOOP)<timeinair>100) anim |= (ANIM_JUMP|ANIM_END)<move || d->strafe)) { if(d->move>0) anim |= (ANIM_FORWARD|ANIM_LOOP)<strafe) anim |= ((d->strafe>0 ? ANIM_LEFT : ANIM_RIGHT)|ANIM_LOOP)<move<0) anim |= (ANIM_BACKWARD|ANIM_LOOP)<>ANIM_SECONDARY)&ANIM_INDEX) anim >>= ANIM_SECONDARY; } if(d->ragdoll && (!ragdoll || (anim&ANIM_INDEX)!=ANIM_DYING)) DELETEP(d->ragdoll); if(!((anim>>ANIM_SECONDARY)&ANIM_INDEX)) anim |= (ANIM_IDLE|ANIM_LOOP)<type==ENT_PLAYER) flags |= MDL_FULLBRIGHT; else flags |= MDL_CULL_DIST; if(d->state==CS_LAGGED) fade = min(fade, 0.3f); else flags |= MDL_DYNSHADOW; rendermodel(NULL, mdlname, anim, o, yaw, pitch, d->roll, flags, d, attachments, basetime, 0, fade, colour); } void setbbfrommodel(dynent *d, const char *mdl) { model *m = loadmodel(mdl); if(!m) return; vec center, radius; m->collisionbox(0, center, radius); if(d->type==ENT_INANIMATE && !m->ellipsecollide) { d->collidetype = COLLIDE_OBB; //d->collidetype = COLLIDE_AABB; //rotatebb(center, radius, int(d->yaw)); } d->xradius = radius.x + fabs(center.x); d->yradius = radius.y + fabs(center.y); d->radius = d->collidetype==COLLIDE_OBB ? sqrtf(d->xradius*d->xradius + d->yradius*d->yradius) : max(d->xradius, d->yradius); d->eyeheight = (center.z-radius.z) + radius.z*2*m->eyeheight; d->aboveeye = radius.z*2*(1.0f-m->eyeheight); } sandboxgamemaker-2.7.1+dfsg/src/engine/rendergl.cpp0000664000175000017500000026457711642642476022255 0ustar showardshoward// rendergl.cpp: core opengl rendering stuff #include "engine.h" bool hasVBO = false, hasDRE = false, hasOQ = false, hasTR = false, hasFBO = false, hasDS = false, hasTF = false, hasBE = false, hasBC = false, hasCM = false, hasNP2 = false, hasTC = false, hasTE = false, hasMT = false, hasD3 = false, hasAF = false, hasVP2 = false, hasVP3 = false, hasPP = false, hasMDA = false, hasTE3 = false, hasTE4 = false, hasVP = false, hasFP = false, hasGLSL = false, hasGM = false, hasNVFB = false, hasSGIDT = false, hasSGISH = false, hasDT = false, hasSH = false, hasNVPCF = false, hasRN = false, hasPBO = false, hasFBB = false, hasUBO = false, hasBUE = false, hasFC = false, hasTEX = false; int hasstencil = 0; VAR(renderpath, 1, 0, 0); // GL_ARB_vertex_buffer_object, GL_ARB_pixel_buffer_object PFNGLGENBUFFERSARBPROC glGenBuffers_ = NULL; PFNGLBINDBUFFERARBPROC glBindBuffer_ = NULL; PFNGLMAPBUFFERARBPROC glMapBuffer_ = NULL; PFNGLUNMAPBUFFERARBPROC glUnmapBuffer_ = NULL; PFNGLBUFFERDATAARBPROC glBufferData_ = NULL; PFNGLBUFFERSUBDATAARBPROC glBufferSubData_ = NULL; PFNGLDELETEBUFFERSARBPROC glDeleteBuffers_ = NULL; PFNGLGETBUFFERSUBDATAARBPROC glGetBufferSubData_ = NULL; // GL_ARB_multitexture PFNGLACTIVETEXTUREARBPROC glActiveTexture_ = NULL; PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTexture_ = NULL; PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2f_ = NULL; PFNGLMULTITEXCOORD3FARBPROC glMultiTexCoord3f_ = NULL; PFNGLMULTITEXCOORD4FARBPROC glMultiTexCoord4f_ = NULL; // GL_ARB_vertex_program, GL_ARB_fragment_program PFNGLGENPROGRAMSARBPROC glGenPrograms_ = NULL; PFNGLDELETEPROGRAMSARBPROC glDeletePrograms_ = NULL; PFNGLBINDPROGRAMARBPROC glBindProgram_ = NULL; PFNGLPROGRAMSTRINGARBPROC glProgramString_ = NULL; PFNGLGETPROGRAMIVARBPROC glGetProgramiv_ = NULL; PFNGLPROGRAMENVPARAMETER4FARBPROC glProgramEnvParameter4f_ = NULL; PFNGLPROGRAMENVPARAMETER4FVARBPROC glProgramEnvParameter4fv_ = NULL; PFNGLENABLEVERTEXATTRIBARRAYARBPROC glEnableVertexAttribArray_ = NULL; PFNGLDISABLEVERTEXATTRIBARRAYARBPROC glDisableVertexAttribArray_ = NULL; PFNGLVERTEXATTRIBPOINTERARBPROC glVertexAttribPointer_ = NULL; // GL_EXT_gpu_program_parameters PFNGLPROGRAMENVPARAMETERS4FVEXTPROC glProgramEnvParameters4fv_ = NULL; PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC glProgramLocalParameters4fv_ = NULL; // GL_ARB_occlusion_query PFNGLGENQUERIESARBPROC glGenQueries_ = NULL; PFNGLDELETEQUERIESARBPROC glDeleteQueries_ = NULL; PFNGLBEGINQUERYARBPROC glBeginQuery_ = NULL; PFNGLENDQUERYARBPROC glEndQuery_ = NULL; PFNGLGETQUERYIVARBPROC glGetQueryiv_ = NULL; PFNGLGETQUERYOBJECTIVARBPROC glGetQueryObjectiv_ = NULL; PFNGLGETQUERYOBJECTUIVARBPROC glGetQueryObjectuiv_ = NULL; // GL_EXT_framebuffer_object PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbuffer_ = NULL; PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffers_ = NULL; PFNGLGENFRAMEBUFFERSEXTPROC glGenRenderbuffers_ = NULL; PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorage_ = NULL; PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatus_ = NULL; PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebuffer_ = NULL; PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffers_ = NULL; PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffers_ = NULL; PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2D_ = NULL; PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbuffer_ = NULL; PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmap_ = NULL; // GL_EXT_framebuffer_blit PFNGLBLITFRAMEBUFFEREXTPROC glBlitFramebuffer_ = NULL; // GL_ARB_shading_language_100, GL_ARB_shader_objects, GL_ARB_fragment_shader, GL_ARB_vertex_shader PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObject_ = NULL; PFNGLDELETEOBJECTARBPROC glDeleteObject_ = NULL; PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObject_ = NULL; PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObject_ = NULL; PFNGLSHADERSOURCEARBPROC glShaderSource_ = NULL; PFNGLCOMPILESHADERARBPROC glCompileShader_ = NULL; PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameteriv_ = NULL; PFNGLATTACHOBJECTARBPROC glAttachObject_ = NULL; PFNGLGETINFOLOGARBPROC glGetInfoLog_ = NULL; PFNGLLINKPROGRAMARBPROC glLinkProgram_ = NULL; PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocation_ = NULL; PFNGLUNIFORM1FARBPROC glUniform1f_ = NULL; PFNGLUNIFORM2FARBPROC glUniform2f_ = NULL; PFNGLUNIFORM3FARBPROC glUniform3f_ = NULL; PFNGLUNIFORM4FARBPROC glUniform4f_ = NULL; PFNGLUNIFORM1FVARBPROC glUniform1fv_ = NULL; PFNGLUNIFORM2FVARBPROC glUniform2fv_ = NULL; PFNGLUNIFORM3FVARBPROC glUniform3fv_ = NULL; PFNGLUNIFORM4FVARBPROC glUniform4fv_ = NULL; PFNGLUNIFORM1IARBPROC glUniform1i_ = NULL; PFNGLBINDATTRIBLOCATIONARBPROC glBindAttribLocation_ = NULL; PFNGLGETACTIVEUNIFORMARBPROC glGetActiveUniform_ = NULL; // GL_EXT_draw_range_elements PFNGLDRAWRANGEELEMENTSEXTPROC glDrawRangeElements_ = NULL; // GL_EXT_blend_minmax PFNGLBLENDEQUATIONEXTPROC glBlendEquation_ = NULL; // GL_EXT_blend_color PFNGLBLENDCOLOREXTPROC glBlendColor_ = NULL; // GL_EXT_multi_draw_arrays PFNGLMULTIDRAWARRAYSEXTPROC glMultiDrawArrays_ = NULL; PFNGLMULTIDRAWELEMENTSEXTPROC glMultiDrawElements_ = NULL; // GL_ARB_texture_compression PFNGLCOMPRESSEDTEXIMAGE3DARBPROC glCompressedTexImage3D_ = NULL; PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glCompressedTexImage2D_ = NULL; PFNGLCOMPRESSEDTEXIMAGE1DARBPROC glCompressedTexImage1D_ = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC glCompressedTexSubImage3D_ = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC glCompressedTexSubImage2D_ = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC glCompressedTexSubImage1D_ = NULL; PFNGLGETCOMPRESSEDTEXIMAGEARBPROC glGetCompressedTexImage_ = NULL; // GL_ARB_uniform_buffer_object PFNGLGETUNIFORMINDICESPROC glGetUniformIndices_ = NULL; PFNGLGETACTIVEUNIFORMSIVPROC glGetActiveUniformsiv_ = NULL; PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex_ = NULL; PFNGLGETACTIVEUNIFORMBLOCKIVPROC glGetActiveUniformBlockiv_ = NULL; PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding_ = NULL; PFNGLBINDBUFFERBASEPROC glBindBufferBase_ = NULL; PFNGLBINDBUFFERRANGEPROC glBindBufferRange_ = NULL; // GL_EXT_bindable_uniform PFNGLUNIFORMBUFFEREXTPROC glUniformBuffer_ = NULL; PFNGLGETUNIFORMBUFFERSIZEEXTPROC glGetUniformBufferSize_ = NULL; PFNGLGETUNIFORMOFFSETEXTPROC glGetUniformOffset_ = NULL; // GL_EXT_fog_coord PFNGLFOGCOORDPOINTEREXTPROC glFogCoordPointer_ = NULL; void *getprocaddress(const char *name) { return SDL_GL_GetProcAddress(name); } VARP(ati_skybox_bug, 0, 0, 1); VAR(ati_oq_bug, 0, 0, 1); VAR(ati_minmax_bug, 0, 0, 1); VAR(ati_dph_bug, 0, 0, 1); VAR(ati_line_bug, 0, 0, 1); VAR(ati_cubemap_bug, 0, 0, 1); VAR(ati_ubo_bug, 0, 0, 1); VAR(nvidia_scissor_bug, 0, 0, 1); VAR(apple_glsldepth_bug, 0, 0, 1); VAR(apple_ff_bug, 0, 0, 1); VAR(apple_vp_bug, 0, 0, 1); VAR(sdl_backingstore_bug, -1, 0, 1); VAR(intel_quadric_bug, 0, 0, 1); VAR(mesa_program_bug, 0, 0, 1); VAR(avoidshaders, 1, 0, 0); VAR(minimizetcusage, 1, 0, 0); VAR(emulatefog, 1, 0, 0); VAR(usevp2, 1, 0, 0); VAR(usevp3, 1, 0, 0); VAR(usetexrect, 1, 0, 0); VAR(hasglsl, 1, 0, 0); VAR(useubo, 1, 0, 0); VAR(usebue, 1, 0, 0); VAR(rtscissor, 0, 1, 1); VAR(blurtile, 0, 1, 1); VAR(rtsharefb, 0, 1, 1); static bool checkseries(const char *s, int low, int high) { while(*s && !isdigit(*s)) ++s; if(!*s) return false; int n = 0; while(isdigit(*s)) n = n*10 + (*s++ - '0'); return n >= low && n < high; } VAR(dbgexts, 0, 0, 1); bool hasext(const char *exts, const char *ext) { int len = strlen(ext); for(const char *cur = exts; (cur = strstr(cur, ext)); cur += len) { if((cur == exts || cur[-1] == ' ') && (cur[len] == ' ' || !cur[len])) return true; } return false; } void gl_checkextensions() { const char *vendor = (const char *)glGetString(GL_VENDOR); const char *exts = (const char *)glGetString(GL_EXTENSIONS); const char *renderer = (const char *)glGetString(GL_RENDERER); const char *version = (const char *)glGetString(GL_VERSION); conoutf(CON_INIT, "Renderer: %s (%s)", renderer, vendor); conoutf(CON_INIT, "Driver: %s", version); #ifdef __APPLE__ extern int mac_osversion(); int osversion = mac_osversion(); /* 0x1050 = 10.5 (Leopard) */ sdl_backingstore_bug = -1; #endif //extern int shaderprecision; // default to low precision shaders on certain cards, can be overridden with -f3 // char *weakcards[] = { "GeForce FX", "Quadro FX", "6200", "9500", "9550", "9600", "9700", "9800", "X300", "X600", "FireGL", "Intel", "Chrome", NULL } // if(shaderprecision==2) for(char **wc = weakcards; *wc; wc++) if(strstr(renderer, *wc)) shaderprecision = 1; if(hasext(exts, "GL_EXT_texture_env_combine") || hasext(exts, "GL_ARB_texture_env_combine")) { hasTE = true; if(hasext(exts, "GL_ARB_texture_env_crossbar")) hasTEX = true; if(hasext(exts, "GL_ATI_texture_env_combine3")) hasTE3 = true; if(hasext(exts, "GL_NV_texture_env_combine4")) hasTE4 = true; if(hasext(exts, "GL_EXT_texture_env_dot3") || hasext(exts, "GL_ARB_texture_env_dot3")) hasD3 = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_env_combine extension."); } else conoutf(CON_WARN, "WARNING: No texture_env_combine extension! (your video card is WAY too old)"); if(hasext(exts, "GL_ARB_multitexture")) { glActiveTexture_ = (PFNGLACTIVETEXTUREARBPROC) getprocaddress("glActiveTextureARB"); glClientActiveTexture_ = (PFNGLCLIENTACTIVETEXTUREARBPROC)getprocaddress("glClientActiveTextureARB"); glMultiTexCoord2f_ = (PFNGLMULTITEXCOORD2FARBPROC) getprocaddress("glMultiTexCoord2fARB"); glMultiTexCoord3f_ = (PFNGLMULTITEXCOORD3FARBPROC) getprocaddress("glMultiTexCoord3fARB"); glMultiTexCoord4f_ = (PFNGLMULTITEXCOORD4FARBPROC) getprocaddress("glMultiTexCoord4fARB"); hasMT = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_multitexture extension."); } else conoutf(CON_WARN, "WARNING: No multitexture extension!"); if(hasext(exts, "GL_ARB_vertex_buffer_object")) { hasVBO = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_vertex_buffer_object extension."); } else conoutf(CON_WARN, "WARNING: No vertex_buffer_object extension! (geometry heavy maps will be SLOW)"); #ifdef __APPLE__ /* VBOs over 256KB seem to destroy performance on 10.5, but not in 10.6 */ extern int maxvbosize; if(osversion < 0x1060) maxvbosize = min(maxvbosize, 8192); #endif if(hasext(exts, "GL_ARB_pixel_buffer_object")) { hasPBO = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_pixel_buffer_object extension."); } if(hasVBO || hasPBO) { glGenBuffers_ = (PFNGLGENBUFFERSARBPROC) getprocaddress("glGenBuffersARB"); glBindBuffer_ = (PFNGLBINDBUFFERARBPROC) getprocaddress("glBindBufferARB"); glMapBuffer_ = (PFNGLMAPBUFFERARBPROC) getprocaddress("glMapBufferARB"); glUnmapBuffer_ = (PFNGLUNMAPBUFFERARBPROC) getprocaddress("glUnmapBufferARB"); glBufferData_ = (PFNGLBUFFERDATAARBPROC) getprocaddress("glBufferDataARB"); glBufferSubData_ = (PFNGLBUFFERSUBDATAARBPROC) getprocaddress("glBufferSubDataARB"); glDeleteBuffers_ = (PFNGLDELETEBUFFERSARBPROC) getprocaddress("glDeleteBuffersARB"); glGetBufferSubData_ = (PFNGLGETBUFFERSUBDATAARBPROC)getprocaddress("glGetBufferSubDataARB"); } if(hasext(exts, "GL_EXT_draw_range_elements")) { glDrawRangeElements_ = (PFNGLDRAWRANGEELEMENTSEXTPROC)getprocaddress("glDrawRangeElementsEXT"); hasDRE = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_draw_range_elements extension."); } if(hasext(exts, "GL_EXT_multi_draw_arrays")) { glMultiDrawArrays_ = (PFNGLMULTIDRAWARRAYSEXTPROC) getprocaddress("glMultiDrawArraysEXT"); glMultiDrawElements_ = (PFNGLMULTIDRAWELEMENTSEXTPROC)getprocaddress("glMultiDrawElementsEXT"); hasMDA = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_multi_draw_arrays extension."); } #ifdef __APPLE__ // floating point FBOs not fully supported until 10.5 if(osversion>=0x1050) #endif if(hasext(exts, "GL_ARB_texture_float") || hasext(exts, "GL_ATI_texture_float")) { hasTF = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_float extension."); shadowmap = 1; extern int smoothshadowmappeel; smoothshadowmappeel = 1; } if(hasext(exts, "GL_NV_float_buffer")) { hasNVFB = true; if(dbgexts) conoutf(CON_INIT, "Using GL_NV_float_buffer extension."); } if(hasext(exts, "GL_EXT_framebuffer_object")) { glBindRenderbuffer_ = (PFNGLBINDRENDERBUFFEREXTPROC) getprocaddress("glBindRenderbufferEXT"); glDeleteRenderbuffers_ = (PFNGLDELETERENDERBUFFERSEXTPROC) getprocaddress("glDeleteRenderbuffersEXT"); glGenRenderbuffers_ = (PFNGLGENFRAMEBUFFERSEXTPROC) getprocaddress("glGenRenderbuffersEXT"); glRenderbufferStorage_ = (PFNGLRENDERBUFFERSTORAGEEXTPROC) getprocaddress("glRenderbufferStorageEXT"); glCheckFramebufferStatus_ = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) getprocaddress("glCheckFramebufferStatusEXT"); glBindFramebuffer_ = (PFNGLBINDFRAMEBUFFEREXTPROC) getprocaddress("glBindFramebufferEXT"); glDeleteFramebuffers_ = (PFNGLDELETEFRAMEBUFFERSEXTPROC) getprocaddress("glDeleteFramebuffersEXT"); glGenFramebuffers_ = (PFNGLGENFRAMEBUFFERSEXTPROC) getprocaddress("glGenFramebuffersEXT"); glFramebufferTexture2D_ = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) getprocaddress("glFramebufferTexture2DEXT"); glFramebufferRenderbuffer_ = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)getprocaddress("glFramebufferRenderbufferEXT"); glGenerateMipmap_ = (PFNGLGENERATEMIPMAPEXTPROC) getprocaddress("glGenerateMipmapEXT"); hasFBO = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_framebuffer_object extension."); if(hasext(exts, "GL_EXT_framebuffer_blit")) { glBlitFramebuffer_ = (PFNGLBLITFRAMEBUFFEREXTPROC) getprocaddress("glBlitFramebufferEXT"); hasFBB = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_framebuffer_blit extension."); } } else conoutf(CON_WARN, "WARNING: No framebuffer object support. (reflective water may be slow)"); #if defined(__APPLE__) // Intel HD3000 broke occlusion queries - either causing software fallback, or returning wrong results if(!strstr(vendor, "Intel")) #endif if(hasext(exts, "GL_ARB_occlusion_query")) { GLint bits; glGetQueryiv_ = (PFNGLGETQUERYIVARBPROC)getprocaddress("glGetQueryivARB"); glGetQueryiv_(GL_SAMPLES_PASSED_ARB, GL_QUERY_COUNTER_BITS_ARB, &bits); if(bits) { glGenQueries_ = (PFNGLGENQUERIESARBPROC) getprocaddress("glGenQueriesARB"); glDeleteQueries_ = (PFNGLDELETEQUERIESARBPROC) getprocaddress("glDeleteQueriesARB"); glBeginQuery_ = (PFNGLBEGINQUERYARBPROC) getprocaddress("glBeginQueryARB"); glEndQuery_ = (PFNGLENDQUERYARBPROC) getprocaddress("glEndQueryARB"); glGetQueryObjectiv_ = (PFNGLGETQUERYOBJECTIVARBPROC) getprocaddress("glGetQueryObjectivARB"); glGetQueryObjectuiv_ = (PFNGLGETQUERYOBJECTUIVARBPROC)getprocaddress("glGetQueryObjectuivARB"); hasOQ = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_occlusion_query extension."); #if defined(__APPLE__) && SDL_BYTEORDER == SDL_BIG_ENDIAN if(strstr(vendor, "ATI") && (osversion<0x1050)) ati_oq_bug = 1; #endif //if(ati_oq_bug) conoutf(CON_WARN, "WARNING: Using ATI occlusion query bug workaround. (use \"/ati_oq_bug 0\" to disable if unnecessary)"); } } if(!hasOQ) { conoutf(CON_WARN, "WARNING: No occlusion query support! (large maps may be SLOW)"); extern int vacubesize; vacubesize = 64; waterreflect = 0; } extern int reservedynlighttc, reserveshadowmaptc, batchlightmaps, ffdynlights, fpdepthfx; if(strstr(vendor, "ATI")) { //conoutf(CON_WARN, "WARNING: ATI cards may show garbage in skybox. (use \"/ati_skybox_bug 1\" to fix)"); reservedynlighttc = 2; reserveshadowmaptc = 3; minimizetcusage = 1; emulatefog = 1; if(hasTF && hasNVFB) fpdepthfx = 1; } else if(strstr(vendor, "NVIDIA")) { reservevpparams = 10; rtsharefb = 0; // work-around for strange driver stalls involving when using many FBOs extern int filltjoints; if(!hasext(exts, "GL_EXT_gpu_shader4")) filltjoints = 0; // DX9 or less NV cards seem to not cause many sparklies if(hasFBO && !hasTF) nvidia_scissor_bug = 1; // 5200 bug, clearing with scissor on an FBO messes up on reflections, may affect lesser cards too extern int fpdepthfx; if(hasTF && (!strstr(renderer, "GeForce") || !checkseries(renderer, 6000, 6600))) fpdepthfx = 1; // FP filtering causes software fallback on 6200? } else if(strstr(vendor, "Intel")) { avoidshaders = 1; intel_quadric_bug = 1; maxtexsize = 256; reservevpparams = 20; batchlightmaps = 0; ffdynlights = 0; if(!hasOQ) waterrefract = 0; #ifdef __APPLE__ apple_vp_bug = 1; #endif } else if(strstr(vendor, "Tungsten") || strstr(vendor, "Mesa") || strstr(vendor, "DRI") || strstr(vendor, "Microsoft") || strstr(vendor, "S3 Graphics")) { avoidshaders = 1; maxtexsize = 256; reservevpparams = 20; batchlightmaps = 0; ffdynlights = 0; if(!hasOQ) waterrefract = 0; } if(hasext(exts, "GL_ARB_vertex_program") && hasext(exts, "GL_ARB_fragment_program")) { hasVP = hasFP = true; glGenPrograms_ = (PFNGLGENPROGRAMSARBPROC) getprocaddress("glGenProgramsARB"); glDeletePrograms_ = (PFNGLDELETEPROGRAMSARBPROC) getprocaddress("glDeleteProgramsARB"); glBindProgram_ = (PFNGLBINDPROGRAMARBPROC) getprocaddress("glBindProgramARB"); glProgramString_ = (PFNGLPROGRAMSTRINGARBPROC) getprocaddress("glProgramStringARB"); glGetProgramiv_ = (PFNGLGETPROGRAMIVARBPROC) getprocaddress("glGetProgramivARB"); glProgramEnvParameter4f_ = (PFNGLPROGRAMENVPARAMETER4FARBPROC) getprocaddress("glProgramEnvParameter4fARB"); glProgramEnvParameter4fv_ = (PFNGLPROGRAMENVPARAMETER4FVARBPROC) getprocaddress("glProgramEnvParameter4fvARB"); glEnableVertexAttribArray_ = (PFNGLENABLEVERTEXATTRIBARRAYARBPROC) getprocaddress("glEnableVertexAttribArrayARB"); glDisableVertexAttribArray_ = (PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) getprocaddress("glDisableVertexAttribArrayARB"); glVertexAttribPointer_ = (PFNGLVERTEXATTRIBPOINTERARBPROC) getprocaddress("glVertexAttribPointerARB"); if(strstr(vendor, "ATI")) ati_dph_bug = ati_line_bug = 1; else if(strstr(vendor, "Tungsten")) mesa_program_bug = 1; #ifdef __APPLE__ if(osversion>=0x1050) // fixed in 1055 for some hardware.. but not all.. { apple_ff_bug = 1; //conoutf(CON_WARN, "WARNING: Using Leopard ARB_position_invariant bug workaround. (use \"/apple_ff_bug 0\" to disable if unnecessary)"); } #endif } if(hasext(exts, "GL_ARB_shading_language_100") && hasext(exts, "GL_ARB_shader_objects") && hasext(exts, "GL_ARB_vertex_shader") && hasext(exts, "GL_ARB_fragment_shader")) { glCreateProgramObject_ = (PFNGLCREATEPROGRAMOBJECTARBPROC) getprocaddress("glCreateProgramObjectARB"); glDeleteObject_ = (PFNGLDELETEOBJECTARBPROC) getprocaddress("glDeleteObjectARB"); glUseProgramObject_ = (PFNGLUSEPROGRAMOBJECTARBPROC) getprocaddress("glUseProgramObjectARB"); glCreateShaderObject_ = (PFNGLCREATESHADEROBJECTARBPROC) getprocaddress("glCreateShaderObjectARB"); glShaderSource_ = (PFNGLSHADERSOURCEARBPROC) getprocaddress("glShaderSourceARB"); glCompileShader_ = (PFNGLCOMPILESHADERARBPROC) getprocaddress("glCompileShaderARB"); glGetObjectParameteriv_ = (PFNGLGETOBJECTPARAMETERIVARBPROC) getprocaddress("glGetObjectParameterivARB"); glAttachObject_ = (PFNGLATTACHOBJECTARBPROC) getprocaddress("glAttachObjectARB"); glGetInfoLog_ = (PFNGLGETINFOLOGARBPROC) getprocaddress("glGetInfoLogARB"); glLinkProgram_ = (PFNGLLINKPROGRAMARBPROC) getprocaddress("glLinkProgramARB"); glGetUniformLocation_ = (PFNGLGETUNIFORMLOCATIONARBPROC) getprocaddress("glGetUniformLocationARB"); glUniform1f_ = (PFNGLUNIFORM1FARBPROC) getprocaddress("glUniform1fARB"); glUniform2f_ = (PFNGLUNIFORM2FARBPROC) getprocaddress("glUniform2fARB"); glUniform3f_ = (PFNGLUNIFORM3FARBPROC) getprocaddress("glUniform3fARB"); glUniform4f_ = (PFNGLUNIFORM4FARBPROC) getprocaddress("glUniform4fARB"); glUniform1fv_ = (PFNGLUNIFORM1FVARBPROC) getprocaddress("glUniform1fvARB"); glUniform2fv_ = (PFNGLUNIFORM2FVARBPROC) getprocaddress("glUniform2fvARB"); glUniform3fv_ = (PFNGLUNIFORM3FVARBPROC) getprocaddress("glUniform3fvARB"); glUniform4fv_ = (PFNGLUNIFORM4FVARBPROC) getprocaddress("glUniform4fvARB"); glUniform1i_ = (PFNGLUNIFORM1IARBPROC) getprocaddress("glUniform1iARB"); glBindAttribLocation_ = (PFNGLBINDATTRIBLOCATIONARBPROC) getprocaddress("glBindAttribLocationARB"); glGetActiveUniform_ = (PFNGLGETACTIVEUNIFORMARBPROC) getprocaddress("glGetActiveUniformARB"); if(!hasVP || !hasFP) { glEnableVertexAttribArray_ = (PFNGLENABLEVERTEXATTRIBARRAYARBPROC) getprocaddress("glEnableVertexAttribArrayARB"); glDisableVertexAttribArray_ = (PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) getprocaddress("glDisableVertexAttribArrayARB"); glVertexAttribPointer_ = (PFNGLVERTEXATTRIBPOINTERARBPROC) getprocaddress("glVertexAttribPointerARB"); } extern bool checkglslsupport(); if(checkglslsupport()) { hasGLSL = true; hasglsl = 1; #ifdef __APPLE__ //if(osversion<0x1050) ?? if(hasVP && hasFP) apple_glsldepth_bug = 1; #endif //if(apple_glsldepth_bug) conoutf(CON_WARN, "WARNING: Using Apple GLSL depth bug workaround. (use \"/apple_glsldepth_bug 0\" to disable if unnecessary"); } } bool hasshaders = (hasVP && hasFP) || hasGLSL; if(hasshaders) { extern int matskel; if(!avoidshaders) matskel = 0; } if(hasext(exts, "GL_NV_vertex_program2_option")) { usevp2 = 1; hasVP2 = true; } if(hasext(exts, "GL_NV_vertex_program3")) { usevp3 = 1; hasVP3 = true; } if(hasext(exts, "GL_EXT_gpu_program_parameters")) { glProgramEnvParameters4fv_ = (PFNGLPROGRAMENVPARAMETERS4FVEXTPROC) getprocaddress("glProgramEnvParameters4fvEXT"); glProgramLocalParameters4fv_ = (PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC)getprocaddress("glProgramLocalParameters4fvEXT"); hasPP = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_gpu_program_parameters extension."); } if(hasext(exts, "GL_ARB_uniform_buffer_object")) { glGetUniformIndices_ = (PFNGLGETUNIFORMINDICESPROC) getprocaddress("glGetUniformIndices"); glGetActiveUniformsiv_ = (PFNGLGETACTIVEUNIFORMSIVPROC) getprocaddress("glGetActiveUniformsiv"); glGetUniformBlockIndex_ = (PFNGLGETUNIFORMBLOCKINDEXPROC) getprocaddress("glGetUniformBlockIndex"); glGetActiveUniformBlockiv_ = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)getprocaddress("glGetActiveUniformBlockiv"); glUniformBlockBinding_ = (PFNGLUNIFORMBLOCKBINDINGPROC) getprocaddress("glUniformBlockBinding"); glBindBufferBase_ = (PFNGLBINDBUFFERBASEPROC) getprocaddress("glBindBufferBase"); glBindBufferRange_ = (PFNGLBINDBUFFERRANGEPROC) getprocaddress("glBindBufferRange"); useubo = 1; hasUBO = true; if(strstr(vendor, "ATI")) ati_ubo_bug = 1; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_uniform_buffer_object extension."); } else if(hasext(exts, "GL_EXT_bindable_uniform")) { glUniformBuffer_ = (PFNGLUNIFORMBUFFEREXTPROC) getprocaddress("glUniformBufferEXT"); glGetUniformBufferSize_ = (PFNGLGETUNIFORMBUFFERSIZEEXTPROC)getprocaddress("glGetUniformBufferSizeEXT"); glGetUniformOffset_ = (PFNGLGETUNIFORMOFFSETEXTPROC) getprocaddress("glGetUniformOffsetEXT"); usebue = 1; hasBUE = true; if(strstr(vendor, "ATI")) ati_ubo_bug = 1; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_bindable_uniform extension."); } if(hasext(exts, "GL_EXT_texture_rectangle") || hasext(exts, "GL_ARB_texture_rectangle")) { usetexrect = 1; hasTR = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_rectangle extension."); } else if(hasMT && hasshaders) conoutf(CON_WARN, "WARNING: No texture rectangle support. (no full screen shaders)"); if(hasext(exts, "GL_EXT_packed_depth_stencil") || hasext(exts, "GL_NV_packed_depth_stencil")) { hasDS = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_packed_depth_stencil extension."); } if(hasext(exts, "GL_EXT_blend_minmax")) { glBlendEquation_ = (PFNGLBLENDEQUATIONEXTPROC) getprocaddress("glBlendEquationEXT"); hasBE = true; if(strstr(vendor, "ATI")) ati_minmax_bug = 1; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_blend_minmax extension."); } if(hasext(exts, "GL_EXT_blend_color")) { glBlendColor_ = (PFNGLBLENDCOLOREXTPROC) getprocaddress("glBlendColorEXT"); hasBC = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_blend_color extension."); } if(hasext(exts, "GL_EXT_fog_coord")) { glFogCoordPointer_ = (PFNGLFOGCOORDPOINTEREXTPROC) getprocaddress("glFogCoordPointerEXT"); hasFC = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_fog_coord extension."); } if(hasext(exts, "GL_ARB_texture_cube_map")) { GLint val; glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, &val); hwcubetexsize = val; hasCM = true; // On Catalyst 10.2, issuing an occlusion query on the first draw using a given cubemap texture causes a nasty crash if(strstr(vendor, "ATI")) ati_cubemap_bug = 1; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_cube_map extension."); } else conoutf(CON_WARN, "WARNING: No cube map texture support. (no reflective glass)"); extern int usenp2; if(hasext(exts, "GL_ARB_texture_non_power_of_two")) { hasNP2 = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_non_power_of_two extension."); } else if(usenp2) conoutf(CON_WARN, "WARNING: Non-power-of-two textures not supported!"); if(hasext(exts, "GL_ARB_texture_compression") && hasext(exts, "GL_EXT_texture_compression_s3tc")) { glCompressedTexImage3D_ = (PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) getprocaddress("glCompressedTexImage3DARB"); glCompressedTexImage2D_ = (PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) getprocaddress("glCompressedTexImage2DARB"); glCompressedTexImage1D_ = (PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) getprocaddress("glCompressedTexImage1DARB"); glCompressedTexSubImage3D_ = (PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC)getprocaddress("glCompressedTexSubImage3DARB"); glCompressedTexSubImage2D_ = (PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC)getprocaddress("glCompressedTexSubImage2DARB"); glCompressedTexSubImage1D_ = (PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC)getprocaddress("glCompressedTexSubImage1DARB"); glGetCompressedTexImage_ = (PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) getprocaddress("glGetCompressedTexImageARB"); hasTC = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_texture_compression_s3tc extension."); } if(hasext(exts, "GL_EXT_texture_filter_anisotropic")) { GLint val; glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &val); hwmaxaniso = val; hasAF = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_texture_filter_anisotropic extension."); } if(hasext(exts, "GL_SGIS_generate_mipmap")) { hasGM = true; if(dbgexts) conoutf(CON_INIT, "Using GL_SGIS_generate_mipmap extension."); } if(hasext(exts, "GL_ARB_depth_texture")) { hasSGIDT = hasDT = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_depth_texture extension."); } else if(hasext(exts, "GL_SGIX_depth_texture")) { hasSGIDT = true; if(dbgexts) conoutf(CON_INIT, "Using GL_SGIX_depth_texture extension."); } if(hasext(exts, "GL_ARB_shadow")) { hasSGISH = hasSH = true; if(strstr(vendor, "NVIDIA") || strstr(renderer, "Radeon HD")) hasNVPCF = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_shadow extension."); } else if(hasext(exts, "GL_SGIX_shadow")) { hasSGISH = true; if(dbgexts) conoutf(CON_INIT, "Using GL_SGIX_shadow extension."); } if(hasext(exts, "GL_EXT_rescale_normal")) { hasRN = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_rescale_normal extension."); } if(!hasSGIDT && !hasSGISH) shadowmap = 0; if(hasext(exts, "GL_EXT_gpu_shader4") && !avoidshaders) { // on DX10 or above class cards (i.e. GF8 or RadeonHD) enable expensive features extern int grass, glare, maxdynlights, depthfxsize, depthfxrect, depthfxfilter, blurdepthfx; grass = 1; if(hasOQ) { waterfallrefract = 1; glare = 1; maxdynlights = MAXDYNLIGHTS; if(hasTR) { depthfxsize = 10; depthfxrect = 1; depthfxfilter = 0; blurdepthfx = 0; } } } GLint val; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &val); hwtexsize = val; } void glext(char *ext) { const char *exts = (const char *)glGetString(GL_EXTENSIONS); intret(hasext(exts, ext) ? 1 : 0); } COMMAND(glext, "s"); void gl_init(int w, int h, int bpp, int depth, int fsaa) { glViewport(0, 0, w, h); glClearColor(0, 0, 0, 0); glClearDepth(1); glDepthFunc(GL_LESS); glDisable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); glDisable(GL_FOG); glFogi(GL_FOG_MODE, GL_LINEAR); //glHint(GL_FOG_HINT, GL_NICEST); GLfloat fogcolor[4] = { 0, 0, 0, 0 }; glFogfv(GL_FOG_COLOR, fogcolor); glEnable(GL_LINE_SMOOTH); //glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glFrontFace(GL_CW); glCullFace(GL_BACK); glDisable(GL_CULL_FACE); #ifdef __APPLE__ if(sdl_backingstore_bug) { if(fsaa) { sdl_backingstore_bug = 1; // since SDL doesn't add kCGLPFABackingStore to the pixelformat and so it isn't guaranteed to be preserved - only manifests when using fsaa? //conoutf(CON_WARN, "WARNING: Using SDL backingstore workaround. (use \"/sdl_backingstore_bug 0\" to disable if unnecessary)"); } else sdl_backingstore_bug = -1; } #endif extern int useshaders, forceglsl; bool hasshaders = (hasVP && hasFP) || hasGLSL; if(!useshaders || (useshaders<0 && avoidshaders) || !hasMT || !hasshaders) { if(!hasMT || !hasshaders) conoutf(CON_WARN, "WARNING: No shader support! Using fixed-function fallback. (no fancy visuals for you)"); else if(useshaders<0 && !hasTF) conoutf(CON_WARN, "WARNING: Disabling shaders for extra performance. (use \"/shaders 1\" to enable shaders if desired)"); renderpath = R_FIXEDFUNCTION; } else renderpath = hasGLSL ? (!hasVP || !hasFP || forceglsl > 0 ? R_GLSLANG : R_ASMGLSLANG) : R_ASMSHADER; static const char * const rpnames[4] = { "fixed-function", "assembly shader", "GLSL shader", "assembly/GLSL shader" }; conoutf(CON_INIT, "Rendering using the OpenGL %s path.", rpnames[renderpath]); inittmus(); setuptexcompress(); } void cleanupgl() { extern int nomasks, nolights, nowater; nomasks = nolights = nowater = 0; extern void cleanupmotionblur(); cleanupmotionblur(); extern void clearminimap(); clearminimap(); } #define VARRAY_INTERNAL #include "varray.h" VAR(wireframe, 0, 0, 1); ICOMMAND(getcamyaw, "", (), floatret(camera1->yaw)); ICOMMAND(getcampitch, "", (), floatret(camera1->pitch)); ICOMMAND(getcamroll, "", (), floatret(camera1->roll)); ICOMMAND(getcampos, "", (), { defformatstring(pos)("%s %s %s", floatstr(camera1->o.x), floatstr(camera1->o.y), floatstr(camera1->o.z)); result(pos); }); vec worldpos, camdir, camright, camup; void findorientation() { float yaw, pitch; #ifdef NEWGUI if(editmode) { float x, y; UI::getcursorpos(x, y); vec dir1 = invmvpmatrix.perspectivetransform(vec(x*2-1, 1-2*y, 2-1)), dir2 = invmvpmatrix.perspectivetransform(vec(x*2-1, 1-2*y, -1)); camdir = dir1.sub(dir2).normalize(); vectoyawpitch(camdir, yaw, pitch); } else #endif { yaw = camera1->yaw; pitch = camera1->pitch; vecfromyawpitch(yaw, pitch, 1, 0, camdir); } vecfromyawpitch(yaw, 0, 0, -1, camright); vecfromyawpitch(yaw, pitch+90, 1, 0, camup); if(raycubepos(camera1->o, camdir, worldpos, 0, RAY_CLIPMAT|RAY_SKIPFIRST) == -1) worldpos = vec(camdir).mul(2*worldsize).add(camera1->o); //otherwise 3dgui won't work when outside of map } void transplayer() { // move from RH to Z-up LH quake style worldspace glLoadMatrixf(viewmatrix.v); glRotatef(camera1->roll, 0, 1, 0); glRotatef(camera1->pitch, -1, 0, 0); glRotatef(camera1->yaw, 0, 0, -1); glTranslatef(-camera1->o.x, -camera1->o.y, -camera1->o.z); } float curfov = 100, curavatarfov = 65, fovy, aspect; int farplane; VARP(zoominvel, 0, 250, 5000); VARP(zoomoutvel, 0, 100, 5000); VARP(zoomfov, 10, 35, 60); VARP(fov, 10, 100, 150); VAR(avatarzoomfov, 10, 25, 60); VAR(avatarfov, 10, 65, 150); FVAR(avatardepth, 0, 0.5f, 1); static int zoommillis = 0; VARF(zoom, -1, 0, 1, if(zoom) zoommillis = totalmillis; ); void disablezoom() { zoom = 0; zoommillis = totalmillis; } void computezoom() { if(!zoom) { curfov = fov; curavatarfov = avatarfov; return; } if(zoom < 0 && curfov >= fov) { zoom = 0; curfov = fov; curavatarfov = avatarfov; return; } // don't zoom-out if not zoomed-in int zoomvel = zoom > 0 ? zoominvel : zoomoutvel, oldfov = zoom > 0 ? fov : zoomfov, newfov = zoom > 0 ? zoomfov : fov, oldavatarfov = zoom > 0 ? avatarfov : avatarzoomfov, newavatarfov = zoom > 0 ? avatarzoomfov : avatarfov; float t = zoomvel ? float(zoomvel - (totalmillis - zoommillis)) / zoomvel : 0; if(t <= 0) { if(!zoomvel && fabs(newfov - curfov) >= 1) { curfov = newfov; curavatarfov = newavatarfov; } zoom = max(zoom, 0); } else { curfov = oldfov*t + newfov*(1 - t); curavatarfov = oldavatarfov*t + newavatarfov*(1 - t); } } FVARP(zoomsens, 1e-3f, 1, 1000); FVARP(zoomaccel, 0, 0, 1000); VARP(zoomautosens, 0, 1, 1); FVARP(sensitivity, 1e-3f, 3, 1000); FVARP(sensitivityscale, 1e-3f, 1, 1000); VARP(invmouse, 0, 0, 1); FVARP(mouseaccel, 0, 0, 1000); VARP(thirdperson, 0, 0, 2); FVARP(thirdpersondistance, 0, 20, 1000); physent *camera1 = NULL; bool detachedcamera = false; bool isthirdperson() { return player!=camera1 || detachedcamera || reflecting; } void fixcamerarange() { const float MAXPITCH = 90.0f; if(camera1->pitch>MAXPITCH) camera1->pitch = MAXPITCH; if(camera1->pitch<-MAXPITCH) camera1->pitch = -MAXPITCH; while(camera1->yaw<0.0f) camera1->yaw += 360.0f; while(camera1->yaw>=360.0f) camera1->yaw -= 360.0f; } void mousemove(int dx, int dy) { float cursens = sensitivity, curaccel = mouseaccel; if(zoom) { if(zoomautosens) { cursens = float(sensitivity*zoomfov)/fov; curaccel = float(mouseaccel*zoomfov)/fov; } else { cursens = zoomsens; curaccel = zoomaccel; } } if(curaccel && curtime && (dx || dy)) cursens += curaccel * sqrtf(dx*dx + dy*dy)/curtime; cursens /= 33.0f*sensitivityscale; dy *= (invmouse ? -1 : 1); if(game::mousemove(dx, dy, cursens)) { fixcamerarange(); return; //game processed mouse movement, don't bother } camera1->yaw += dx*cursens; camera1->pitch -= dy*cursens; fixcamerarange(); if(camera1!=player && !detachedcamera) { player->yaw = camera1->yaw; player->pitch = camera1->pitch; } } void recomputecamera() { game::setupcamera(); computezoom(); static physent tempcamera; if(!game::recomputecamera(camera1, tempcamera, detachedcamera, thirdpersondistance)) { bool shoulddetach = thirdperson > 1 || game::detachcamera(); if(!thirdperson && !shoulddetach) { camera1 = player; detachedcamera = false; } else { camera1 = &tempcamera; if(detachedcamera && shoulddetach) camera1->o = player->o; else { *camera1 = *player; detachedcamera = shoulddetach; } camera1->reset(); camera1->type = ENT_CAMERA; camera1->collidetype = COLLIDE_AABB; camera1->move = -1; camera1->eyeheight = camera1->aboveeye = camera1->radius = camera1->xradius = camera1->yradius = 2; vec dir; vecfromyawpitch(camera1->yaw, camera1->pitch, -1, 0, dir); if(game::collidecamera()) { movecamera(camera1, dir, thirdpersondistance, 1); movecamera(camera1, dir, clamp(thirdpersondistance - camera1->o.dist(player->o), 0.0f, 1.0f), 0.1f); } else camera1->o.add(vec(dir).mul(thirdpersondistance)); } } setviewcell(camera1->o); } extern const glmatrixf viewmatrix(vec4(-1, 0, 0, 0), vec4(0, 0, 1, 0), vec4(0, -1, 0, 0)); glmatrixf mvmatrix, projmatrix, mvpmatrix, invmvmatrix, invmvpmatrix; void readmatrices() { glGetFloatv(GL_MODELVIEW_MATRIX, mvmatrix.v); glGetFloatv(GL_PROJECTION_MATRIX, projmatrix.v); mvpmatrix.mul(projmatrix, mvmatrix); invmvmatrix.invert(mvmatrix); invmvpmatrix.invert(mvpmatrix); } FVAR(nearplane, 1e-3f, 0.54f, 1e3f); void project(float fovy, float aspect, int farplane, bool flipx = false, bool flipy = false, bool swapxy = false, float zscale = 1) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); if(swapxy) glRotatef(90, 0, 0, 1); if(flipx || flipy!=swapxy || zscale!=1) glScalef(flipx ? -1 : 1, flipy!=swapxy ? -1 : 1, zscale); GLdouble ydist = nearplane * tan(fovy/2*RAD), xdist = ydist * aspect; glFrustum(-xdist, xdist, -ydist, ydist, nearplane, farplane); glMatrixMode(GL_MODELVIEW); } vec calcavatarpos(const vec &pos, float dist) { vec eyepos; mvmatrix.transform(pos, eyepos); GLdouble ydist = nearplane * tan(curavatarfov/2*RAD), xdist = ydist * aspect; vec4 scrpos; scrpos.x = eyepos.x*nearplane/xdist; scrpos.y = eyepos.y*nearplane/ydist; scrpos.z = (eyepos.z*(farplane + nearplane) - 2*nearplane*farplane) / (farplane - nearplane); scrpos.w = -eyepos.z; vec worldpos = invmvpmatrix.perspectivetransform(scrpos); vec dir = vec(worldpos).sub(camera1->o).rescale(dist); return dir.add(camera1->o); } VAR(reflectclip, 0, 6, 64); VAR(reflectclipavatar, -64, 0, 64); glmatrixf clipmatrix; static const glmatrixf dummymatrix; static int projectioncount = 0; void pushprojection(const glmatrixf &m = dummymatrix) { glMatrixMode(GL_PROJECTION); if(projectioncount <= 0) glPushMatrix(); if(&m != &dummymatrix) glLoadMatrixf(m.v); if(fogging) { glMultMatrixf(mvmatrix.v); glMultMatrixf(invfogmatrix.v); } glMatrixMode(GL_MODELVIEW); projectioncount++; } void popprojection() { --projectioncount; glMatrixMode(GL_PROJECTION); glPopMatrix(); if(projectioncount > 0) { glPushMatrix(); if(fogging) { glMultMatrixf(mvmatrix.v); glMultMatrixf(invfogmatrix.v); } } glMatrixMode(GL_MODELVIEW); } FVAR(polygonoffsetfactor, -1e4f, -3.0f, 1e4f); FVAR(polygonoffsetunits, -1e4f, -3.0f, 1e4f); FVAR(depthoffset, -1e4f, 0.01f, 1e4f); void enablepolygonoffset(GLenum type) { if(!depthoffset) { glPolygonOffset(polygonoffsetfactor, polygonoffsetunits); glEnable(type); return; } bool clipped = reflectz < 1e15f && reflectclip; glmatrixf offsetmatrix = clipped ? clipmatrix : projmatrix; offsetmatrix[14] += depthoffset * projmatrix[10]; glMatrixMode(GL_PROJECTION); if(!clipped) glPushMatrix(); glLoadMatrixf(offsetmatrix.v); if(fogging) { glMultMatrixf(mvmatrix.v); glMultMatrixf(invfogmatrix.v); } glMatrixMode(GL_MODELVIEW); } void disablepolygonoffset(GLenum type) { if(!depthoffset) { glDisable(type); return; } bool clipped = reflectz < 1e15f && reflectclip; glMatrixMode(GL_PROJECTION); if(clipped) { glLoadMatrixf(clipmatrix.v); if(fogging) { glMultMatrixf(mvmatrix.v); glMultMatrixf(invfogmatrix.v); } } else glPopMatrix(); glMatrixMode(GL_MODELVIEW); } void calcspherescissor(const vec ¢er, float size, float &sx1, float &sy1, float &sx2, float &sy2) { vec worldpos(center); if(reflecting) worldpos.z = 2*reflectz - worldpos.z; vec e(mvmatrix.transformx(worldpos), mvmatrix.transformy(worldpos), mvmatrix.transformz(worldpos)); if(e.z > 2*size) { sx1 = sy1 = 1; sx2 = sy2 = -1; return; } float zzrr = e.z*e.z - size*size, dx = e.x*e.x + zzrr, dy = e.y*e.y + zzrr, focaldist = 1.0f/tan(fovy*0.5f*RAD); sx1 = sy1 = -1; sx2 = sy2 = 1; #define CHECKPLANE(c, dir, focaldist, low, high) \ do { \ float nzc = (cz*cz + 1) / (cz dir drt) - cz, \ pz = (d##c)/(nzc*e.c - e.z); \ if(pz > 0) \ { \ float c = (focaldist)*nzc, \ pc = pz*nzc; \ if(pc < e.c) low = c; \ else if(pc > e.c) high = c; \ } \ } while(0) if(dx > 0) { float cz = e.x/e.z, drt = sqrtf(dx)/size; CHECKPLANE(x, -, focaldist/aspect, sx1, sx2); CHECKPLANE(x, +, focaldist/aspect, sx1, sx2); } if(dy > 0) { float cz = e.y/e.z, drt = sqrtf(dy)/size; CHECKPLANE(y, -, focaldist, sy1, sy2); CHECKPLANE(y, +, focaldist, sy1, sy2); } } static int scissoring = 0; static GLint oldscissor[4]; int pushscissor(float sx1, float sy1, float sx2, float sy2) { scissoring = 0; if(sx1 <= -1 && sy1 <= -1 && sx2 >= 1 && sy2 >= 1) return 0; sx1 = max(sx1, -1.0f); sy1 = max(sy1, -1.0f); sx2 = min(sx2, 1.0f); sy2 = min(sy2, 1.0f); GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); int sx = viewport[0] + int(floor((sx1+1)*0.5f*viewport[2])), sy = viewport[1] + int(floor((sy1+1)*0.5f*viewport[3])), sw = viewport[0] + int(ceil((sx2+1)*0.5f*viewport[2])) - sx, sh = viewport[1] + int(ceil((sy2+1)*0.5f*viewport[3])) - sy; if(sw <= 0 || sh <= 0) return 0; if(glIsEnabled(GL_SCISSOR_TEST)) { glGetIntegerv(GL_SCISSOR_BOX, oldscissor); sw += sx; sh += sy; sx = max(sx, int(oldscissor[0])); sy = max(sy, int(oldscissor[1])); sw = min(sw, int(oldscissor[0] + oldscissor[2])) - sx; sh = min(sh, int(oldscissor[1] + oldscissor[3])) - sy; if(sw <= 0 || sh <= 0) return 0; scissoring = 2; } else scissoring = 1; glScissor(sx, sy, sw, sh); if(scissoring<=1) glEnable(GL_SCISSOR_TEST); return scissoring; } void popscissor() { if(scissoring>1) glScissor(oldscissor[0], oldscissor[1], oldscissor[2], oldscissor[3]); else if(scissoring) glDisable(GL_SCISSOR_TEST); scissoring = 0; } glmatrixf envmatrix; void setenvmatrix() { envmatrix = fogging ? fogmatrix : mvmatrix; if(reflecting) envmatrix.reflectz(reflectz); envmatrix.transpose(); } VARR(fog, 16, 4000, 1000024); bvec fogcolor(0x80, 0x99, 0xB3); HVARFR(fogcolour, 0, 0x8099B3, 0xFFFFFF, { fogcolor = bvec((fogcolour>>16)&0xFF, (fogcolour>>8)&0xFF, fogcolour&0xFF); }); static float findsurface(int fogmat, const vec &v, int &abovemat) { ivec o(v), co; int csize; do { cube &c = lookupcube(o.x, o.y, o.z, 0, co, csize); int mat = c.material&MATF_VOLUME; if(mat != fogmat) { abovemat = isliquid(mat) ? mat : MAT_AIR; return o.z; } o.z = co.z + csize; } while(o.z < worldsize); abovemat = MAT_AIR; return worldsize; } static void blendfog(int fogmat, float blend, float logblend, float &start, float &end, float *fogc) { switch(fogmat) { case MAT_WATER: loopk(3) fogc[k] += blend*watercolor[k]/255.0f; end += logblend*min(fog, max(waterfog*4, 32)); break; case MAT_LAVA: loopk(3) fogc[k] += blend*lavacolor[k]/255.0f; end += logblend*min(fog, max(lavafog*4, 32)); break; default: loopk(3) fogc[k] += blend*fogcolor[k]/255.0f; start += logblend*(fog+64)/8; end += logblend*fog; break; } } static void setfog(int fogmat, float below = 1, int abovemat = MAT_AIR) { float fogc[4] = { 0, 0, 0, 1 }; float start = 0, end = 0; float logscale = 256, logblend = log(1 + (logscale - 1)*below) / log(logscale); blendfog(fogmat, below, logblend, start, end, fogc); if(below < 1) blendfog(abovemat, 1-below, 1-logblend, start, end, fogc); glFogf(GL_FOG_START, start); glFogf(GL_FOG_END, end); glFogfv(GL_FOG_COLOR, fogc); glClearColor(fogc[0], fogc[1], fogc[2], 1.0f); } static void blendfogoverlay(int fogmat, float blend, float *overlay) { float maxc; switch(fogmat) { case MAT_WATER: maxc = max(watercolor[0], max(watercolor[1], watercolor[2])); loopk(3) overlay[k] += blend*max(0.4f, watercolor[k]/min(32.0f + maxc*7.0f/8.0f, 255.0f)); break; case MAT_LAVA: maxc = max(lavacolor[0], max(lavacolor[1], lavacolor[2])); loopk(3) overlay[k] += blend*max(0.4f, lavacolor[k]/min(32.0f + maxc*7.0f/8.0f, 255.0f)); break; default: loopk(3) overlay[k] += blend; break; } } void drawfogoverlay(int fogmat, float fogblend, int abovemat) { notextureshader->set(); glDisable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_ZERO, GL_SRC_COLOR); float overlay[3] = { 0, 0, 0 }; blendfogoverlay(fogmat, fogblend, overlay); blendfogoverlay(abovemat, 1-fogblend, overlay); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glColor3fv(overlay); glBegin(GL_TRIANGLE_STRIP); glVertex2f(-1, -1); glVertex2f(1, -1); glVertex2f(-1, 1); glVertex2f(1, 1); glEnd(); glDisable(GL_BLEND); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glEnable(GL_TEXTURE_2D); defaultshader->set(); } bool renderedgame = false; void rendergame(bool mainpass) { game::rendergame(mainpass); if(!shadowmapping) renderedgame = true; } VARP(skyboxglare, 0, 1, 1); void drawglare() { glaring = true; refracting = -1; float oldfogstart, oldfogend, oldfogcolor[4], zerofog[4] = { 0, 0, 0, 1 }; glGetFloatv(GL_FOG_START, &oldfogstart); glGetFloatv(GL_FOG_END, &oldfogend); glGetFloatv(GL_FOG_COLOR, oldfogcolor); glFogf(GL_FOG_START, (fog+64)/8); glFogf(GL_FOG_END, fog); glFogfv(GL_FOG_COLOR, zerofog); glClearColor(0, 0, 0, 1); glClear((skyboxglare ? 0 : GL_COLOR_BUFFER_BIT) | GL_DEPTH_BUFFER_BIT); rendergeom(); if(skyboxglare) drawskybox(farplane, false); renderreflectedmapmodels(); rendergame(); if(!isthirdperson()) { project(curavatarfov, aspect, farplane, false, false, false, avatardepth); game::renderavatar(); project(fovy, aspect, farplane); } renderwater(); rendermaterials(); renderalphageom(); renderparticles(); glFogf(GL_FOG_START, oldfogstart); glFogf(GL_FOG_END, oldfogend); glFogfv(GL_FOG_COLOR, oldfogcolor); refracting = 0; glaring = false; } VARP(reflectmms, 0, 1, 1); VARR(refractsky, 0, 0, 1); glmatrixf fogmatrix, invfogmatrix; void drawreflection(float z, bool refract) { reflectz = z < 0 ? 1e16f : z; reflecting = !refract; refracting = refract ? (z < 0 || camera1->o.z >= z ? -1 : 1) : 0; fading = renderpath!=R_FIXEDFUNCTION && waterrefract && waterfade && hasFBO && z>=0; fogging = refracting<0 && z>=0; float oldfogstart, oldfogend, oldfogcolor[4]; glGetFloatv(GL_FOG_START, &oldfogstart); glGetFloatv(GL_FOG_END, &oldfogend); glGetFloatv(GL_FOG_COLOR, oldfogcolor); if(fogging) { glFogf(GL_FOG_START, camera1->o.z - z); glFogf(GL_FOG_END, camera1->o.z - (z-waterfog)); GLfloat m[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -camera1->o.x, -camera1->o.y, -camera1->o.z, 1 }; memcpy(fogmatrix.v, m, sizeof(m)); invfogmatrix.invert(fogmatrix); pushprojection(); glPushMatrix(); glLoadMatrixf(fogmatrix.v); float fogc[4] = { watercolor.x/255.0f, watercolor.y/255.0f, watercolor.z/255.0f, 1.0f }; glFogfv(GL_FOG_COLOR, fogc); } else { glFogf(GL_FOG_START, (fog+64)/8); glFogf(GL_FOG_END, fog); float fogc[4] = { fogcolor.x/255.0f, fogcolor.y/255.0f, fogcolor.z/255.0f, 1.0f }; glFogfv(GL_FOG_COLOR, fogc); } if(fading) { float scale = fogging ? -0.25f : 0.25f, offset = 2*fabs(scale) - scale*z; setenvparamf("waterfadeparams", SHPARAM_VERTEX, 8, scale, offset, -scale, offset + camera1->o.z*scale); setenvparamf("waterfadeparams", SHPARAM_PIXEL, 8, scale, offset, -scale, offset + camera1->o.z*scale); } if(reflecting) { glPushMatrix(); glTranslatef(0, 0, 2*z); glScalef(1, 1, -1); glFrontFace(GL_CCW); } setenvmatrix(); if(reflectclip && z>=0) { float zoffset = reflectclip/4.0f, zclip; if(refracting<0) { zclip = z+zoffset; if(camera1->o.z<=zclip) zclip = z; } else { zclip = z-zoffset; if(camera1->o.z>=zclip && camera1->o.z<=z+4.0f) zclip = z; if(reflecting) zclip = 2*z - zclip; } plane clipplane; invmvmatrix.transposedtransform(plane(0, 0, refracting>0 ? 1 : -1, refracting>0 ? -zclip : zclip), clipplane); clipmatrix.clip(clipplane, projmatrix); pushprojection(clipmatrix); } renderreflectedgeom(refracting<0 && z>=0 && caustics, fogging); if(reflecting || refracting>0 || (refracting<0 && refractsky) || z<0) { if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); if(reflectclip && z>=0) popprojection(); if(fogging) { popprojection(); glPopMatrix(); } drawskybox(farplane, false); if(fogging) { pushprojection(); glPushMatrix(); glLoadMatrixf(fogmatrix.v); } if(reflectclip && z>=0) pushprojection(clipmatrix); if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); } else if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); renderdecals(); if(reflectmms) renderreflectedmapmodels(); rendergame(); if(refracting && z>=0 && !isthirdperson() && fabs(camera1->o.z-z) <= 0.5f*(player->eyeheight + player->aboveeye)) { glmatrixf avatarproj; avatarproj.perspective(curavatarfov, aspect, nearplane, farplane); if(reflectclip) { popprojection(); glmatrixf avatarclip; plane clipplane; invmvmatrix.transposedtransform(plane(0, 0, refracting, reflectclipavatar/4.0f - refracting*z), clipplane); avatarclip.clip(clipplane, avatarproj); pushprojection(avatarclip); } else pushprojection(avatarproj); game::renderavatar(); popprojection(); if(reflectclip) pushprojection(clipmatrix); } if(refracting) rendergrass(); rendermaterials(); renderalphageom(fogging); renderparticles(); if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); if(reflectclip && z>=0) popprojection(); if(reflecting) { glPopMatrix(); glFrontFace(GL_CW); } if(fogging) { popprojection(); glPopMatrix(); } glFogf(GL_FOG_START, oldfogstart); glFogf(GL_FOG_END, oldfogend); glFogfv(GL_FOG_COLOR, oldfogcolor); reflectz = 1e16f; refracting = 0; reflecting = fading = fogging = false; setenvmatrix(); } bool envmapping = false; void drawcubemap(int size, const vec &o, float yaw, float pitch, const cubemapside &side) { envmapping = true; physent *oldcamera = camera1; static physent cmcamera; cmcamera = *player; cmcamera.reset(); cmcamera.type = ENT_CAMERA; cmcamera.o = o; cmcamera.yaw = yaw; cmcamera.pitch = pitch; cmcamera.roll = 0; camera1 = &cmcamera; setviewcell(camera1->o); defaultshader->set(); int fogmat = lookupmaterial(o)&MATF_VOLUME; if(fogmat!=MAT_WATER && fogmat!=MAT_LAVA) fogmat = MAT_AIR; setfog(fogmat); glClear(GL_DEPTH_BUFFER_BIT); int farplane = worldsize*2; project(90.0f, 1.0f, farplane, !side.flipx, !side.flipy, side.swapxy); transplayer(); readmatrices(); findorientation(); setenvmatrix(); glEnable(GL_FOG); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); xtravertsva = xtraverts = glde = gbatches = 0; visiblecubes(); if(limitsky()) drawskybox(farplane, true); rendergeom(); if(!limitsky()) drawskybox(farplane, false); // queryreflections(); rendermapmodels(); renderalphageom(); // drawreflections(); // renderwater(); // rendermaterials(); glDisable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_FOG); camera1 = oldcamera; envmapping = false; } bool minimapping = false; GLuint minimaptex = 0; vec minimapcenter(0, 0, 0), minimapradius(0, 0, 0), minimapscale(0, 0, 0); void clearminimap() { if(minimaptex) { glDeleteTextures(1, &minimaptex); minimaptex = 0; } } VARR(minimapheight, 0, 0, 2<<16); bvec minimapcolor(0, 0, 0); HVARFR(minimapcolour, 0, 0, 0xFFFFFF, { minimapcolor = bvec((minimapcolour>>16)&0xFF, (minimapcolour>>8)&0xFF, minimapcolour&0xFF); }); VARR(minimapclip, 0, 0, 1); VARFP(minimapsize, 7, 8, 10, { if(minimaptex) drawminimap(); }); void bindminimap() { glBindTexture(GL_TEXTURE_2D, minimaptex); } void clipminimap(ivec &bbmin, ivec &bbmax, cube *c = worldroot, int x = 0, int y = 0, int z = 0, int size = worldsize>>1) { loopi(8) { ivec o(i, x, y, z, size); if(c[i].children) clipminimap(bbmin, bbmax, c[i].children, o.x, o.y, o.z, size>>1); else if(!isentirelysolid(c[i]) && (c[i].material&MATF_CLIP)!=MAT_CLIP) { loopk(3) bbmin[k] = min(bbmin[k], o[k]); loopk(3) bbmax[k] = max(bbmax[k], o[k] + size); } } } void drawminimap() { if(!game::needminimap()) { clearminimap(); return; } renderprogress(0, "generating mini-map...", 0, !renderedframe); int size = 1<w, screen->h)); while(size > sizelimit) size /= 2; if(!minimaptex) glGenTextures(1, &minimaptex); extern vector valist; ivec bbmin(worldsize, worldsize, worldsize), bbmax(0, 0, 0); loopv(valist) { vtxarray *va = valist[i]; loopk(3) { if(va->geommin[k]>va->geommax[k]) continue; bbmin[k] = min(bbmin[k], va->geommin[k]); bbmax[k] = max(bbmax[k], va->geommax[k]); } } if(minimapclip) { ivec clipmin(worldsize, worldsize, worldsize), clipmax(0, 0, 0); clipminimap(clipmin, clipmax); loopk(2) bbmin[k] = max(bbmin[k], clipmin[k]); loopk(2) bbmax[k] = min(bbmax[k], clipmax[k]); } minimapradius = bbmax.tovec().sub(bbmin.tovec()).mul(0.5f); minimapcenter = bbmin.tovec().add(minimapradius); minimapradius.x = minimapradius.y = max(minimapradius.x, minimapradius.y); minimapscale = vec((0.5f - 1.0f/size)/minimapradius.x, (0.5f - 1.0f/size)/minimapradius.y, 1.0f); envmapping = minimapping = true; physent *oldcamera = camera1; static physent cmcamera; cmcamera = *player; cmcamera.reset(); cmcamera.type = ENT_CAMERA; cmcamera.o = vec(minimapcenter.x, minimapcenter.y, max(minimapcenter.z + minimapradius.z + 1, float(minimapheight))); cmcamera.yaw = 0; cmcamera.pitch = -90; cmcamera.roll = 0; camera1 = &cmcamera; setviewcell(vec(-1, -1, -1)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-minimapradius.x, minimapradius.x, -minimapradius.y, minimapradius.y, 0, camera1->o.z + 1); glScalef(-1, 1, 1); glMatrixMode(GL_MODELVIEW); transplayer(); defaultshader->set(); GLfloat fogc[4] = { minimapcolor.x/255.0f, minimapcolor.y/255.0f, minimapcolor.z/255.0f, 1.0f }; glFogf(GL_FOG_START, 0); glFogf(GL_FOG_END, 1000000); glFogfv(GL_FOG_COLOR, fogc); glClearColor(fogc[0], fogc[1], fogc[2], fogc[3]); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glViewport(1, 1, size-2, size-2); glScissor(1, 1, size-2, size-2); glEnable(GL_SCISSOR_TEST); glDisable(GL_FOG); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glFrontFace(GL_CCW); xtravertsva = xtraverts = glde = gbatches = 0; visiblecubes(false); queryreflections(); drawreflections(); loopi(minimapheight > 0 && minimapheight < minimapcenter.z + minimapradius.z ? 2 : 1) { if(i) { glClear(GL_DEPTH_BUFFER_BIT); camera1->o.z = minimapheight; transplayer(); } rendergeom(); rendermapmodels(); renderwater(); rendermaterials(); renderalphageom(); } glFrontFace(GL_CW); glDisable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_FOG); glDisable(GL_SCISSOR_TEST); glViewport(0, 0, screen->w, screen->h); camera1 = oldcamera; envmapping = minimapping = false; glBindTexture(GL_TEXTURE_2D, minimaptex); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB5, 0, 0, size, size, 0); setuptexparameters(minimaptex, NULL, 3, 1, GL_RGB5, GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); } GLuint motiontex = 0; int motionw = 0, motionh = 0, lastmotion = 0; void cleanupmotionblur() { if(motiontex) { glDeleteTextures(1, &motiontex); motiontex = 0; } motionw = motionh = 0; lastmotion = 0; } VARFP(motionblur, 0, 0, 1, { if(!motionblur) cleanupmotionblur(); }); VARP(motionblurmillis, 1, 5, 1000); FVARP(motionblurscale, 0, 0.5f, 1); void addmotionblur() { if(!motionblur || !hasTR || max(screen->w, screen->h) > hwtexsize) return; if(paused || game::ispaused()) { lastmotion = 0; return; } if(!motiontex || motionw != screen->w || motionh != screen->h) { if(!motiontex) glGenTextures(1, &motiontex); motionw = screen->w; motionh = screen->h; lastmotion = 0; createtexture(motiontex, motionw, motionh, NULL, 3, 0, GL_RGB, GL_TEXTURE_RECTANGLE_ARB); } glBindTexture(GL_TEXTURE_RECTANGLE_ARB, motiontex); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_RECTANGLE_ARB); rectshader->set(); glColor4f(1, 1, 1, lastmotion ? pow(motionblurscale, max(float(lastmillis - lastmotion)/motionblurmillis, 1.0f)) : 0); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f( 0, 0); glVertex2f(-1, -1); glTexCoord2f(motionw, 0); glVertex2f( 1, -1); glTexCoord2f( 0, motionh); glVertex2f(-1, 1); glTexCoord2f(motionw, motionh); glVertex2f( 1, 1); glEnd(); glDisable(GL_TEXTURE_RECTANGLE_ARB); glEnable(GL_TEXTURE_2D); glDisable(GL_BLEND); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); if(lastmillis - lastmotion >= motionblurmillis) { lastmotion = lastmillis - lastmillis%motionblurmillis; glCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, screen->w, screen->h); } } bool dopostfx = false; void invalidatepostfx() { dopostfx = false; } void gl_drawhud(int w, int h); int xtraverts, xtravertsva; void gl_drawframe(int w, int h) { defaultshader->set(); updatedynlights(); aspect = w/float(h); fovy = 2*atan2(tan(curfov/2*RAD), aspect)/RAD; int fogmat = lookupmaterial(camera1->o)&MATF_VOLUME, abovemat = MAT_AIR; float fogblend = 1.0f, causticspass = 0.0f; if(fogmat==MAT_WATER || fogmat==MAT_LAVA) { float z = findsurface(fogmat, camera1->o, abovemat) - WATER_OFFSET; if(camera1->o.z < z + 1) fogblend = min(z + 1 - camera1->o.z, 1.0f); else fogmat = abovemat; if(caustics && fogmat==MAT_WATER && camera1->o.z < z) causticspass = renderpath==R_FIXEDFUNCTION ? 1.0f : min(z - camera1->o.z, 1.0f); } else fogmat = MAT_AIR; setfog(fogmat, fogblend, abovemat); if(fogmat!=MAT_AIR) { float blend = abovemat==MAT_AIR ? fogblend : 1.0f; fovy += blend*sinf(lastmillis/1000.0)*2.0f; aspect += blend*sinf(lastmillis/1000.0+PI)*0.1f; } farplane = worldsize*2; project(fovy, aspect, farplane); transplayer(); readmatrices(); findorientation(); setenvmatrix(); glEnable(GL_FOG); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); xtravertsva = xtraverts = glde = gbatches = 0; if(!hasFBO) { if(dopostfx) { drawglaretex(); drawdepthfxtex(); drawreflections(); } else dopostfx = true; } visiblecubes(); if(shadowmap && !hasFBO) rendershadowmap(); glClear(GL_DEPTH_BUFFER_BIT|(wireframe && editmode ? GL_COLOR_BUFFER_BIT : 0)|(hasstencil ? GL_STENCIL_BUFFER_BIT : 0)); if(wireframe && editmode) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); if(limitsky()) drawskybox(farplane, true); rendergeom(causticspass); extern int outline; if(!wireframe && editmode && outline) renderoutline(); queryreflections(); generategrass(); if(!limitsky()) drawskybox(farplane, false); updatetexanims(); //__offtools__ update tex id's for texanimations renderdecals(true); rendermapmodels(); rendergame(true); if(!isthirdperson()) { project(curavatarfov, aspect, farplane, false, false, false, avatardepth); game::renderavatar(); project(fovy, aspect, farplane); } if(wireframe && editmode) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if(hasFBO) { drawglaretex(); drawdepthfxtex(); drawreflections(); } if(wireframe && editmode) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); renderwater(); rendergrass(); rendermaterials(); renderalphageom(); renderparticles(true); if(wireframe && editmode) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_FOG); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); addmotionblur(); addglare(); if(fogmat==MAT_WATER || fogmat==MAT_LAVA) drawfogoverlay(fogmat, fogblend, abovemat); renderpostfx(); defaultshader->set(); #ifndef NEWGUI g3d_render(); #else UI::render(); #endif glDisable(GL_TEXTURE_2D); notextureshader->set(); gl_drawhud(w, h); renderedgame = false; } void gl_drawmainmenu(int w, int h) { xtravertsva = xtraverts = glde = gbatches = 0; renderbackground(NULL, NULL, NULL, NULL, true, true); renderpostfx(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); defaultshader->set(); glEnable(GL_TEXTURE_2D); #ifdef NEWGUI UI::render(); #else g3d_render(); #endif notextureshader->set(); glDisable(GL_TEXTURE_2D); gl_drawhud(w, h); } VARNP(damagecompass, usedamagecompass, 0, 1, 1); VARP(damagecompassfade, 1, 1000, 10000); VARP(damagecompasssize, 1, 30, 100); VARP(damagecompassalpha, 1, 25, 100); VARP(damagecompassmin, 1, 25, 1000); VARP(damagecompassmax, 1, 200, 1000); float dcompass[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; void damagecompass(int n, const vec &loc) { if(!usedamagecompass) return; vec delta(loc); delta.sub(camera1->o); float yaw, pitch; if(delta.magnitude()<4) yaw = camera1->yaw; else vectoyawpitch(delta, yaw, pitch); yaw -= camera1->yaw; if(yaw >= 360) yaw = fmod(yaw, 360); else if(yaw < 0) yaw = 360 - fmod(-yaw, 360); int dir = (int(yaw+22.5f)%360)/45; dcompass[dir] += max(n, damagecompassmin)/float(damagecompassmax); if(dcompass[dir]>1) dcompass[dir] = 1; } void drawdamagecompass(int w, int h) { int dirs = 0; float size = damagecompasssize/100.0f*min(h, w)/2.0f; loopi(8) if(dcompass[i]>0) { if(!dirs) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 0, 0, damagecompassalpha/100.0f); } dirs++; glPushMatrix(); glTranslatef(w/2, h/2, 0); glRotatef(i*45, 0, 0, 1); glTranslatef(0, -size/2.0f-min(h, w)/4.0f, 0); float logscale = 32, scale = log(1 + (logscale - 1)*dcompass[i]) / log(logscale); glScalef(size*scale, size*scale, 0); glBegin(GL_TRIANGLES); glVertex3f(1, 1, 0); glVertex3f(-1, 1, 0); glVertex3f(0, 0, 0); glEnd(); glPopMatrix(); // fade in log space so short blips don't disappear too quickly scale -= float(curtime)/damagecompassfade; dcompass[i] = scale > 0 ? (pow(logscale, scale) - 1) / (logscale - 1) : 0; } } int damageblendmillis = 0; VARFP(damagescreen, 0, 1, 1, { if(!damagescreen) damageblendmillis = 0; }); VARP(damagescreenfactor, 1, 7, 100); VARP(damagescreenalpha, 1, 45, 100); VARP(damagescreenfade, 0, 125, 1000); VARP(damagescreenmin, 1, 10, 1000); VARP(damagescreenmax, 1, 100, 1000); void damageblend(int n) { if(!damagescreen) return; if(lastmillis > damageblendmillis) damageblendmillis = lastmillis; damageblendmillis += clamp(n, damagescreenmin, damagescreenmax)*damagescreenfactor; } void drawdamagescreen(int w, int h) { if(lastmillis >= damageblendmillis) return; defaultshader->set(); glEnable(GL_TEXTURE_2D); static Texture *damagetex = NULL; if(!damagetex) damagetex = textureload("packages/hud/damage.png", 3); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D, damagetex->id); float fade = damagescreenalpha/100.0f; if(damageblendmillis - lastmillis < damagescreenfade) fade *= float(damageblendmillis - lastmillis)/damagescreenfade; glColor4f(fade, fade, fade, fade); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(1, 0); glVertex2f(w, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glEnd(); glDisable(GL_TEXTURE_2D); notextureshader->set(); } VAR(hidestats, 0, 0, 1); VAR(hidehud, 0, 0, 1); VARP(crosshairsize, 0, 15, 50); VARP(cursorsize, 0, 30, 50); VARP(crosshaircol, 0, 1, 1); VARP(crosshairimg, 0, 1, 1); vector crosshairs; void loadcrosshair(const char *name, int i) { if(i < 0) return; if(!crosshairs.inrange(i)) { int len = crosshairs.length(); crosshairs.growbuf(i + 1); crosshairs.advance(i + 1 - len); loopj(crosshairs.length() - len) crosshairs[j + len] = NULL; } crosshairs[i] = name ? textureload(name, 3, true) : notexture; if(crosshairs[i] == notexture) crosshairs[i] = textureload(game::defaultcrosshair(i) ? game::defaultcrosshair(i) : "data/crosshair", 3, true); } void loadcrosshair_(const char *name, int *i) { loadcrosshair(name, *i); } SVARP(guicursortex, "hud/2.3/guicursor"); COMMANDN(loadcrosshair, loadcrosshair_, "si"); ICOMMAND(getcrosshair, "i", (int *i), const char *name = "packages/crosshair/default.png"; if(crosshairs.inrange(*i)) { name = crosshairs[*i] ? crosshairs[*i]->name : game::defaultcrosshair(*i); if(!name) name = "packages/crosshair/default.png"; } result(name); ) void writecrosshairs(stream *f) { loopv(crosshairs) if(crosshairs[i] && crosshairs[i]!=notexture) f->printf("loadcrosshair \"%s\" %d\n", crosshairs[i]->name, i); f->printf("\n"); } void drawcrosshair(int w, int h) { bool windowhit = #ifdef NEWGUI UI::hascursor(); #else g3d_windowhit(true, false); #endif if(!windowhit && hidehud) return; //(hidehud || player->state==CS_SPECTATOR || player->state==CS_DEAD)) return; #ifndef NEWGUI if(!windowhit && mainmenu) return; #else if(!windowhit && UI::mainmenu) return; #endif float r = 1, g = 1, b = 1, cx = 0.5f, cy = 0.5f, chsize; Texture *crosshair; #ifdef NEWGUI UI::getcursorpos(cx, cy); #endif if(windowhit) { defformatstring(tname)("data/%s", guicursortex); static Texture *cursor = NULL; cursor = textureload(tname, 3, true); crosshair = cursor; chsize = cursorsize*w/900.0f; #ifndef NEWGUI g3d_cursorpos(cx, cy); #endif } else { int index = game::selectcrosshair(r, g, b); if(index < 0) return; if(!crosshaircol) { r = g = b = 1; } if(!crosshairimg) { index = 0; } crosshair = crosshairs.inrange(index) ? crosshairs[index] : NULL; if(!crosshair) { loadcrosshair(NULL, index); crosshair = crosshairs[index]; } chsize = crosshairsize*w/900.0f; } if(crosshair->bpp==4) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); else glBlendFunc(GL_ONE, GL_ONE); glColor3f(r, g, b); float x = cx*w - (windowhit ? 0 : chsize/2.0f); float y = cy*h - (windowhit ? 0 : chsize/2.0f); glBindTexture(GL_TEXTURE_2D, crosshair->id); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x + chsize, y); glTexCoord2f(0, 1); glVertex2f(x, y + chsize); glTexCoord2f(1, 1); glVertex2f(x + chsize, y + chsize); glEnd(); } VARP(wallclock, 0, 0, 1); VARP(wallclock24, 0, 0, 1); VARP(wallclocksecs, 0, 0, 1); static time_t walltime = 0; VARP(showfps, 0, 1, 1); VARP(showfpsrange, 0, 0, 1); VAR(showeditstats, 0, 0, 1); VAR(statrate, 1, 200, 1000); FVARP(conscale, 1e-3f, 0.33f, 1e3f); void gl_drawhud(int w, int h) { #ifdef NEWGUI if(!hidehud && !UI::mainmenu) #else if(!hidehud && !mainmenu) #endif { glEnable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); if(editmode)renderblendbrush(); if (editmode) rendereditcursor(); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); extern int showenthelpers; extern void renderhelpers(); if((showenthelpers==1 && game::showenthelpers()) || showenthelpers == 2) renderhelpers(); glDisable(GL_BLEND); glDepthMask(GL_TRUE); glDisable(GL_DEPTH_TEST); } gettextres(w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1, 1, 1); extern int debugsm; if(debugsm) { extern void viewshadowmap(); viewshadowmap(); } extern int debugglare; if(debugglare) { extern void viewglaretex(); viewglaretex(); } extern int debugdepthfx; if(debugdepthfx) { extern void viewdepthfxtex(); viewdepthfxtex(); } glEnable(GL_BLEND); #ifndef NEWGUI if(!mainmenu) #else if(!UI::mainmenu) #endif { drawdamagescreen(w, h); drawdamagecompass(w, h); } glEnable(GL_TEXTURE_2D); defaultshader->set(); int conw = int(w/conscale), conh = int(h/conscale), abovehud = conh - FONTH, limitgui = abovehud; #ifdef NEWGUI if(!hidehud && !UI::mainmenu) #else if(!hidehud && !mainmenu) #endif { if(hidestats || (!editmode && !showeditstats)) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); game::gameplayhud(w, h); limitgui = abovehud = min(abovehud, int(conh*game::abovegameplayhud(w, h))); } if(!hidestats) { glPushMatrix(); glScalef(conscale, conscale, 1); int roffset = 0; if(showfps) { static int lastfps = 0, prevfps[3] = { 0, 0, 0 }, curfps[3] = { 0, 0, 0 }; if(totalmillis - lastfps >= statrate) { memcpy(prevfps, curfps, sizeof(prevfps)); lastfps = totalmillis - (totalmillis%statrate); } int nextfps[3]; getfps(nextfps[0], nextfps[1], nextfps[2]); loopi(3) if(prevfps[i]==curfps[i]) curfps[i] = nextfps[i]; if(showfpsrange) draw_textf("fps %d+%d-%d", conw-7*FONTH, conh-FONTH*3/2, curfps[0], curfps[1], curfps[2]); else draw_textf("fps %d", conw-5*FONTH, conh-FONTH*3/2, curfps[0]); roffset += FONTH; } if(wallclock) { if(!walltime) { walltime = time(NULL); walltime -= totalmillis/1000; if(!walltime) walltime++; } time_t walloffset = walltime + totalmillis/1000; struct tm *localvals = localtime(&walloffset); static string buf; if(localvals && strftime(buf, sizeof(buf), wallclocksecs ? (wallclock24 ? "%H:%M:%S" : "%I:%M:%S%p") : (wallclock24 ? "%H:%M" : "%I:%M%p"), localvals)) { // hack because not all platforms (windows) support %P lowercase option // also strip leading 0 from 12 hour time char *dst = buf; const char *src = &buf[!wallclock24 && buf[0]=='0' ? 1 : 0]; while(*src) *dst++ = tolower(*src++); *dst++ = '\0'; draw_text(buf, conw-5*FONTH, conh-FONTH*3/2-roffset); roffset += FONTH; } } if(editmode || showeditstats) { static int laststats = 0, prevstats[8] = { 0, 0, 0, 0, 0, 0, 0 }, curstats[8] = { 0, 0, 0, 0, 0, 0, 0 }; if(totalmillis - laststats >= statrate) { memcpy(prevstats, curstats, sizeof(prevstats)); laststats = totalmillis - (totalmillis%statrate); } int nextstats[8] = { vtris*100/max(wtris, 1), vverts*100/max(wverts, 1), xtraverts/1024, xtravertsva/1024, glde, gbatches, getnumqueries(), rplanes }; loopi(8) if(prevstats[i]==curstats[i]) curstats[i] = nextstats[i]; abovehud -= 2*FONTH; draw_textf("wtr:%dk(%d%%) wvt:%dk(%d%%) evt:%dk eva:%dk", FONTH/2, abovehud, wtris/1024, curstats[0], wverts/1024, curstats[1], curstats[2], curstats[3]); draw_textf("ond:%d va:%d gl:%d(%d) oq:%d lm:%d rp:%d pvs:%d", FONTH/2, abovehud+FONTH, allocnodes*8, allocva, curstats[4], curstats[5], curstats[6], lightmaps.length(), curstats[7], getnumviewcells()); limitgui = abovehud; } if(editmode) { abovehud -= FONTH; draw_textf("cube %s%d", FONTH/2, abovehud, selchildcount<0 ? "1/" : "", abs(selchildcount)); char *editinfo = executeret("edithud"); if(editinfo) { if(editinfo[0]) { int tw, th; text_bounds(editinfo, tw, th); th += FONTH-1; th -= th%FONTH; abovehud -= max(th, FONTH); draw_text(editinfo, FONTH/2, abovehud); } DELETEA(editinfo); } } else if(identexists("gamehud")) { char *gameinfo = executeret("gamehud"); if(gameinfo) { if(gameinfo[0]) { int tw, th; text_bounds(gameinfo, tw, th); th += FONTH-1; th -= th%FONTH; roffset += max(th, FONTH); draw_text(gameinfo, conw-max(5*FONTH, 2*FONTH+tw), conh-FONTH/2-roffset); } DELETEA(gameinfo); } } glPopMatrix(); } rendertexturepanel(w, h); } #ifndef NEWGUI g3d_limitscale((2*limitgui - conh) / float(conh)); #endif glPushMatrix(); glScalef(conscale, conscale, 1); abovehud -= rendercommand(FONTH/2, abovehud - FONTH/2, conw-FONTH); extern int fullconsole; if(!hidehud || fullconsole) renderconsole(conw, conh, abovehud - FONTH/2); glPopMatrix(); drawcrosshair(w, h); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); } extern void setupscreen(int &usedcolorbits, int &useddepthbits, int &usedfsaa); extern int scr_w, scr_h; bool resettextures() { if( reloadtexture("data/loadingscreen/engine_badge.png") && reloadtexture("data/loadingscreen/load_back.png") && reloadtexture("data/loadingscreen/load_bar.png") && reloadtexture("data/loadingscreen/load_frame.png") && reloadtexture("data/loadingscreen/mapshot_frame.png") && reloadtexture("data/loadingscreen/title.png") && reloadtexture(imagelogo) ) return true; return false; } void resetgl() { clearchanges(CHANGE_GFX); renderbackground("resetting OpenGL"); extern void cleanupva(); extern void cleanupparticles(); extern void cleanupsky(); extern void cleanupmodels(); extern void cleanuptextures(); extern void cleanuplightmaps(); extern void cleanupblendmap(); extern void cleanshadowmap(); extern void cleanreflections(); extern void cleanupglare(); extern void cleanupdepthfx(); extern void cleanupshaders(); extern void cleanupgl(); cleartexanims(false); recorder::cleanup(); cleanupva(); cleanupparticles(); cleanupsky(); cleanupmodels(); cleanuptextures(); cleanuplightmaps(); cleanupblendmap(); cleanshadowmap(); cleanreflections(); cleanupglare(); cleanupdepthfx(); cleanupshaders(); cleanupgl(); SDL_SetVideoMode(0, 0, 0, 0); int usedcolorbits = 0, useddepthbits = 0, usedfsaa = 0; setupscreen(usedcolorbits, useddepthbits, usedfsaa); gl_init(scr_w, scr_h, usedcolorbits, useddepthbits, usedfsaa); extern void reloadfonts(); extern void reloadtextures(); extern void reloadshaders(); inbetweenframes = false; if(!resettextures()) fatal("failed to reload core texture"); reloadfonts(); inbetweenframes = true; renderbackground("initializing..."); extern void restoregamma(); restoregamma(); reloadshaders(); reloadtextures(); initlights(); allchanged(true); reconftexanims(); } static void getbackgroundres(int &w, int &h) { float wk = 1, hk = 1; if(w < 1024) wk = 1024.0f/w; if(h < 768) hk = 768.0f/h; wk = hk = max(wk, hk); w = int(ceil(w*wk)); h = int(ceil(h*hk)); } string backgroundcaption = ""; Texture *backgroundmapshot = NULL; string backgroundmapname = ""; char *backgroundmapinfo = NULL; void restorebackground() { if(renderedframe) return; renderbackground(backgroundcaption[0] ? backgroundcaption : NULL, backgroundmapshot, backgroundmapname[0] ? backgroundmapname : NULL, backgroundmapinfo, true); } void renderbackground(const char *caption, Texture *mapshot, const char *mapname, const char *mapinfo, bool restore, bool force) { if(!inbetweenframes && !force) return; stopsounds(); int w = screen->w, h = screen->h; getbackgroundres(w, h); gettextres(w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); defaultshader->set(); glEnable(GL_TEXTURE_2D); static int lastupdate = -1, lastw = -1, lasth = -1; #ifdef NEWGUI if((renderedframe && !UI::mainmenu && lastupdate != lastmillis) || lastw != w || lasth != h) #else if((renderedframe && !mainmenu && lastupdate != lastmillis) || lastw != w || lasth != h) #endif { lastupdate = lastmillis; lastw = w; lasth = h; } else if(lastupdate != lastmillis) lastupdate = lastmillis; loopi(restore ? 1 : 3) { glColor3f(1,1,1); float ratio = 0; /*loading screen background*/ glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Texture *background = textureload("data/loadingscreen/load_back.png", 3, false, false); glBindTexture(GL_TEXTURE_2D, background->id); ratio = max((float)h/background->ys, (float)w/background->xs); int wborder = (w - background->xs*ratio) / 2; int hborder = (h - background->ys*ratio) / 2; glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0,0); glVertex2f(wborder, hborder); glTexCoord2f(1,0); glVertex2f(w-wborder, hborder); glTexCoord2f(0,1); glVertex2f(wborder, h-hborder); glTexCoord2f(1,1); glVertex2f(w-wborder, h-hborder); glEnd(); /*module logo*/ float logoh = 0.30f*min(w, h), logow = logoh*0.90; float logox = 0.18f*(w - logow), logoy = 1.35*(h*0.5f - logoh); settexture(imagelogo, 3); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0,0); glVertex2f(logox, logoy); glTexCoord2f(1,0); glVertex2f(logox+logow, logoy); glTexCoord2f(0,1); glVertex2f(logox, logoy+logoh); glTexCoord2f(1,1); glVertex2f(logox+logow, logoy+logoh); glEnd(); /*loading screen title*/ float lh = 0.23f*min(w,h), lw = lh*5.67; float lx = 0.03f*(w - lw), ly = 0.03f*(h*0.5f - lh); settexture("data/loadingscreen/title.png", 3); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0,0); glVertex2f(lx, ly); glTexCoord2f(1,0); glVertex2f(lx+lw, ly); glTexCoord2f(0,1); glVertex2f(lx, ly+lh); glTexCoord2f(1,1); glVertex2f(lx+lw, ly+lh); glEnd(); /*engine badge*/ float badgeh = 0.12f*min(w, h), badgew = badgeh*2.00; float badgex = 0.01f*(w - badgew), badgey = 2.3f*(h*0.5f - badgeh); settexture("data/loadingscreen/engine_badge.png", 3); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(badgex, badgey); glTexCoord2f(1, 0); glVertex2f(badgex+badgew, badgey); glTexCoord2f(0, 1); glVertex2f(badgex, badgey+badgeh); glTexCoord2f(1, 1); glVertex2f(badgex+badgew, badgey+badgeh); glEnd(); /*the rest*/ if(caption) { int tw = text_width(caption); float tsz = 0.04f*min(w, h)/FONTH; float tx = 0.5f*(w - tw*tsz); float ty = h - 0.075f*1.5f*min(w, h) - 1.25f*FONTH*tsz; glPushMatrix(); glTranslatef(tx, ty, 0); glScalef(tsz, tsz, 1); draw_text(caption, 0, 0); glPopMatrix(); } if(mapshot || mapname) { int infowidth = 12*FONTH; float sz = 0.35f*min(w, h); float msz = (0.75f*min(w, h) - sz)/(infowidth + FONTH); float x = 0.5f*(w-sz); float y = ly+lh - sz/15; if(mapinfo) { int miw, mih; text_bounds(mapinfo, miw, mih, infowidth); x-= 0.5*(miw*msz + FONTH*msz); } if(mapshot && mapshot!=notexture) { glBindTexture(GL_TEXTURE_2D, mapshot->id); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x+sz, y); glTexCoord2f(0, 1); glVertex2f(x, y+sz); glTexCoord2f(1, 1); glVertex2f(x+sz, y+sz); glEnd(); } else { int qw, qh; text_bounds("?", qw, qh); float qsz = sz*0.5f/max(qw, qh); glPushMatrix(); glTranslatef(x + 0.5f*(sz - qw*qsz), y + 0.5f*(sz - qh*qsz), 0); glScalef(qsz, qsz, 1); draw_text("?", 0, 0); glPopMatrix(); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } settexture("data/loadingscreen/mapshot_frame.png", 3); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x+sz, y); glTexCoord2f(0, 1); glVertex2f(x, y+sz); glTexCoord2f(1, 1); glVertex2f(x+sz, y+sz); glEnd(); if(mapname) { int tw = text_width(mapname); float tsz = sz/(8*FONTH); float tx = 0.9f*sz - tw*tsz; float ty = 0.9f*sz - FONTH*tsz; if(tx < 0.1f*sz) { tsz = 0.1f*sz/tw; tx = 0.1f; } glPushMatrix(); glTranslatef(x+tx, y+ty, 0); glScalef(tsz, tsz, 1); draw_text(mapname, 0, 0); glPopMatrix(); } if(mapinfo) { glPushMatrix(); glTranslatef(x+sz+FONTH*msz, y, 0); glScalef(msz, msz, 1); draw_text(mapinfo, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, -1, infowidth); glPopMatrix(); } } if(!mapshot && !mapname && !caption && !mapinfo) { float scale = (min(w, h) * 0.100f) / max(1, text_width(version)), ty = w - (min(w,h) * 0.15f), tx = h - (1.5f * FONTH * scale); glPushMatrix(); glTranslatef(ty, tx, 0); glScalef(scale, scale, 1); draw_text(version, 0, 0); glPopMatrix(); } glDisable(GL_BLEND); if(!restore) swapbuffers(); } glDisable(GL_TEXTURE_2D); if(!restore) { renderedframe = false; copystring(backgroundcaption, caption ? caption : ""); backgroundmapshot = mapshot; copystring(backgroundmapname, mapname ? mapname : ""); if(mapinfo != backgroundmapinfo) { DELETEA(backgroundmapinfo); if(mapinfo) backgroundmapinfo = newstring(mapinfo); } } } void setnotextureshader() { notextureshader->set(); } void setdefaultshader() { defaultshader->set(); } void setlineshader() { lineshader->set(); } sandboxgamemaker-2.7.1+dfsg/src/engine/md2.h0000664000175000017500000003716311460063014020546 0ustar showardshowardstruct md2; float md2normaltable[256][3] = { { -0.525731f, 0.000000f, 0.850651f }, { -0.442863f, 0.238856f, 0.864188f }, { -0.295242f, 0.000000f, 0.955423f }, { -0.309017f, 0.500000f, 0.809017f }, { -0.162460f, 0.262866f, 0.951056f }, { 0.000000f, 0.000000f, 1.000000f }, { 0.000000f, 0.850651f, 0.525731f }, { -0.147621f, 0.716567f, 0.681718f }, { 0.147621f, 0.716567f, 0.681718f }, { 0.000000f, 0.525731f, 0.850651f }, { 0.309017f, 0.500000f, 0.809017f }, { 0.525731f, 0.000000f, 0.850651f }, { 0.295242f, 0.000000f, 0.955423f }, { 0.442863f, 0.238856f, 0.864188f }, { 0.162460f, 0.262866f, 0.951056f }, { -0.681718f, 0.147621f, 0.716567f }, { -0.809017f, 0.309017f, 0.500000f }, { -0.587785f, 0.425325f, 0.688191f }, { -0.850651f, 0.525731f, 0.000000f }, { -0.864188f, 0.442863f, 0.238856f }, { -0.716567f, 0.681718f, 0.147621f }, { -0.688191f, 0.587785f, 0.425325f }, { -0.500000f, 0.809017f, 0.309017f }, { -0.238856f, 0.864188f, 0.442863f }, { -0.425325f, 0.688191f, 0.587785f }, { -0.716567f, 0.681718f, -0.147621f }, { -0.500000f, 0.809017f, -0.309017f }, { -0.525731f, 0.850651f, 0.000000f }, { 0.000000f, 0.850651f, -0.525731f }, { -0.238856f, 0.864188f, -0.442863f }, { 0.000000f, 0.955423f, -0.295242f }, { -0.262866f, 0.951056f, -0.162460f }, { 0.000000f, 1.000000f, 0.000000f }, { 0.000000f, 0.955423f, 0.295242f }, { -0.262866f, 0.951056f, 0.162460f }, { 0.238856f, 0.864188f, 0.442863f }, { 0.262866f, 0.951056f, 0.162460f }, { 0.500000f, 0.809017f, 0.309017f }, { 0.238856f, 0.864188f, -0.442863f }, { 0.262866f, 0.951056f, -0.162460f }, { 0.500000f, 0.809017f, -0.309017f }, { 0.850651f, 0.525731f, 0.000000f }, { 0.716567f, 0.681718f, 0.147621f }, { 0.716567f, 0.681718f, -0.147621f }, { 0.525731f, 0.850651f, 0.000000f }, { 0.425325f, 0.688191f, 0.587785f }, { 0.864188f, 0.442863f, 0.238856f }, { 0.688191f, 0.587785f, 0.425325f }, { 0.809017f, 0.309017f, 0.500000f }, { 0.681718f, 0.147621f, 0.716567f }, { 0.587785f, 0.425325f, 0.688191f }, { 0.955423f, 0.295242f, 0.000000f }, { 1.000000f, 0.000000f, 0.000000f }, { 0.951056f, 0.162460f, 0.262866f }, { 0.850651f, -0.525731f, 0.000000f }, { 0.955423f, -0.295242f, 0.000000f }, { 0.864188f, -0.442863f, 0.238856f }, { 0.951056f, -0.162460f, 0.262866f }, { 0.809017f, -0.309017f, 0.500000f }, { 0.681718f, -0.147621f, 0.716567f }, { 0.850651f, 0.000000f, 0.525731f }, { 0.864188f, 0.442863f, -0.238856f }, { 0.809017f, 0.309017f, -0.500000f }, { 0.951056f, 0.162460f, -0.262866f }, { 0.525731f, 0.000000f, -0.850651f }, { 0.681718f, 0.147621f, -0.716567f }, { 0.681718f, -0.147621f, -0.716567f }, { 0.850651f, 0.000000f, -0.525731f }, { 0.809017f, -0.309017f, -0.500000f }, { 0.864188f, -0.442863f, -0.238856f }, { 0.951056f, -0.162460f, -0.262866f }, { 0.147621f, 0.716567f, -0.681718f }, { 0.309017f, 0.500000f, -0.809017f }, { 0.425325f, 0.688191f, -0.587785f }, { 0.442863f, 0.238856f, -0.864188f }, { 0.587785f, 0.425325f, -0.688191f }, { 0.688191f, 0.587785f, -0.425325f }, { -0.147621f, 0.716567f, -0.681718f }, { -0.309017f, 0.500000f, -0.809017f }, { 0.000000f, 0.525731f, -0.850651f }, { -0.525731f, 0.000000f, -0.850651f }, { -0.442863f, 0.238856f, -0.864188f }, { -0.295242f, 0.000000f, -0.955423f }, { -0.162460f, 0.262866f, -0.951056f }, { 0.000000f, 0.000000f, -1.000000f }, { 0.295242f, 0.000000f, -0.955423f }, { 0.162460f, 0.262866f, -0.951056f }, { -0.442863f, -0.238856f, -0.864188f }, { -0.309017f, -0.500000f, -0.809017f }, { -0.162460f, -0.262866f, -0.951056f }, { 0.000000f, -0.850651f, -0.525731f }, { -0.147621f, -0.716567f, -0.681718f }, { 0.147621f, -0.716567f, -0.681718f }, { 0.000000f, -0.525731f, -0.850651f }, { 0.309017f, -0.500000f, -0.809017f }, { 0.442863f, -0.238856f, -0.864188f }, { 0.162460f, -0.262866f, -0.951056f }, { 0.238856f, -0.864188f, -0.442863f }, { 0.500000f, -0.809017f, -0.309017f }, { 0.425325f, -0.688191f, -0.587785f }, { 0.716567f, -0.681718f, -0.147621f }, { 0.688191f, -0.587785f, -0.425325f }, { 0.587785f, -0.425325f, -0.688191f }, { 0.000000f, -0.955423f, -0.295242f }, { 0.000000f, -1.000000f, 0.000000f }, { 0.262866f, -0.951056f, -0.162460f }, { 0.000000f, -0.850651f, 0.525731f }, { 0.000000f, -0.955423f, 0.295242f }, { 0.238856f, -0.864188f, 0.442863f }, { 0.262866f, -0.951056f, 0.162460f }, { 0.500000f, -0.809017f, 0.309017f }, { 0.716567f, -0.681718f, 0.147621f }, { 0.525731f, -0.850651f, 0.000000f }, { -0.238856f, -0.864188f, -0.442863f }, { -0.500000f, -0.809017f, -0.309017f }, { -0.262866f, -0.951056f, -0.162460f }, { -0.850651f, -0.525731f, 0.000000f }, { -0.716567f, -0.681718f, -0.147621f }, { -0.716567f, -0.681718f, 0.147621f }, { -0.525731f, -0.850651f, 0.000000f }, { -0.500000f, -0.809017f, 0.309017f }, { -0.238856f, -0.864188f, 0.442863f }, { -0.262866f, -0.951056f, 0.162460f }, { -0.864188f, -0.442863f, 0.238856f }, { -0.809017f, -0.309017f, 0.500000f }, { -0.688191f, -0.587785f, 0.425325f }, { -0.681718f, -0.147621f, 0.716567f }, { -0.442863f, -0.238856f, 0.864188f }, { -0.587785f, -0.425325f, 0.688191f }, { -0.309017f, -0.500000f, 0.809017f }, { -0.147621f, -0.716567f, 0.681718f }, { -0.425325f, -0.688191f, 0.587785f }, { -0.162460f, -0.262866f, 0.951056f }, { 0.442863f, -0.238856f, 0.864188f }, { 0.162460f, -0.262866f, 0.951056f }, { 0.309017f, -0.500000f, 0.809017f }, { 0.147621f, -0.716567f, 0.681718f }, { 0.000000f, -0.525731f, 0.850651f }, { 0.425325f, -0.688191f, 0.587785f }, { 0.587785f, -0.425325f, 0.688191f }, { 0.688191f, -0.587785f, 0.425325f }, { -0.955423f, 0.295242f, 0.000000f }, { -0.951056f, 0.162460f, 0.262866f }, { -1.000000f, 0.000000f, 0.000000f }, { -0.850651f, 0.000000f, 0.525731f }, { -0.955423f, -0.295242f, 0.000000f }, { -0.951056f, -0.162460f, 0.262866f }, { -0.864188f, 0.442863f, -0.238856f }, { -0.951056f, 0.162460f, -0.262866f }, { -0.809017f, 0.309017f, -0.500000f }, { -0.864188f, -0.442863f, -0.238856f }, { -0.951056f, -0.162460f, -0.262866f }, { -0.809017f, -0.309017f, -0.500000f }, { -0.681718f, 0.147621f, -0.716567f }, { -0.681718f, -0.147621f, -0.716567f }, { -0.850651f, 0.000000f, -0.525731f }, { -0.688191f, 0.587785f, -0.425325f }, { -0.587785f, 0.425325f, -0.688191f }, { -0.425325f, 0.688191f, -0.587785f }, { -0.425325f, -0.688191f, -0.587785f }, { -0.587785f, -0.425325f, -0.688191f }, { -0.688191f, -0.587785f, -0.425325f } }; struct md2 : vertmodel, vertloader { struct md2_header { int magic; int version; int skinwidth, skinheight; int framesize; int numskins, numvertices, numtexcoords; int numtriangles, numglcommands, numframes; int offsetskins, offsettexcoords, offsettriangles; int offsetframes, offsetglcommands, offsetend; }; struct md2_vertex { uchar vertex[3], normalindex; }; struct md2_frame { float scale[3]; float translate[3]; char name[16]; }; md2(const char *name) : vertmodel(name) {} static const char *formatname() { return "md2"; } static bool multiparted() { return false; } static bool multimeshed() { return false; } int type() const { return MDL_MD2; } int linktype(animmodel *m) const { return LINK_COOP; } struct md2meshgroup : vertmeshgroup { void genverts(int *glcommands, vector &tcverts, vector &vindexes, vector &tris) { hashtable tchash; vector idxs; for(int *command = glcommands; (*command)!=0;) { int numvertex = *command++; bool isfan = numvertex<0; if(isfan) numvertex = -numvertex; idxs.setsize(0); loopi(numvertex) { union { int i; float f; } u, v; u.i = *command++; v.i = *command++; int vindex = *command++; ivec tckey(u.i, v.i, vindex); int *idx = tchash.access(tckey); if(!idx) { idx = &tchash[tckey]; *idx = tcverts.length(); tcvert &tc = tcverts.add(); tc.u = u.f; tc.v = v.f; vindexes.add((ushort)vindex); } idxs.add(*idx); } loopi(numvertex-2) { tri &t = tris.add(); if(isfan) { t.vert[0] = idxs[0]; t.vert[1] = idxs[i+1]; t.vert[2] = idxs[i+2]; } else loopk(3) t.vert[k] = idxs[i&1 && k ? i+(1-(k-1))+1 : i+k]; } } } bool load(char *filename) { stream *file = openfile(filename, "rb"); if(!file) return false; md2_header header; file->read(&header, sizeof(md2_header)); lilswap(&header.magic, sizeof(md2_header)/sizeof(int)); if(header.magic!=844121161 || header.version!=8) { delete file; return false; } name = newstring(filename); numframes = header.numframes; vertmesh &m = *new vertmesh; m.group = this; meshes.add(&m); int *glcommands = new int[header.numglcommands]; file->seek(header.offsetglcommands, SEEK_SET); int numglcommands = file->read(glcommands, header.numglcommands*sizeof(int))/sizeof(int); lilswap(glcommands, numglcommands); if(numglcommands < header.numglcommands) memset(&glcommands[numglcommands], 0, (header.numglcommands-numglcommands)*sizeof(int)); vector tcgen; vector vgen; vector trigen; genverts(glcommands, tcgen, vgen,trigen); delete[] glcommands; m.numverts = tcgen.length(); m.tcverts = new tcvert[m.numverts]; memcpy(m.tcverts, tcgen.getbuf(), m.numverts*sizeof(tcvert)); m.numtris = trigen.length(); m.tris = new tri[m.numtris]; memcpy(m.tris, trigen.getbuf(), m.numtris*sizeof(tri)); m.verts = new vert[m.numverts*numframes]; md2_vertex *tmpverts = new md2_vertex[header.numvertices]; int frame_offset = header.offsetframes; vert *curvert = m.verts; loopi(header.numframes) { md2_frame frame; file->seek(frame_offset, SEEK_SET); file->read(&frame, sizeof(md2_frame)); lilswap(frame.scale, 6); file->read(tmpverts, header.numvertices*sizeof(md2_vertex)); loopj(m.numverts) { const md2_vertex &v = tmpverts[vgen[j]]; curvert->pos = vec(v.vertex[0]*frame.scale[0]+frame.translate[0], -(v.vertex[1]*frame.scale[1]+frame.translate[1]), v.vertex[2]*frame.scale[2]+frame.translate[2]); const float *norm = md2normaltable[v.normalindex]; curvert->norm = vec(norm[0], -norm[1], norm[2]); curvert++; } frame_offset += header.framesize; } delete[] tmpverts; delete file; return true; } }; struct md2part : part { void getdefaultanim(animinfo &info, int anim, uint varseed, dynent *d) { // 0 3 6 7 8 9 10 11 12 13 14 15 16 17 // D D D D D D A P I R, E J T W FO SA GS GI static int _frame[] = { 178, 184, 190, 183, 189, 197, 46, 54, 0, 40, 162, 67, 95, 112, 72, 84, 7, 6 }; static int _range[] = { 6, 6, 8, 1, 1, 1, 8, 4, 40, 6, 1, 1, 17, 11, 12, 11, 18, 1 }; // DE DY I F B L R H1 H2 H3 H4 H5 H6 H7 A1 A2 A3 A4 A5 A6 A7 PA J SI SW ED LA T WI LO GI GS static int animfr[] = { 5, 2, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 7, 11, 8, 9, 10, 14, 12, 13, 15, 17, 16 }; anim &= ANIM_INDEX; if((size_t)anim >= sizeof(animfr)/sizeof(animfr[0])) { info.frame = 0; info.range = 1; return; } int n = animfr[anim]; switch(anim) { case ANIM_DYING: case ANIM_DEAD: n -= varseed%3; break; case ANIM_FORWARD: case ANIM_BACKWARD: case ANIM_LEFT: case ANIM_RIGHT: case ANIM_SWIM: info.speed = 5500.0f/d->maxspeed; break; } info.frame = _frame[n]; info.range = _range[n]; } }; meshgroup *loadmeshes(char *name, va_list args) { md2meshgroup *group = new md2meshgroup; if(!group->load(name)) { delete group; return NULL; } return group; } bool load() { if(loaded) return true; part &mdl = *new md2part; parts.add(&mdl); mdl.model = this; mdl.index = 0; const char *pname = parentdir(loadname); defformatstring(name1)("packages/models/%s/tris.md2", loadname); mdl.meshes = sharemeshes(path(name1)); if(!mdl.meshes) { defformatstring(name2)("packages/models/%s/tris.md2", pname); // try md2 in parent folder (vert sharing) mdl.meshes = sharemeshes(path(name2)); if(!mdl.meshes) return false; } Texture *tex, *masks; loadskin(loadname, pname, tex, masks); mdl.initskins(tex, masks); if(tex==notexture) conoutf("could not load model skin for %s", name1); loading = this; identflags &= ~IDF_PERSIST; defformatstring(name3)("packages/models/%s/md2.cfg", loadname); if(!execfile(name3, false)) { formatstring(name3)("packages/models/%s/md2.cfg", pname); execfile(name3, false); } identflags |= IDF_PERSIST; loading = 0; scale /= 4; translate.y = -translate.y; parts[0]->translate = translate; loopv(parts) parts[i]->meshes->shared++; preloadshaders(); return loaded = true; } }; vertcommands md2commands; sandboxgamemaker-2.7.1+dfsg/src/engine/main.cpp0000664000175000017500000007403711655776734021376 0ustar showardshoward// main.cpp: initialisation & main loop #include "engine.h" SVARO(version, "2.7.1"); string imagelogo; extern void cleargamma(); void cleanup() { recorder::stop(); cleanupserver(); SDL_ShowCursor(1); SDL_WM_GrabInput(SDL_GRAB_OFF); cleargamma(); freeocta(worldroot); extern void clear_command(); clear_command(); extern void clear_console(); clear_console(); extern void clear_mdls(); clear_mdls(); extern void clear_sound(); clear_sound(); closelogfile(); SDL_Quit(); } void quit() // normal exit { extern void writeinitcfg(); writeinitcfg(); writeservercfg(); abortconnect(); disconnect(); localdisconnect(); writecfg(); cleanup(); exit(EXIT_SUCCESS); } void fatal(const char *s, ...) // failure exit { static int errors = 0; errors++; if(errors <= 2) // print up to one extra recursive error { defvformatstring(msg,s,s); logoutf("%s", msg); if(errors <= 1) // avoid recursion { if(SDL_WasInit(SDL_INIT_VIDEO)) { SDL_ShowCursor(1); SDL_WM_GrabInput(SDL_GRAB_OFF); cleargamma(); } #ifdef WIN32 MessageBox(NULL, msg, "Sandbox fatal error", MB_OK|MB_SYSTEMMODAL); #endif SDL_Quit(); } } exit(EXIT_FAILURE); } SDL_Surface *screen = NULL; VAR(curtime, 1, 0, 0); VAR(totalmillis, 1, 1, 0); VAR(lastmillis, 1, 1, 0); dynent *player = NULL; int initing = NOT_INITING; static bool restoredinits = false; bool initwarning(const char *desc, int level, int type) { if(initing < level) { addchange(desc, type); return true; } return false; } #define SCR_MINW 320 #define SCR_MINH 200 #define SCR_MAXW 10000 #define SCR_MAXH 10000 #define SCR_DEFAULTW 1024 #define SCR_DEFAULTH 768 VARF(scr_w, SCR_MINW, -1, SCR_MAXW, initwarning("screen resolution")); VARF(scr_h, SCR_MINH, -1, SCR_MAXH, initwarning("screen resolution")); VARF(colorbits, 0, 0, 32, initwarning("color depth")); VARF(depthbits, 0, 0, 32, initwarning("depth-buffer precision")); VARF(stencilbits, 0, 0, 32, initwarning("stencil-buffer precision")); VARF(fsaa, -1, -1, 16, initwarning("anti-aliasing")); VARF(vsync, -1, -1, 1, initwarning("vertical sync")); void writeinitcfg() { if(!restoredinits) return; stream *f = openutf8file("init.cfg", "wb"); if(!f) return; f->printf("// automatically written on exit, DO NOT MODIFY\n// modify settings in game\n"); extern int fullscreen; f->printf("fullscreen %d\n", fullscreen); f->printf("scr_w %d\n", scr_w); f->printf("scr_h %d\n", scr_h); f->printf("colorbits %d\n", colorbits); f->printf("depthbits %d\n", depthbits); f->printf("stencilbits %d\n", stencilbits); f->printf("fsaa %d\n", fsaa); f->printf("vsync %d\n", vsync); extern int useshaders, shaderprecision, forceglsl; f->printf("shaders %d\n", useshaders); f->printf("shaderprecision %d\n", shaderprecision); f->printf("forceglsl %d\n", forceglsl); extern int soundchans, soundfreq, soundbufferlen; f->printf("soundchans %d\n", soundchans); f->printf("soundfreq %d\n", soundfreq); f->printf("soundbufferlen %d\n", soundbufferlen); delete f; } COMMAND(quit, ""); static void getbackgroundres(int &w, int &h) { float wk = 1, hk = 1; if(w < 1024) wk = 1024.0f/w; if(h < 768) hk = 768.0f/h; wk = hk = max(wk, hk); w = int(ceil(w*wk)); h = int(ceil(h*hk)); } extern void renderbackground(const char *caption, Texture *mapshot, const char *mapname, const char *mapinfo, bool restore, bool force); extern void restorebackground(); float loadprogress = 0; void renderprogress(float bar, const char *text, GLuint tex, bool background) // also used during loading { if(!inbetweenframes || envmapping) return; clientkeepalive(); // make sure our connection doesn't time out while loading maps etc. #ifdef __APPLE__ interceptkey(SDLK_UNKNOWN); // keep the event queue awake to avoid 'beachball' cursor #endif extern int sdl_backingstore_bug; if(background || sdl_backingstore_bug > 0) restorebackground(); int w = screen->w, h = screen->h; getbackgroundres(w, h); gettextres(w, h); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); defaultshader->set(); glColor3f(1, 1, 1); float fh = 0.070f*min(w, h), fw = fh*10, fx = renderedframe ? w - fw - fh/4 : 0.5f*(w - fw), fy = renderedframe ? fh/4 : h - fh*1.5f; settexture("data/loadingscreen/load_frame.png", 3); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex2f(fx, fy); glTexCoord2f(1,0); glVertex2f(fx+fw, fy); glTexCoord2f(1,1); glVertex2f(fx+fw, fy+fh); glTexCoord2f(0,1); glVertex2f(fx, fy+fh); glEnd(); float bh = fh*20/52.0f, bx = fx + fw*17/511.0f; float by = fy + fh*16/52.0f, sw = fw*7/511.0f; float mw = fw, prog = bar; float ex = fx + max(mw*bar, fw*7/511.0f); if(bar > 0) { settexture("data/loadingscreen/load_bar.png", 3); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(fx, fy); glTexCoord2f(prog, 0); glVertex2f(ex, fy); glTexCoord2f(prog, 1); glVertex2f(ex, fy+fh); glTexCoord2f(0, 1); glVertex2f(fx, fy+fh); glEnd(); } if(text) { int tw = text_width(text); float tsz = bh*0.8f/FONTH; if(tw*tsz > mw) tsz = mw/tw; glPushMatrix(); glTranslatef(bx+sw, by + (bh - FONTH*tsz)/2, 0); glScalef(tsz, tsz, 1); draw_text(text, 0, 0); glPopMatrix(); } glDisable(GL_BLEND); if(tex) { float sz = 0.35f*min(w, h), x = 0.5f*(w-sz), y = 0.5f*min(w, h) - sz/15; glBindTexture(GL_TEXTURE_2D, tex); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x+sz, y); glTexCoord2f(0, 1); glVertex2f(x, y+sz); glTexCoord2f(1, 1); glVertex2f(x+sz, y+sz); glEnd(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); settexture("data/loadingscreen/mapshot_frame.png", 3); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x+sz, y); glTexCoord2f(0, 1); glVertex2f(x, y+sz); glTexCoord2f(1, 1); glVertex2f(x+sz, y+sz); glEnd(); glDisable(GL_BLEND); } glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); swapbuffers(); } void keyrepeat(bool on) { SDL_EnableKeyRepeat(on ? SDL_DEFAULT_REPEAT_DELAY : 0, SDL_DEFAULT_REPEAT_INTERVAL); } static bool grabinput = false, minimized = false; void inputgrab(bool on) { #ifndef WIN32 if(!(screen->flags & SDL_FULLSCREEN)) SDL_WM_GrabInput(SDL_GRAB_OFF); else #endif SDL_WM_GrabInput(on ? SDL_GRAB_ON : SDL_GRAB_OFF); SDL_ShowCursor(on ? SDL_DISABLE : SDL_ENABLE); } void setfullscreen(bool enable) { if(!screen) return; #if defined(WIN32) || defined(__APPLE__) initwarning(enable ? "fullscreen" : "windowed"); #else if(enable == !(screen->flags&SDL_FULLSCREEN)) { SDL_WM_ToggleFullScreen(screen); inputgrab(grabinput); } #endif } #ifdef _DEBUG VARF(fullscreen, 0, 0, 1, setfullscreen(fullscreen!=0)); #else VARF(fullscreen, 0, 1, 1, setfullscreen(fullscreen!=0)); #endif void screenres(int *w, int *h) { #if !defined(WIN32) && !defined(__APPLE__) if(initing >= INIT_RESET) { #endif scr_w = clamp(*w, SCR_MINW, SCR_MAXW); scr_h = clamp(*h, SCR_MINH, SCR_MAXH); #if defined(WIN32) || defined(__APPLE__) initwarning("screen resolution"); #else return; } SDL_Surface *surf = SDL_SetVideoMode(clamp(*w, SCR_MINW, SCR_MAXW), clamp(*h, SCR_MINH, SCR_MAXH), 0, SDL_OPENGL|(screen->flags&SDL_FULLSCREEN ? SDL_FULLSCREEN : SDL_RESIZABLE)); if(!surf) return; screen = surf; scr_w = screen->w; scr_h = screen->h; glViewport(0, 0, scr_w, scr_h); #endif } COMMAND(screenres, "ii"); static int curgamma = 100; VARFP(gamma, 30, 100, 300, { if(gamma == curgamma) return; curgamma = gamma; float f = gamma/100.0f; if(SDL_SetGamma(f,f,f)==-1) conoutf(CON_ERROR, "Could not set gamma: %s", SDL_GetError()); }); void restoregamma() { if(curgamma == 100) return; float f = curgamma/100.0f; SDL_SetGamma(1, 1, 1); SDL_SetGamma(f, f, f); } void cleargamma() { if(curgamma != 100) SDL_SetGamma(1, 1, 1); } VAR(dbgmodes, 0, 0, 1); int desktopw = 0, desktoph = 0; void setupscreen(int &usedcolorbits, int &useddepthbits, int &usedfsaa) { int flags = SDL_RESIZABLE; #if defined(WIN32) || defined(__APPLE__) flags = 0; #endif if(fullscreen) flags = SDL_FULLSCREEN; SDL_Rect **modes = SDL_ListModes(NULL, SDL_OPENGL|flags); if(modes && modes!=(SDL_Rect **)-1) { int widest = -1, best = -1; for(int i = 0; modes[i]; i++) { if(dbgmodes) conoutf(CON_DEBUG, "mode[%d]: %d x %d", i, modes[i]->w, modes[i]->h); if(widest < 0 || modes[i]->w > modes[widest]->w || (modes[i]->w == modes[widest]->w && modes[i]->h > modes[widest]->h)) widest = i; } if(scr_w < 0 || scr_h < 0) { int w = scr_w, h = scr_h, ratiow = desktopw, ratioh = desktoph; if(w < 0 && h < 0) { w = SCR_DEFAULTW; h = SCR_DEFAULTH; } if(ratiow <= 0 || ratioh <= 0) { ratiow = modes[widest]->w; ratioh = modes[widest]->h; } for(int i = 0; modes[i]; i++) if(modes[i]->w*ratioh == modes[i]->h*ratiow) { if(w <= modes[i]->w && h <= modes[i]->h && (best < 0 || modes[i]->w < modes[best]->w)) best = i; } } if(best < 0) { int w = scr_w, h = scr_h; if(w < 0 && h < 0) { w = SCR_DEFAULTW; h = SCR_DEFAULTH; } else if(w < 0) w = (h*SCR_DEFAULTW)/SCR_DEFAULTH; else if(h < 0) h = (w*SCR_DEFAULTH)/SCR_DEFAULTW; for(int i = 0; modes[i]; i++) { if(w <= modes[i]->w && h <= modes[i]->h && (best < 0 || modes[i]->w < modes[best]->w || (modes[i]->w == modes[best]->w && modes[i]->h < modes[best]->h))) best = i; } } if(flags&SDL_FULLSCREEN) { if(best >= 0) { scr_w = modes[best]->w; scr_h = modes[best]->h; } else if(desktopw > 0 && desktoph > 0) { scr_w = desktopw; scr_h = desktoph; } else if(widest >= 0) { scr_w = modes[widest]->w; scr_h = modes[widest]->h; } } else if(best < 0) { scr_w = min(scr_w >= 0 ? scr_w : (scr_h >= 0 ? (scr_h*SCR_DEFAULTW)/SCR_DEFAULTH : SCR_DEFAULTW), (int)modes[widest]->w); scr_h = min(scr_h >= 0 ? scr_h : (scr_w >= 0 ? (scr_w*SCR_DEFAULTH)/SCR_DEFAULTW : SCR_DEFAULTH), (int)modes[widest]->h); } if(dbgmodes) conoutf(CON_DEBUG, "selected %d x %d", scr_w, scr_h); } if(scr_w < 0 && scr_h < 0) { scr_w = SCR_DEFAULTW; scr_h = SCR_DEFAULTH; } else if(scr_w < 0) scr_w = (scr_h*SCR_DEFAULTW)/SCR_DEFAULTH; else if(scr_h < 0) scr_h = (scr_w*SCR_DEFAULTH)/SCR_DEFAULTW; bool hasbpp = true; if(colorbits) hasbpp = SDL_VideoModeOK(scr_w, scr_h, colorbits, SDL_OPENGL|flags)==colorbits; SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); #if SDL_VERSION_ATLEAST(1, 2, 11) if(vsync>=0) SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vsync); #endif static int configs[] = { 0x7, /* try everything */ 0x6, 0x5, 0x3, /* try disabling one at a time */ 0x4, 0x2, 0x1, /* try disabling two at a time */ 0 /* try disabling everything */ }; int config = 0; SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0); if(!depthbits) SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); if(!fsaa) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); } loopi(sizeof(configs)/sizeof(configs[0])) { config = configs[i]; if(!depthbits && config&1) continue; if(!stencilbits && config&2) continue; if(fsaa<=0 && config&4) continue; if(depthbits) SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, config&1 ? depthbits : 16); if(stencilbits) { hasstencil = config&2 ? stencilbits : 0; SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, hasstencil); } else hasstencil = 0; if(fsaa>0) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, config&4 ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, config&4 ? fsaa : 0); } screen = SDL_SetVideoMode(scr_w, scr_h, hasbpp ? colorbits : 0, SDL_OPENGL|flags); if(screen) break; } if(!screen) fatal("Unable to create OpenGL screen: %s", SDL_GetError()); else { if(!hasbpp) conoutf(CON_WARN, "%d bit color buffer not supported - disabling", colorbits); if(depthbits && (config&1)==0) conoutf(CON_WARN, "%d bit z-buffer not supported - disabling", depthbits); if(stencilbits && (config&2)==0) conoutf(CON_WARN, "Stencil buffer not supported - disabling"); if(fsaa>0 && (config&4)==0) conoutf(CON_WARN, "%dx anti-aliasing not supported - disabling", fsaa); } scr_w = screen->w; scr_h = screen->h; usedcolorbits = hasbpp ? colorbits : 0; useddepthbits = config&1 ? depthbits : 0; usedfsaa = config&4 ? fsaa : 0; } extern void resetgl(); COMMAND(resetgl, ""); static int ignoremouse = 5; vector events; void pushevent(const SDL_Event &e) { events.add(e); } bool interceptkey(int sym) { static int lastintercept = SDLK_UNKNOWN; int len = lastintercept == sym ? events.length() : 0; SDL_Event event; while(SDL_PollEvent(&event)) switch(event.type) { case SDL_MOUSEMOTION: break; default: pushevent(event); break; } lastintercept = sym; if(sym != SDLK_UNKNOWN) for(int i = len; i < events.length(); i++) { if(events[i].type == SDL_KEYDOWN && events[i].key.keysym.sym == sym) { events.remove(i); return true; } } return false; } static void resetmousemotion() { #ifndef WIN32 if(!(screen->flags&SDL_FULLSCREEN)) { SDL_WarpMouse(screen->w / 2, screen->h / 2); } #endif } static inline bool skipmousemotion(SDL_Event &event) { if(event.type != SDL_MOUSEMOTION) return true; #ifndef WIN32 if(!(screen->flags&SDL_FULLSCREEN)) { #ifdef __APPLE__ if(event.motion.y == 0) return true; // let mac users drag windows via the title bar #endif if(event.motion.x == screen->w / 2 && event.motion.y == screen->h / 2) return true; // ignore any motion events generated SDL_WarpMouse } #endif return false; } static void checkmousemotion(int &dx, int &dy) { loopv(events) { SDL_Event &event = events[i]; if(skipmousemotion(event)) { if(i > 0) events.remove(0, i); return; } dx += event.motion.xrel; dy += event.motion.yrel; } events.setsize(0); SDL_Event event; while(SDL_PollEvent(&event)) { if(skipmousemotion(event)) { events.add(event); return; } dx += event.motion.xrel; dy += event.motion.yrel; } } void checkinput() { SDL_Event event; int lasttype = 0, lastbut = 0; while(events.length() || SDL_PollEvent(&event)) { if(events.length()) event = events.remove(0); switch(event.type) { case SDL_QUIT: quit(); break; #if !defined(WIN32) && !defined(__APPLE__) case SDL_VIDEORESIZE: screenres(&event.resize.w, &event.resize.h); break; #endif case SDL_KEYDOWN: case SDL_KEYUP: keypress(event.key.keysym.sym, event.key.state==SDL_PRESSED, uni2cube(event.key.keysym.unicode)); break; case SDL_ACTIVEEVENT: if(event.active.state & SDL_APPINPUTFOCUS) inputgrab(grabinput = event.active.gain!=0); if(event.active.state & SDL_APPACTIVE) minimized = !event.active.gain; break; case SDL_MOUSEMOTION: if(ignoremouse) { ignoremouse--; break; } if(grabinput && !skipmousemotion(event)) { int dx = event.motion.xrel, dy = event.motion.yrel; checkmousemotion(dx, dy); resetmousemotion(); #ifndef NEWGUI if(!g3d_movecursor(dx, dy)) #else if(!UI::movecursor(dx, dy) && !UI::hascursor()) #endif mousemove(dx, dy); } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: if(lasttype==event.type && lastbut==event.button.button) break; // why?? get event twice without it keypress(-event.button.button, event.button.state!=0, 0); lasttype = event.type; lastbut = event.button.button; break; } } } void swapbuffers() { recorder::capture(); SDL_GL_SwapBuffers(); } VARF(gamespeed, 10, 100, 1000, if(multiplayer()) gamespeed = 100); VARF(paused, 0, 0, 1, if(multiplayer()) paused = 0); VAR(mainmenufps, 0, 60, 1000); VARP(maxfps, 0, 200, 1000); void limitfps(int &millis, int curmillis) { #ifdef NEWGUI int limit = UI::mainmenu && mainmenufps ? (maxfps ? min(maxfps, mainmenufps) : mainmenufps) : maxfps; #else int limit = mainmenu && mainmenufps ? (maxfps ? min(maxfps, mainmenufps) : mainmenufps) : maxfps; #endif if(!limit) return; static int fpserror = 0; int delay = 1000/limit - (millis-curmillis); if(delay < 0) fpserror = 0; else { fpserror += 1000%limit; if(fpserror >= limit) { ++delay; fpserror -= limit; } if(delay > 0) { SDL_Delay(delay); millis += delay; } } } #if defined(WIN32) && !defined(_DEBUG) && !defined(__GNUC__) void stackdumper(unsigned int type, EXCEPTION_POINTERS *ep) { if(!ep) fatal("unknown type"); EXCEPTION_RECORD *er = ep->ExceptionRecord; CONTEXT *context = ep->ContextRecord; string out, t; formatstring(out)("Sandbox Win32 Exception: 0x%x [0x%x]\n\n", er->ExceptionCode, er->ExceptionCode==EXCEPTION_ACCESS_VIOLATION ? er->ExceptionInformation[1] : -1); STACKFRAME sf = {{context->Eip, 0, AddrModeFlat}, {}, {context->Ebp, 0, AddrModeFlat}, {context->Esp, 0, AddrModeFlat}, 0}; SymInitialize(GetCurrentProcess(), NULL, TRUE); while(::StackWalk(IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), GetCurrentThread(), &sf, context, NULL, ::SymFunctionTableAccess, ::SymGetModuleBase, NULL)) { struct { IMAGEHLP_SYMBOL sym; string n; } si = { { sizeof( IMAGEHLP_SYMBOL ), 0, 0, 0, sizeof(string) } }; IMAGEHLP_LINE li = { sizeof( IMAGEHLP_LINE ) }; DWORD off; if(SymGetSymFromAddr(GetCurrentProcess(), (DWORD)sf.AddrPC.Offset, &off, &si.sym) && SymGetLineFromAddr(GetCurrentProcess(), (DWORD)sf.AddrPC.Offset, &off, &li)) { char *del = strrchr(li.FileName, '\\'); formatstring(t)("%s - %s [%d]\n", si.sym.Name, del ? del + 1 : li.FileName, li.LineNumber); concatstring(out, t); } } fatal(out); } #endif #define MAXFPSHISTORY 60 int fpspos = 0, fpshistory[MAXFPSHISTORY]; void resetfpshistory() { loopi(MAXFPSHISTORY) fpshistory[i] = 1; fpspos = 0; } void updatefpshistory(int millis) { fpshistory[fpspos++] = max(1, min(1000, millis)); if(fpspos>=MAXFPSHISTORY) fpspos = 0; } void getfps(int &fps, int &bestdiff, int &worstdiff) { int total = fpshistory[MAXFPSHISTORY-1], best = total, worst = total; loopi(MAXFPSHISTORY-1) { int millis = fpshistory[i]; total += millis; if(millis < best) best = millis; if(millis > worst) worst = millis; } fps = (1000*MAXFPSHISTORY)/total; bestdiff = 1000/best-fps; worstdiff = fps-1000/worst; } void getfps_(int *raw) { int fps, bestdiff, worstdiff; if(*raw) fps = 1000/fpshistory[(fpspos+MAXFPSHISTORY-1)%MAXFPSHISTORY]; else getfps(fps, bestdiff, worstdiff); intret(fps); } COMMANDN(getfps, getfps_, "i"); bool inbetweenframes = false, renderedframe = true; static bool findarg(int argc, char **argv, const char *str) { for(int i = 1; i 0 ? 1 : 0; shaderprecision = clamp(n >= 4 ? n - 4 : n - 1, 0, 2); forceglsl = n >= 4 ? 1 : 0; break; } case 'l': { char pkgdir[] = "packages/"; load = strstr(path(&argv[i][2]), path(pkgdir)); if(load) load += sizeof(pkgdir)-1; else load = &argv[i][2]; break; } case 'x': initscript = &argv[i][2]; break; default: if(!serveroption(argv[i])) gameargs.add(argv[i]); break; } else gameargs.add(argv[i]); } initing = NOT_INITING; if(dedicated <= 1) { logoutf("init: sdl"); int par = 0; #ifdef _DEBUG par = SDL_INIT_NOPARACHUTE; #ifdef WIN32 SetEnvironmentVariable("SDL_DEBUG", "1"); #endif #endif if(SDL_Init(SDL_INIT_TIMER|SDL_INIT_VIDEO|SDL_INIT_AUDIO|par)<0) fatal("Unable to initialize SDL: %s", SDL_GetError()); } logoutf("init: net"); if(enet_initialize()<0) fatal("Unable to initialise network module"); atexit(enet_deinitialize); enet_time_set(0); logoutf("init: game"); game::parseoptions(gameargs); initserver(dedicated>0, dedicated>1); // never returns if dedicated ASSERT(dedicated <= 1); game::initclient(); logoutf("init: video: mode"); const SDL_VideoInfo *video = SDL_GetVideoInfo(); if(video) { desktopw = video->current_w; desktoph = video->current_h; } int usedcolorbits = 0, useddepthbits = 0, usedfsaa = 0; setupscreen(usedcolorbits, useddepthbits, usedfsaa); logoutf("init: video: misc"); defformatstring(capt)("Sandbox Engine %s", version); SDL_WM_SetCaption(capt, NULL); keyrepeat(false); SDL_ShowCursor(0); logoutf("init: gl"); gl_checkextensions(); gl_init(scr_w, scr_h, usedcolorbits, useddepthbits, usedfsaa); notexture = textureload("data/notexture"); if(!notexture) fatal("could not find core textures"); #ifdef NEWGUI UI::setup(); #endif logoutf("init: console"); identflags &= ~IDF_PERSIST; if(!execfile("data/stdlib.cfg", false)) fatal("cannot find data files (you are running from the wrong folder, try .bat file in the main folder)"); // this is the first file we load. if(!execfile("data/font.cfg", false)) fatal("cannot find font definitions"); if(!setfont("default")) fatal("no default font specified"); formatstring(imagelogo)("data/%s/logo", game::gameident()); inbetweenframes = true; renderbackground("initialising..."); logoutf("init: gl: effects"); loadshaders(); particleinit(); initdecals(); logoutf("init: world"); camera1 = player = game::iterdynents(0); emptymap(0, true, NULL, false); logoutf("init: sound"); initsound(); logoutf("init: cfg"); execfile("data/keymap.cfg"); execfile("data/stdedit.cfg"); defformatstring(confname)("data/%s/std.cfg", game::gameident()); execfile(confname, false); formatstring(confname)("data/%s/sounds.cfg", game::gameident()); if(!execfile(confname, false)) execfile("data/sounds.cfg"); execfile("data/brush.cfg"); execfile("mybrushes.cfg", false); #ifdef NEWGUI execfile("data/newui.cfg"); formatstring(confname)("data/%s/newui.cfg", game::gameident()); execfile(confname, false); #else execfile("data/menus.cfg"); formatstring(confname)("data/%s/menus.cfg", game::gameident()); execfile(confname, false); #endif if(game::savedservers()) execfile(game::savedservers(), false); identflags |= IDF_PERSIST; initing = INIT_LOAD; formatstring(confname)("config_%s.cfg", game::gameident()); if(!execfile(confname, false)) setdefaults(); execfile(game::autoexec(), false); initing = NOT_INITING; identflags &= ~IDF_PERSIST; formatstring(confname)("data/%s/game.cfg", game::gameident()); execfile(confname, false); execfile("packages/loadback/loadback.cfg", false); identflags |= IDF_PERSIST; if(execfile("once.cfg", false)) remove(findfile("once.cfg", "rb")); if(load) { logoutf("init: localconnect"); //localconnect(); game::changemap(load); } if(initscript) execute(initscript); logoutf("init: mainloop"); initmumble(); resetfpshistory(); inputgrab(grabinput = true); for(;;) { static int frames = 0; int millis = getclockmillis(); limitfps(millis, totalmillis); int elapsed = millis-totalmillis; if(multiplayer(false)) curtime = game::ispaused() ? 0 : elapsed; else { static int timeerr = 0; int scaledtime = elapsed*gamespeed + timeerr; curtime = scaledtime/100; timeerr = scaledtime%100; if(curtime>200) curtime = 200; if(paused || game::ispaused()) curtime = 0; } lastmillis += curtime; totalmillis = millis; extern void updatetime(); updatetime(); checkinput(); #ifndef NEWGUI menuprocess(); #else UI::update(); #endif tryedit(); if(lastmillis) { game::updateworld(); } checksleep(lastmillis); serverslice(false, 0); if(frames) updatefpshistory(elapsed); frames++; // miscellaneous general game effects recomputecamera(); updateparticles(); updatesounds(); if(minimized) continue; inbetweenframes = false; #ifndef NEWGUI if(mainmenu) #else if(UI::mainmenu) #endif gl_drawmainmenu(screen->w, screen->h); else gl_drawframe(screen->w, screen->h); swapbuffers(); renderedframe = inbetweenframes = true; } ASSERT(0); return EXIT_FAILURE; #if defined(WIN32) && !defined(_DEBUG) && !defined(__GNUC__) } __except(stackdumper(0, GetExceptionInformation()), EXCEPTION_CONTINUE_SEARCH) { return 0; } #endif } sandboxgamemaker-2.7.1+dfsg/src/engine/menus.cpp0000664000175000017500000004377611544613352021566 0ustar showardshoward// menus.cpp: ingame menu system (also used for scores and serverlist) #ifndef NEWGUI #include "engine.h" HVARP(guititlecolour, 0, 0xDDFF00, 0xFFFFFF); HVARP(guibuttoncolour, 0, 0xFFFF33, 0xFFFFFF); HVARP(guitextcolour, 0, 0x00FF64, 0xFFFFFF); HVARP(guislidercolour, 0, 0x00E4FF, 0xFFFFFF); HVARP(guicheckboxcolour, 0, 0xFFFF33, 0xFFFFFF); static vec menupos; static int menustart = 0; static int menutab = 1; static g3d_gui *cgui = NULL; extern int guirollovercolour; void resetcolours (){ guititlecolour = 0xDDFF00; guibuttoncolour = 0xFFFF33; guitextcolour = 0x00FF64; guislidercolour = 0x00E4FF; guicheckboxcolour = 0xFFFF33; guirollovercolour = 0x00FFC0; } COMMANDN(guiresetcolours, resetcolours, ""); struct menu : g3d_callback { char *name, *header; uint *contents, *onclear; menu() : name(NULL), header(NULL), contents(NULL), onclear(NULL) {} void gui(g3d_gui &g, bool firstpass) { cgui = &g; cgui->start(menustart, 0.03f, &menutab); cgui->tab(header ? header : name, guititlecolour); execute(contents); cgui->end(); cgui = NULL; } virtual void clear() { DELETEA(onclear); } }; struct delayedupdate { enum { INT, FLOAT, STRING, ACTION } type; ident *id; union { int i; float f; char *s; } val; delayedupdate() : type(ACTION), id(NULL) { val.s = NULL; } ~delayedupdate() { if(type == STRING || type == ACTION) DELETEA(val.s); } void schedule(const char *s) { type = ACTION; val.s = newstring(s); } void schedule(ident *var, int i) { type = INT; id = var; val.i = i; } void schedule(ident *var, float f) { type = FLOAT; id = var; val.f = f; } void schedule(ident *var, char *s) { type = STRING; id = var; val.s = newstring(s); } int getint() const { switch(type) { case INT: return val.i; case FLOAT: return int(val.f); case STRING: return int(strtol(val.s, NULL, 0)); default: return 0; } } float getfloat() const { switch(type) { case INT: return float(val.i); case FLOAT: return val.f; case STRING: return float(parsefloat(val.s)); default: return 0; } } const char *getstring() const { switch(type) { case INT: return intstr(val.i); case FLOAT: return intstr(int(floor(val.f))); case STRING: return val.s; default: return ""; } } void run() { if(type == ACTION) { if(val.s) execute(val.s); } else if(id) switch(id->type) { case ID_VAR: setvarchecked(id, getint()); break; case ID_FVAR: setfvarchecked(id, getfloat()); break; case ID_SVAR: setsvarchecked(id, getstring()); break; case ID_ALIAS: alias(id->name, getstring()); break; } } }; static hashtable guis; static vector guistack; static vector updatelater; static bool shouldclearmenu = true, clearlater = false; VARP(menudistance, 16, 40, 256); VARP(menuautoclose, 32, 120, 4096); vec menuinfrontofplayer() { vec dir; vecfromyawpitch(camera1->yaw, 0, 1, 0, dir); dir.mul(menudistance).add(camera1->o); dir.z -= player->eyeheight-1; return dir; } void popgui() { menu *m = guistack.pop(); m->clear(); } void removegui(menu *m) { loopv(guistack) if(guistack[i]==m) { guistack.remove(i); m->clear(); return; } } void pushgui(menu *m, int pos = -1) { if(guistack.empty()) { menupos = menuinfrontofplayer(); g3d_resetcursor(); } if(pos < 0) guistack.add(m); else guistack.insert(pos, m); if(pos < 0 || pos==guistack.length()-1) { menutab = 1; menustart = totalmillis; } } void restoregui(int pos) { int clear = guistack.length()-pos-1; loopi(clear) popgui(); menutab = 1; menustart = totalmillis; } void showgui(const char *name) { menu *m = guis.access(name); if(!m) return; int pos = guistack.find(m); if(pos<0) pushgui(m); else restoregui(pos); } bool activegui(const char *name) { if(!guistack.length()) return false; return !strcmp(guistack.last()->name, name); } int numgui() { return guistack.length(); } int cleargui(int n) { int clear = guistack.length(); if(mainmenu && !isconnected(true) && clear > 0 && guistack[0]->name && !strcmp(guistack[0]->name, "main")) { clear--; if(!clear) return 1; } if(n>0) clear = min(clear, n); loopi(clear) popgui(); if(!guistack.empty()) restoregui(guistack.length()-1); return clear; } void guionclear(char *action) { if(guistack.empty()) return; menu *m = guistack.last(); DELETEA(m->onclear); if(action[0]) m->onclear = compilecode(action); } void guifont(const char *name, uint *contents) { pushfont(); setfont(name); execute(contents); popfont(); } void guistayopen(uint *contents) { bool oldclearmenu = shouldclearmenu; shouldclearmenu = false; execute(contents); shouldclearmenu = oldclearmenu; } void guinoautotab(uint *contents) { if(!cgui) return; cgui->allowautotab(false); execute(contents); cgui->allowautotab(true); } //@DOC name and icon are optional void guibutton(char *name, char *action, char *icon, int *colour) { if(!cgui) return; bool hideicon = !strcmp(icon, "0"); int ret = cgui->button(name, *colour ? *colour : guibuttoncolour, hideicon ? NULL : (icon[0] ? icon : (strstr(action, "showgui") ? "menu" : "action"))); if(ret&G3D_UP) { updatelater.add().schedule(action[0] ? action : name); if(shouldclearmenu) clearlater = true; } else if(ret&G3D_ROLLOVER) { alias("guirollovername", name); alias("guirolloveraction", action); } } void guiimage(char *path, char *action, float *scale, int *overlaid, char *alt) { if(!cgui) return; Texture *t = textureload(path, 0, true, false); if(t==notexture) { if(alt[0]) t = textureload(alt, 0, true, false); if(t==notexture) return; } int ret = cgui->image(t, *scale, *overlaid!=0); if(ret&G3D_UP) { if(*action) { updatelater.add().schedule(action); if(shouldclearmenu) clearlater = true; } } else if(ret&G3D_ROLLOVER) { alias("guirolloverimgpath", path); alias("guirolloverimgaction", action); } } void guicolor(int *color) { if(cgui) { defformatstring(desc)("0x%06X", *color); cgui->text(desc, *color, NULL); } } void guitextbox(char *text, int *width, int *height, int *color) { if(cgui && text[0]) cgui->textbox(text, *width ? *width : 12, *height ? *height : 1, *color ? *color : guitextcolour); } void guitext(char *name, char *icon, int *colour) { bool hideicon = !strcmp(icon, "0"); if(cgui) cgui->text(name, *colour ? *colour : (!hideicon && icon[0] ? guibuttoncolour : guitextcolour), hideicon ? NULL : (icon[0] ? icon : "info")); } void guititle(char *name, int *colour) { if(cgui) cgui->title(name, *colour ? *colour : guititlecolour); } void guitab(char *name, int *colour) { if(cgui) cgui->tab(name, *colour ? *colour : guititlecolour); } void guibar() { if(cgui) cgui->separator(); } void guistrut(float *strut, int *alt) { if(cgui) { if(!*alt) cgui->pushlist(); cgui->strut(*strut); if(!*alt) cgui->poplist(); } } template static void updateval(char *var, T val, char *onchange) { ident *id = newident(var); updatelater.add().schedule(id, val); if(onchange[0]) updatelater.add().schedule(onchange); } static int getval(char *var) { ident *id = getident(var); if(!id) return 0; switch(id->type) { case ID_VAR: return *id->storage.i; case ID_FVAR: return int(*id->storage.f); case ID_SVAR: return parseint(*id->storage.s); case ID_ALIAS: return id->getint(); default: return 0; } } static float getfval(char *var) { ident *id = getident(var); if(!id) return 0; switch(id->type) { case ID_VAR: return *id->storage.i; case ID_FVAR: return *id->storage.f; case ID_SVAR: return parsefloat(*id->storage.s); case ID_ALIAS: return id->getfloat(); default: return 0; } } static const char *getsval(char *var) { ident *id = getident(var); if(!id) return ""; switch(id->type) { case ID_VAR: return intstr(*id->storage.i); case ID_FVAR: return floatstr(*id->storage.f); case ID_SVAR: return *id->storage.s; case ID_ALIAS: return id->getstr(); default: return ""; } } void guislider(char *var, int *min, int *max, char *onchange, int *colour, int *reverse) { if(!cgui) return; int oldval = getval(var), val = oldval, vmin = *max ? *min : getvarmin(var), vmax = *max ? *max : getvarmax(var); cgui->slider(val, vmin, vmax, *colour ? *colour : guislidercolour, NULL, *reverse ? true : false); if(val != oldval) updateval(var, val, onchange); } void guilistslider(char *var, char *list, char *onchange, int *colour, int *reverse) { if(!cgui) return; vector vals; list += strspn(list, "\n\t "); while(*list) { vals.add(parseint(list)); list += strcspn(list, "\n\t \0"); list += strspn(list, "\n\t "); } if(vals.empty()) return; int val = getval(var), oldoffset = vals.length()-1, offset = oldoffset; loopv(vals) if(val <= vals[i]) { oldoffset = offset = i; break; } defformatstring(label)("%d", val); cgui->slider(offset, 0, vals.length()-1, *colour ? *colour : guislidercolour, label, *reverse ? true: false); if(offset != oldoffset) updateval(var, vals[offset], onchange); } void guinameslider(char *var, char *names, char *list, char *onchange, int *colour) { if(!cgui) return; vector vals; list += strspn(list, "\n\t "); while(*list) { vals.add(parseint(list)); list += strcspn(list, "\n\t \0"); list += strspn(list, "\n\t "); } if(vals.empty()) return; int val = getval(var), oldoffset = vals.length()-1, offset = oldoffset; loopv(vals) if(val <= vals[i]) { oldoffset = offset = i; break; } char *label = indexlist(names, offset); cgui->slider(offset, 0, vals.length()-1, *colour ? *colour : guititlecolour, label); if(offset != oldoffset) updateval(var, vals[offset], onchange); delete[] label; } void guicheckbox(char *name, char *var, float *on, float *off, char *onchange, int *colour) { bool enabled = getfval(var)!=*off; if(cgui && cgui->button(name, *colour ? *colour : guicheckboxcolour, enabled ? "checkbox_on" : "checkbox_off")&G3D_UP) { updateval(var, enabled ? *off : (*on || *off ? *on : 1.0f), onchange); } } void guiradio(char *name, char *var, float *n, char *onchange, int *colour) { bool enabled = getfval(var)==*n; if(cgui && cgui->button(name, *colour ? *colour : guicheckboxcolour, enabled ? "radio_on" : "radio_off")&G3D_UP) { if(!enabled) updateval(var, *n, onchange); } } void guibitfield(char *name, char *var, int *mask, char *onchange, int *colour) { int val = getval(var); bool enabled = (val & *mask) != 0; if(cgui && cgui->button(name, *colour ? *colour : guibuttoncolour, enabled ? "checkbox_on" : "checkbox_off")&G3D_UP) { updateval(var, enabled ? val & ~*mask : val | *mask, onchange); } } //-ve length indicates a wrapped text field of any (approx 260 chars) length, |length| is the field width void guifield(char *var, int *maxlength, char *onchange, int *colour) { if(!cgui) return; const char *initval = getsval(var); char *result = cgui->field(var, *colour ? *colour : guibuttoncolour, *maxlength ? *maxlength : 12, 0, initval); if(result) updateval(var, result, onchange); } //-ve maxlength indicates a wrapped text field of any (approx 260 chars) length, |maxlength| is the field width void guieditor(char *name, int *maxlength, int *height, int *mode, int *colour) { if(!cgui) return; cgui->field(name, *colour ? *colour : guibuttoncolour, *maxlength ? *maxlength : 12, *height, NULL, *mode<=0 ? EDITORFOREVER : *mode); //returns a non-NULL pointer (the currentline) when the user commits, could then manipulate via text* commands } //-ve length indicates a wrapped text field of any (approx 260 chars) length, |length| is the field width void guikeyfield(char *var, int *maxlength, char *onchange) { if(!cgui) return; const char *initval = getsval(var); char *result = cgui->keyfield(var, guibuttoncolour, *maxlength ? *maxlength : -8, 0, initval); if(result) updateval(var, result, onchange); } void guilist(uint *contents) { if(!cgui) return; cgui->pushlist(); execute(contents); cgui->poplist(); } void guialign(int *align, uint *contents) { if(!cgui) return; cgui->pushlist(clamp(*align, -1, 1)); execute(contents); cgui->poplist(); } void newgui(char *name, char *contents, char *header) { menu *m = guis.access(name); if(!m) { name = newstring(name); m = &guis[name]; m->name = name; } else { DELETEA(m->header); DELETEA(m->contents); } m->header = header && header[0] ? newstring(header) : NULL; m->contents = compilecode(contents); } void guiservers() { extern char *showservers(g3d_gui *cgui); if(cgui) { char *command = showservers(cgui); if(command) { updatelater.add().schedule(command); if(shouldclearmenu) clearlater = true; } } } COMMAND(newgui, "sss"); COMMAND(guibutton, "sssi"); COMMAND(guitext, "ssi"); COMMAND(guiservers, "s"); ICOMMAND(cleargui, "i", (int *n), intret(cleargui(*n))); COMMAND(showgui, "s"); COMMAND(guionclear, "s"); COMMAND(guifont, "se"); COMMAND(guistayopen, "e"); COMMAND(guinoautotab, "e"); COMMAND(guilist, "e"); COMMAND(guialign, "ie"); COMMAND(guititle, "si"); COMMAND(guibar,""); COMMAND(guistrut,"fi"); COMMAND(guiimage,"ssfis"); COMMAND(guislider,"siisii"); COMMAND(guilistslider, "sssii"); COMMAND(guinameslider, "ssssi"); COMMAND(guiradio,"ssfsi"); COMMAND(guibitfield, "ssisi"); COMMAND(guicheckbox, "ssffsi"); COMMAND(guitab, "si"); COMMAND(guifield, "sisi"); COMMAND(guikeyfield, "sis"); COMMAND(guieditor, "siiii"); COMMAND(guicolor, "i"); COMMAND(guitextbox, "siii"); struct change { int type; const char *desc; change() {} change(int type, const char *desc) : type(type), desc(desc) {} }; static vector needsapply; static struct applymenu : menu { void gui(g3d_gui &g, bool firstpass) { if(guistack.empty()) return; g.start(menustart, 0.03f); g.text("the following settings have changed:", guitextcolour, "info"); loopv(needsapply) g.text(needsapply[i].desc, guitextcolour, "info"); g.separator(); g.text("apply changes now?", guitextcolour, "info"); if(g.button("yes", guibuttoncolour, "action")&G3D_UP) { int changetypes = 0; loopv(needsapply) changetypes |= needsapply[i].type; if(changetypes&CHANGE_GFX) updatelater.add().schedule("resetgl"); if(changetypes&CHANGE_SOUND) updatelater.add().schedule("resetsound"); clearlater = true; } if(g.button("no", guibuttoncolour, "action")&G3D_UP) clearlater = true; g.end(); } void clear() { menu::clear(); needsapply.shrink(0); } } applymenu; VARP(applydialog, 0, 1, 1); static bool processingmenu = false; void addchange(const char *desc, int type) { if(!applydialog) return; loopv(needsapply) if(!strcmp(needsapply[i].desc, desc)) return; needsapply.add(change(type, desc)); if(needsapply.length() && guistack.find(&applymenu) < 0) pushgui(&applymenu, processingmenu ? max(guistack.length()-1, 0) : -1); } void clearchanges(int type) { loopv(needsapply) { if(needsapply[i].type&type) { needsapply[i].type &= ~type; if(!needsapply[i].type) needsapply.remove(i--); } } if(needsapply.empty()) removegui(&applymenu); } void menuprocess() { processingmenu = true; int wasmain = mainmenu, level = guistack.length(); loopv(updatelater) updatelater[i].run(); updatelater.shrink(0); if(wasmain > mainmenu || clearlater) { if(wasmain > mainmenu || level==guistack.length()) { loopvrev(guistack) { menu *m = guistack[i]; if(m->onclear) { uint *action = m->onclear; m->onclear = NULL; execute(action); delete[] action; } } cleargui(level); } clearlater = false; } if(mainmenu && !isconnected(true) && guistack.empty()) showgui("main"); processingmenu = false; } VAR(mainmenu, 1, 1, 0); void clearmainmenu() { if(mainmenu && (isconnected() || haslocalclients())) { mainmenu = 0; if(!processingmenu) cleargui(); } } void g3d_mainmenu() { if(!guistack.empty()) { extern int usegui2d; if(!mainmenu && !usegui2d && camera1->o.dist(menupos) > menuautoclose) cleargui(); else g3d_addgui(guistack.last(), menupos, GUI_2D | GUI_FOLLOW); } } #endif sandboxgamemaker-2.7.1+dfsg/src/engine/renderva.cpp0000664000175000017500000027052111642642476022243 0ustar showardshoward// renderva.cpp: handles the occlusion and rendering of vertex arrays #include "engine.h" static inline void drawtris(GLsizei numindices, const GLvoid *indices, ushort minvert, ushort maxvert) { if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, minvert, maxvert, numindices, GL_UNSIGNED_SHORT, indices); else glDrawElements(GL_TRIANGLES, numindices, GL_UNSIGNED_SHORT, indices); glde++; } static inline void drawvatris(vtxarray *va, GLsizei numindices, const GLvoid *indices) { drawtris(numindices, indices, va->minvert, va->maxvert); } ///////// view frustrum culling /////////////////////// plane vfcP[5]; // perpindictular vectors to view frustrum bounding planes float vfcDfog; // far plane culling distance (fog limit). float vfcDnear[5], vfcDfar[5]; vtxarray *visibleva; bool isfoggedsphere(float rad, const vec &cv) { loopi(4) if(vfcP[i].dist(cv) < -rad) return true; float dist = vfcP[4].dist(cv); return dist < -rad || dist > vfcDfog + rad; } int isvisiblesphere(float rad, const vec &cv) { int v = VFC_FULL_VISIBLE; float dist; loopi(5) { dist = vfcP[i].dist(cv); if(dist < -rad) return VFC_NOT_VISIBLE; if(dist < rad) v = VFC_PART_VISIBLE; } dist -= vfcDfog; if(dist > rad) return VFC_FOGGED; //VFC_NOT_VISIBLE; // culling when fog is closer than size of world results in HOM if(dist > -rad) v = VFC_PART_VISIBLE; return v; } static inline int ishiddencube(const ivec &o, int size) { loopi(5) if(o.dist(vfcP[i]) < -vfcDfar[i]*size) return true; return false; } static inline int isfoggedcube(const ivec &o, int size) { loopi(4) if(o.dist(vfcP[i]) < -vfcDfar[i]*size) return true; float dist = o.dist(vfcP[4]); return dist < -vfcDfar[4]*size || dist > vfcDfog - vfcDnear[4]*size; } int isvisiblecube(const ivec &o, int size) { int v = VFC_FULL_VISIBLE; float dist; loopi(5) { dist = o.dist(vfcP[i]); if(dist < -vfcDfar[i]*size) return VFC_NOT_VISIBLE; if(dist < -vfcDnear[i]*size) v = VFC_PART_VISIBLE; } dist -= vfcDfog; if(dist > -vfcDnear[4]*size) return VFC_FOGGED; if(dist > -vfcDfar[4]*size) v = VFC_PART_VISIBLE; return v; } float vadist(vtxarray *va, const vec &p) { return p.dist_to_bb(va->bbmin, va->bbmax); } #define VASORTSIZE 64 static vtxarray *vasort[VASORTSIZE]; void addvisibleva(vtxarray *va) { float dist = vadist(va, camera1->o); va->distance = int(dist); /*cv.dist(camera1->o) - va->size*SQRT3/2*/ int hash = min(int(dist*VASORTSIZE/worldsize), VASORTSIZE-1); vtxarray **prev = &vasort[hash], *cur = vasort[hash]; while(cur && va->distance >= cur->distance) { prev = &cur->next; cur = cur->next; } va->next = *prev; *prev = va; } void sortvisiblevas() { visibleva = NULL; vtxarray **last = &visibleva; loopi(VASORTSIZE) if(vasort[i]) { vtxarray *va = vasort[i]; *last = va; while(va->next) va = va->next; last = &va->next; } } void findvisiblevas(vector &vas, bool resetocclude = false) { loopv(vas) { vtxarray &v = *vas[i]; int prevvfc = resetocclude ? VFC_NOT_VISIBLE : v.curvfc; v.curvfc = isvisiblecube(v.o, v.size); if(v.curvfc!=VFC_NOT_VISIBLE) { if(pvsoccluded(v.o, v.size)) { v.curvfc += PVS_FULL_VISIBLE - VFC_FULL_VISIBLE; continue; } addvisibleva(&v); if(v.children.length()) findvisiblevas(v.children, prevvfc>=VFC_NOT_VISIBLE); if(prevvfc>=VFC_NOT_VISIBLE) { v.occluded = !v.texs ? OCCLUDE_GEOM : OCCLUDE_NOTHING; v.query = NULL; } } } } void calcvfcD() { loopi(5) { plane &p = vfcP[i]; vfcDnear[i] = vfcDfar[i] = 0; loopk(3) if(p[k] > 0) vfcDfar[i] += p[k]; else vfcDnear[i] += p[k]; } } void setvfcP(float z, const vec &bbmin, const vec &bbmax) { vec4 px = mvpmatrix.getrow(0), py = mvpmatrix.getrow(1), pz = mvpmatrix.getrow(2), pw = mvpmatrix.getrow(3); vfcP[0] = plane(vec4(pw).mul(-bbmin.x).add(px)).normalize(); // left plane vfcP[1] = plane(vec4(pw).mul(bbmax.x).sub(px)).normalize(); // right plane vfcP[2] = plane(vec4(pw).mul(-bbmin.y).add(py)).normalize(); // bottom plane vfcP[3] = plane(vec4(pw).mul(bbmax.y).sub(py)).normalize(); // top plane vfcP[4] = plane(vec4(pw).add(pz)).normalize(); // near/far planes if(z >= 0) loopi(5) vfcP[i].reflectz(z); extern int fog; vfcDfog = fog; calcvfcD(); } plane oldvfcP[5]; void savevfcP() { memcpy(oldvfcP, vfcP, sizeof(vfcP)); } void restorevfcP() { memcpy(vfcP, oldvfcP, sizeof(vfcP)); calcvfcD(); } extern vector varoot, valist; void visiblecubes(bool cull) { memset(vasort, 0, sizeof(vasort)); if(cull) { setvfcP(); findvisiblevas(varoot); sortvisiblevas(); } else { memset(vfcP, 0, sizeof(vfcP)); vfcDfog = 1000000; memset(vfcDnear, 0, sizeof(vfcDnear)); memset(vfcDfar, 0, sizeof(vfcDfar)); visibleva = NULL; loopv(valist) { vtxarray *va = valist[i]; va->distance = 0; va->curvfc = VFC_FULL_VISIBLE; va->occluded = !va->texs ? OCCLUDE_GEOM : OCCLUDE_NOTHING; va->query = NULL; va->next = visibleva; visibleva = va; } } } static inline bool insideva(const vtxarray *va, const vec &v, int margin = 2) { int size = va->size + margin; return v.x>=va->o.x-margin && v.y>=va->o.y-margin && v.z>=va->o.z-margin && v.x<=va->o.x+size && v.y<=va->o.y+size && v.z<=va->o.z+size; } ///////// occlusion queries ///////////// #define MAXQUERY 2048 struct queryframe { int cur, max; occludequery queries[MAXQUERY]; }; static queryframe queryframes[2] = {{0, 0}, {0, 0}}; static uint flipquery = 0; int getnumqueries() { return queryframes[flipquery].cur; } void flipqueries() { flipquery = (flipquery + 1) % 2; queryframe &qf = queryframes[flipquery]; loopi(qf.cur) qf.queries[i].owner = NULL; qf.cur = 0; } occludequery *newquery(void *owner) { queryframe &qf = queryframes[flipquery]; if(qf.cur >= qf.max) { if(qf.max >= MAXQUERY) return NULL; glGenQueries_(1, &qf.queries[qf.max++].id); } occludequery *query = &qf.queries[qf.cur++]; query->owner = owner; query->fragments = -1; return query; } void resetqueries() { loopi(2) loopj(queryframes[i].max) queryframes[i].queries[j].owner = NULL; } void clearqueries() { loopi(2) { queryframe &qf = queryframes[i]; loopj(qf.max) { glDeleteQueries_(1, &qf.queries[j].id); qf.queries[j].owner = NULL; } qf.cur = qf.max = 0; } } VAR(oqfrags, 0, 8, 64); VAR(oqwait, 0, 1, 1); bool checkquery(occludequery *query, bool nowait) { GLuint fragments; if(query->fragments >= 0) fragments = query->fragments; else { if(nowait || !oqwait) { GLint avail; glGetQueryObjectiv_(query->id, GL_QUERY_RESULT_AVAILABLE, &avail); if(!avail) return false; } glGetQueryObjectuiv_(query->id, GL_QUERY_RESULT_ARB, &fragments); query->fragments = fragments; } return fragments < uint(oqfrags); } void drawbb(const ivec &bo, const ivec &br, const vec &camera) { glBegin(GL_QUADS); loopi(6) { int dim = dimension(i), coord = dimcoord(i); if(coord) { if(camera[dim] < bo[dim] + br[dim]) continue; } else if(camera[dim] > bo[dim]) continue; loopj(4) { const ivec &cc = facecoords[i][j]; glVertex3f(cc.x ? bo.x+br.x : bo.x, cc.y ? bo.y+br.y : bo.y, cc.z ? bo.z+br.z : bo.z); } xtraverts += 4; } glEnd(); } extern int octaentsize; static octaentities *visiblemms, **lastvisiblemms; static inline bool insideoe(const octaentities *oe, const vec &v, int margin = 1) { return v.x>=oe->bbmin.x-margin && v.y>=oe->bbmin.y-margin && v.z>=oe->bbmin.z-margin && v.x<=oe->bbmax.x+margin && v.y<=oe->bbmax.y+margin && v.z<=oe->bbmax.z+margin; } void findvisiblemms(const vector &ents) { for(vtxarray *va = visibleva; va; va = va->next) { if(va->mapmodels.empty() || va->curvfc >= VFC_FOGGED || va->occluded >= OCCLUDE_BB) continue; loopv(va->mapmodels) { octaentities *oe = va->mapmodels[i]; if(isfoggedcube(oe->o, oe->size) || pvsoccluded(oe->bbmin, ivec(oe->bbmax).sub(oe->bbmin))) continue; bool occluded = oe->query && oe->query->owner == oe && checkquery(oe->query); if(occluded) { oe->distance = -1; oe->next = NULL; *lastvisiblemms = oe; lastvisiblemms = &oe->next; } else { int visible = 0; loopv(oe->mapmodels) { extentity &e = *ents[oe->mapmodels[i]]; if(e.flags&extentity::F_NOVIS) continue; e.visible = true; ++visible; } if(!visible) continue; oe->distance = int(camera1->o.dist_to_bb(oe->o, oe->size)); octaentities **prev = &visiblemms, *cur = visiblemms; while(cur && cur->distance >= 0 && oe->distance > cur->distance) { prev = &cur->next; cur = cur->next; } if(*prev == NULL) lastvisiblemms = &oe->next; oe->next = *prev; *prev = oe; } } } } VAR(oqmm, 0, 4, 8); extern bool getentboundingbox(extentity &e, ivec &o, ivec &r); void rendermapmodel(extentity &e) { int anim = ANIM_MAPMODEL|ANIM_LOOP, basetime = 0; if(e.flags&extentity::F_ANIM) entities::animatemapmodel(e, anim, basetime); mapmodelinfo &mmi = getmminfo(e.attr[1]); if(&mmi) rendermodel(&e.light, mmi.name, anim, e.o, e.attr[0], 0, 0, MDL_CULL_VFC | MDL_CULL_DIST | MDL_DYNLIGHT, NULL, NULL, basetime, 0, 1, e.attr[5]? e.attr[5] : 0xFFFFFF); } extern int reflectdist; vtxarray *reflectedva; void renderreflectedmapmodels() { const vector &ents = entities::getents(); octaentities *mms = visiblemms; if(reflecting) { octaentities **lastmms = &mms; for(vtxarray *va = reflectedva; va; va = va->rnext) { if(va->mapmodels.empty() || va->distance > reflectdist) continue; loopv(va->mapmodels) { octaentities *oe = va->mapmodels[i]; *lastmms = oe; lastmms = &oe->rnext; } } *lastmms = NULL; } for(octaentities *oe = mms; oe; oe = reflecting ? oe->rnext : oe->next) { if(reflecting || refracting>0 ? oe->bbmax.z <= reflectz : oe->bbmin.z >= reflectz) continue; if(isfoggedcube(oe->o, oe->size)) continue; loopv(oe->mapmodels) { extentity &e = *ents[oe->mapmodels[i]]; if(e.visible || e.flags&extentity::F_NOVIS) continue; e.visible = true; } } if(mms) { startmodelbatches(); for(octaentities *oe = mms; oe; oe = reflecting ? oe->rnext : oe->next) { loopv(oe->mapmodels) { extentity &e = *ents[oe->mapmodels[i]]; if(!e.visible) continue; rendermapmodel(e); e.visible = false; } } endmodelbatches(); } } void rendermapmodels() { const vector &ents = entities::getents(); visiblemms = NULL; lastvisiblemms = &visiblemms; findvisiblemms(ents); static int skipoq = 0; bool doquery = hasOQ && oqfrags && oqmm; startmodelbatches(); for(octaentities *oe = visiblemms; oe; oe = oe->next) if(oe->distance>=0) { bool rendered = false; loopv(oe->mapmodels) { extentity &e = *ents[oe->mapmodels[i]]; if(!e.visible) continue; if(!rendered) { rendered = true; oe->query = doquery && oe->distance>0 && !(++skipoq%oqmm) ? newquery(oe) : NULL; if(oe->query) startmodelquery(oe->query); } rendermapmodel(e); e.visible = false; } if(rendered && oe->query) endmodelquery(); } endmodelbatches(); bool colormask = true; for(octaentities *oe = visiblemms; oe; oe = oe->next) if(oe->distance<0) { oe->query = doquery && !insideoe(oe, camera1->o) ? newquery(oe) : NULL; if(!oe->query) continue; if(colormask) { glDepthMask(GL_FALSE); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); nocolorshader->set(); colormask = false; } startquery(oe->query); drawbb(oe->bbmin, ivec(oe->bbmax).sub(oe->bbmin)); endquery(oe->query); } if(!colormask) { glDepthMask(GL_TRUE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, fading ? GL_FALSE : GL_TRUE); } } static inline bool bbinsideva(const ivec &bo, const ivec &br, vtxarray *va) { return bo.x >= va->bbmin.x && bo.y >= va->bbmin.y && va->o.z >= va->bbmin.z && bo.x + br.x <= va->bbmax.x && bo.y + br.y <= va->bbmax.y && bo.z + br.z <= va->bbmax.z; } static inline bool bboccluded(const ivec &bo, const ivec &br, cube *c, const ivec &o, int size) { loopoctabox(o, size, bo, br) { ivec co(i, o.x, o.y, o.z, size); if(c[i].ext && c[i].ext->va) { vtxarray *va = c[i].ext->va; if(va->curvfc >= VFC_FOGGED || (va->occluded >= OCCLUDE_BB && bbinsideva(bo, br, va))) continue; } if(c[i].children && bboccluded(bo, br, c[i].children, co, size>>1)) continue; return false; } return true; } bool bboccluded(const ivec &bo, const ivec &br) { int diff = (bo.x^(bo.x+br.x)) | (bo.y^(bo.y+br.y)) | (bo.z^(bo.z+br.z)); if(diff&~((1<ext && c->ext->va) { vtxarray *va = c->ext->va; if(va->curvfc >= VFC_FOGGED || (va->occluded >= OCCLUDE_BB && bbinsideva(bo, br, va))) return true; } scale--; while(c->children && !(diff&(1<children[octastep(bo.x, bo.y, bo.z, scale)]; if(c->ext && c->ext->va) { vtxarray *va = c->ext->va; if(va->curvfc >= VFC_FOGGED || (va->occluded >= OCCLUDE_BB && bbinsideva(bo, br, va))) return true; } scale--; } if(c->children) return bboccluded(bo, br, c->children, ivec(bo).mask(~((2<=2) { glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glEnable(GL_TEXTURE_GEN_T); } } static void disabletexgen(int dims = 2) { glDisable(GL_TEXTURE_GEN_S); if(dims>=2) glDisable(GL_TEXTURE_GEN_T); } VAR(outline, 0, 0, 1); HVARP(outlinecolour, 0, 0, 0xFFFFFF); VAR(dtoutline, 0, 1, 1); void renderoutline() { lineshader->set(); glDisable(GL_TEXTURE_2D); glEnableClientState(GL_VERTEX_ARRAY); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor3ub((outlinecolour>>16)&0xFF, (outlinecolour>>8)&0xFF, outlinecolour&0xFF); enablepolygonoffset(GL_POLYGON_OFFSET_LINE); if(!dtoutline) glDisable(GL_DEPTH_TEST); vtxarray *prev = NULL; for(vtxarray *va = visibleva; va; va = va->next) { if(va->occluded >= OCCLUDE_BB) continue; if(!va->alphaback && !va->alphafront && (!va->texs || va->occluded >= OCCLUDE_GEOM)) continue; if(!prev || va->vbuf != prev->vbuf) { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); } glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); } if(va->texs && va->occluded < OCCLUDE_GEOM) { drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; } if(va->alphaback || va->alphafront) { drawvatris(va, 3*(va->alphabacktris + va->alphafronttris), &va->edata[3*(va->tris + va->blendtris)]); xtravertsva += 3*(va->alphabacktris + va->alphafronttris); } prev = va; } if(!dtoutline) glEnable(GL_DEPTH_TEST); disablepolygonoffset(GL_POLYGON_OFFSET_LINE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); glEnable(GL_TEXTURE_2D); defaultshader->set(); } HVAR(blendbrushcolor, 0, 0x0000C0, 0xFFFFFF); void renderblendbrush(GLuint tex, float x, float y, float w, float h) { static Shader *blendbrushshader = NULL; if(!blendbrushshader) blendbrushshader = lookupshaderbyname("blendbrush"); blendbrushshader->set(); glEnableClientState(GL_VERTEX_ARRAY); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tex); glColor4ub((blendbrushcolor>>16)&0xFF, (blendbrushcolor>>8)&0xFF, blendbrushcolor&0xFF, 0x40); GLfloat s[4] = { 1.0f/w, 0, 0, -x/w }, t[4] = { 0, 1.0f/h, 0, -y/h }; if(renderpath==R_FIXEDFUNCTION) { setuptexgen(); glTexGenfv(GL_S, GL_OBJECT_PLANE, s); glTexGenfv(GL_T, GL_OBJECT_PLANE, t); } else { setlocalparamfv("texgenS", SHPARAM_VERTEX, 0, s); setlocalparamfv("texgenT", SHPARAM_VERTEX, 1, t); } vtxarray *prev = NULL; for(vtxarray *va = visibleva; va; va = va->next) { if(!va->texs || va->occluded >= OCCLUDE_GEOM) continue; if(va->o.x + va->size <= x || va->o.y + va->size <= y || va->o.x >= x + w || va->o.y >= y + h) continue; if(!prev || va->vbuf != prev->vbuf) { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); } glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); } drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; prev = va; } if(renderpath==R_FIXEDFUNCTION) disabletexgen(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); glDepthFunc(GL_LESS); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); notextureshader->set(); } void rendershadowmapreceivers() { if(!hasBE) return; static Shader *shadowmapshader = NULL; if(!shadowmapshader) shadowmapshader = lookupshaderbyname("shadowmapreceiver"); shadowmapshader->set(); glDisable(GL_TEXTURE_2D); glEnableClientState(GL_VERTEX_ARRAY); glCullFace(GL_FRONT); glDepthMask(GL_FALSE); glDepthFunc(GL_GREATER); extern int ati_minmax_bug; if(!ati_minmax_bug) glColorMask(GL_FALSE, GL_FALSE, GL_TRUE, GL_FALSE); glEnable(GL_BLEND); glBlendEquation_(GL_MAX_EXT); glBlendFunc(GL_ONE, GL_ONE); vtxarray *prev = NULL; for(vtxarray *va = visibleva; va; va = va->next) { if(!va->texs || va->curvfc >= VFC_FOGGED || !isshadowmapreceiver(va)) continue; if(!prev || va->vbuf != prev->vbuf) { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); } glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); } drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; prev = va; } glDisable(GL_BLEND); glBlendEquation_(GL_FUNC_ADD_EXT); glCullFace(GL_BACK); glDepthMask(GL_TRUE); glDepthFunc(GL_LESS); if(!ati_minmax_bug) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); glEnable(GL_TEXTURE_2D); } void renderdepthobstacles(const vec &bbmin, const vec &bbmax, float scale, float *ranges, int numranges) { float scales[4] = { 0, 0, 0, 0 }, offsets[4] = { 0, 0, 0, 0 }; if(numranges < 0) { SETSHADER(depthfxsplitworld); loopi(-numranges) { if(!i) scales[i] = 1.0f/scale; else scales[i] = scales[i-1]*256; } } else { SETSHADER(depthfxworld); if(!numranges) loopi(4) scales[i] = 1.0f/scale; else loopi(numranges) { scales[i] = 1.0f/scale; offsets[i] = -ranges[i]/scale; } } setlocalparamfv("depthscale", SHPARAM_VERTEX, 0, scales); setlocalparamfv("depthoffsets", SHPARAM_VERTEX, 1, offsets); glDisable(GL_TEXTURE_2D); glEnableClientState(GL_VERTEX_ARRAY); vtxarray *prev = NULL; for(vtxarray *va = visibleva; va; va = va->next) { if(!va->texs || va->occluded >= OCCLUDE_GEOM || va->o.x > bbmax.x || va->o.y > bbmax.y || va->o.z > bbmax.z || va->o.x + va->size < bbmin.x || va->o.y + va->size < bbmin.y || va->o.z + va->size < bbmin.z) continue; if(!prev || va->vbuf != prev->vbuf) { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); } glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); } drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; if(va->alphabacktris + va->alphafronttris > 0) { drawvatris(va, 3*(va->alphabacktris + va->alphafronttris), va->edata + 3*(va->tris + va->blendtris)); xtravertsva += 3*(va->alphabacktris + va->alphafronttris); } prev = va; } if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); glEnable(GL_TEXTURE_2D); defaultshader->set(); } VAR(oqdist, 0, 256, 1024); VAR(zpass, 0, 1, 1); VAR(glowpass, 0, 1, 1); VAR(envpass, 0, 1, 1); struct renderstate { bool colormask, depthmask, blending, mtglow; int skipped, alphaing; GLuint vbuf; int diffusetmu, lightmaptmu, glowtmu, causticstmu; GLfloat color[4], fogcolor[4]; vec colorscale, glowcolor, envscale, lightcolor; float alphascale; GLuint textures[8]; Slot *slot, *texgenslot; VSlot *vslot, *texgenvslot; float texgenscrollS, texgenscrollT; int texgendim; bool mttexgen, specmask; int visibledynlights; uint dynlightmask; vec dynlightpos; float dynlightradius; renderstate() : colormask(true), depthmask(true), blending(false), mtglow(false), skipped(0), alphaing(0), vbuf(0), diffusetmu(0), lightmaptmu(1), glowtmu(-1), causticstmu(-1), colorscale(1, 1, 1), glowcolor(1, 1, 1), envscale(0, 0, 0), alphascale(0), slot(NULL), texgenslot(NULL), vslot(NULL), texgenvslot(NULL), texgenscrollS(0), texgenscrollT(0), texgendim(-1), mttexgen(false), specmask(false), visibledynlights(0), dynlightmask(0) { loopk(4) color[k] = 1; loopk(8) textures[k] = 0; } }; void renderquery(renderstate &cur, occludequery *query, vtxarray *va, bool full = true) { nocolorshader->set(); if(cur.colormask) { cur.colormask = false; glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } if(cur.depthmask) { cur.depthmask = false; glDepthMask(GL_FALSE); } vec camera(camera1->o); if(reflecting) camera.z = reflectz; startquery(query); if(full) drawbb(ivec(va->bbmin).sub(1), ivec(va->bbmax).sub(va->bbmin).add(2), camera); else drawbb(va->geommin, ivec(va->geommax).sub(va->geommin), camera); endquery(query); } enum { RENDERPASS_LIGHTMAP = 0, RENDERPASS_COLOR, RENDERPASS_Z, RENDERPASS_GLOW, RENDERPASS_ENVMAP, RENDERPASS_CAUSTICS, RENDERPASS_FOG, RENDERPASS_SHADOWMAP, RENDERPASS_DYNLIGHT, RENDERPASS_LIGHTMAP_BLEND }; struct geombatch { const elementset &es; VSlot &vslot; ushort *edata; vtxarray *va; int next, batch; geombatch(const elementset &es, ushort *edata, vtxarray *va) : es(es), vslot(lookupvslot(es.texture)), edata(edata), va(va), next(-1), batch(-1) {} int compare(const geombatch &b) const { if(va->vbuf < b.va->vbuf) return -1; if(va->vbuf > b.va->vbuf) return 1; if(renderpath!=R_FIXEDFUNCTION) { if(va->dynlightmask < b.va->dynlightmask) return -1; if(va->dynlightmask > b.va->dynlightmask) return 1; if(vslot.slot->shader < b.vslot.slot->shader) return -1; if(vslot.slot->shader > b.vslot.slot->shader) return 1; if(vslot.slot->params.length() < b.vslot.slot->params.length()) return -1; if(vslot.slot->params.length() > b.vslot.slot->params.length()) return 1; } if(es.texture < b.es.texture) return -1; if(es.texture > b.es.texture) return 1; if(es.lmid < b.es.lmid) return -1; if(es.lmid > b.es.lmid) return 1; if(es.envmap < b.es.envmap) return -1; if(es.envmap > b.es.envmap) return 1; if(es.dim < b.es.dim) return -1; if(es.dim > b.es.dim) return 1; return 0; } }; static vector geombatches; static int firstbatch = -1, numbatches = 0; static void mergetexs(renderstate &cur, vtxarray *va, elementset *texs = NULL, int numtexs = 0, ushort *edata = NULL) { if(!texs) { texs = va->eslist; numtexs = va->texs; edata = va->edata; if(cur.alphaing) { texs += va->texs + va->blends; edata += 3*(va->tris + va->blendtris); numtexs = va->alphaback; if(cur.alphaing > 1) numtexs += va->alphafront; } } if(firstbatch < 0) { firstbatch = geombatches.length(); numbatches = numtexs; loopi(numtexs-1) { geombatches.add(geombatch(texs[i], edata, va)).next = i+1; edata += texs[i].length[1]; } geombatches.add(geombatch(texs[numtexs-1], edata, va)); return; } int prevbatch = -1, curbatch = firstbatch, curtex = 0; do { geombatch &b = geombatches.add(geombatch(texs[curtex], edata, va)); edata += texs[curtex].length[1]; int dir = -1; while(curbatch >= 0) { dir = b.compare(geombatches[curbatch]); if(dir <= 0) break; prevbatch = curbatch; curbatch = geombatches[curbatch].next; } if(!dir) { int last = curbatch, next; for(;;) { next = geombatches[last].batch; if(next < 0) break; last = next; } if(last==curbatch) { b.batch = curbatch; b.next = geombatches[curbatch].next; if(prevbatch < 0) firstbatch = geombatches.length()-1; else geombatches[prevbatch].next = geombatches.length()-1; curbatch = geombatches.length()-1; } else { b.batch = next; geombatches[last].batch = geombatches.length()-1; } } else { numbatches++; b.next = curbatch; if(prevbatch < 0) firstbatch = geombatches.length()-1; else geombatches[prevbatch].next = geombatches.length()-1; prevbatch = geombatches.length()-1; } } while(++curtex < numtexs); } static void mergeglowtexs(renderstate &cur, vtxarray *va) { int start = -1; ushort *edata = va->edata, *startdata = NULL; int firsttex = 0, numtexs = va->texs; if(cur.alphaing) { firsttex += va->texs + va->blends; edata += 3*(va->tris + va->blendtris); numtexs = va->alphaback; if(cur.alphaing > 1) numtexs += va->alphafront; } for(int i = firsttex; i < firsttex + numtexs; i++) { elementset &es = va->eslist[i]; VSlot &vslot = lookupvslot(es.texture, false); if(vslot.slot->texmask&(1<=0) { mergetexs(cur, va, &va->eslist[start], i-start, startdata); start = -1; } edata += es.length[1]; } if(start>=0) mergetexs(cur, va, &va->eslist[start], firsttex+numtexs-start, startdata); } static void mergeenvmaptexs(renderstate &cur, vtxarray *va) { int start = -1; ushort *edata = va->edata, *startdata = NULL; int firsttex = 0, numtexs = va->texs; if(cur.alphaing) { firsttex += va->texs + va->blends; edata += 3*(va->tris + va->blendtris); numtexs = va->alphaback; if(cur.alphaing > 1) numtexs += va->alphafront; } for(int i = firsttex; i < firsttex + numtexs; i++) { elementset &es = va->eslist[i]; VSlot &vslot = lookupvslot(es.texture, false); if(vslot.slot->shader->type&SHADER_ENVMAP && vslot.skipped&(1<=0) { mergetexs(cur, va, &va->eslist[start], i-start, startdata); start = -1; } edata += es.length[1]; } if(start>=0) mergetexs(cur, va, &va->eslist[start], firsttex+numtexs-start, startdata); } static void changedynlightpos(renderstate &cur) { GLfloat tx[4] = { 0.5f/cur.dynlightradius, 0, 0, 0.5f - 0.5f*cur.dynlightpos.x/cur.dynlightradius }, ty[4] = { 0, 0.5f/cur.dynlightradius, 0, 0.5f - 0.5f*cur.dynlightpos.y/cur.dynlightradius }, tz[4] = { 0, 0, 0.5f/cur.dynlightradius, 0.5f - 0.5f*cur.dynlightpos.z/cur.dynlightradius }; glActiveTexture_(GL_TEXTURE0_ARB); glTexGenfv(GL_S, GL_OBJECT_PLANE, tx); glTexGenfv(GL_T, GL_OBJECT_PLANE, ty); glActiveTexture_(GL_TEXTURE1_ARB); glTexGenfv(GL_S, GL_OBJECT_PLANE, tz); glActiveTexture_(GL_TEXTURE2_ARB); } static void changevbuf(renderstate &cur, int pass, vtxarray *va) { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); } cur.vbuf = va->vbuf; glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); if(pass==RENDERPASS_LIGHTMAP) { glTexCoordPointer(2, GL_FLOAT, VTXSIZE, &va->vdata[0].u); if(cur.glowtmu >= 0) { glClientActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glTexCoordPointer(2, GL_FLOAT, VTXSIZE, &va->vdata[0].u); } glClientActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); glTexCoordPointer(2, renderpath==R_FIXEDFUNCTION ? GL_FLOAT : GL_SHORT, VTXSIZE, &va->vdata[0].lmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); if(renderpath!=R_FIXEDFUNCTION) { glNormalPointer(GL_BYTE, VTXSIZE, va->vdata[0].norm.v); glColorPointer(4, GL_UNSIGNED_BYTE, VTXSIZE, va->vdata[0].tangent.v); } else if(cur.glowtmu >= 0 && hasCM && maxtmus >= 2) glNormalPointer(GL_BYTE, VTXSIZE, va->vdata[0].norm.v); } else if(pass == RENDERPASS_ENVMAP) { glTexCoordPointer(2, GL_FLOAT, VTXSIZE, &va->vdata[0].u); glNormalPointer(GL_BYTE, VTXSIZE, va->vdata[0].norm.v); } else if(pass==RENDERPASS_COLOR || pass==RENDERPASS_GLOW || pass==RENDERPASS_DYNLIGHT) glTexCoordPointer(2, GL_FLOAT, VTXSIZE, &va->vdata[0].u); } static void changebatchtmus(renderstate &cur, int pass, geombatch &b) { bool changed = false; extern bool brightengeom; extern int fullbright; int lmid = brightengeom && (b.es.lmid < LMID_RESERVED || fullbright) ? LMID_BRIGHT : b.es.lmid; if(cur.textures[cur.lightmaptmu]!=lightmaptexs[lmid].id) { glActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); glBindTexture(GL_TEXTURE_2D, cur.textures[cur.lightmaptmu] = lightmaptexs[lmid].id); changed = true; } if(renderpath==R_FIXEDFUNCTION) { if(b.vslot.slot->shader->type&SHADER_ENVMAP && b.es.envmap!=EMID_CUSTOM && cur.envscale.x) { GLuint emtex = lookupenvmap(b.es.envmap); if(cur.textures[cur.glowtmu]!=emtex) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cur.textures[cur.glowtmu] = emtex); changed = true; } } } else { int tmu = cur.lightmaptmu+1; if(b.vslot.slot->shader->type&SHADER_NORMALSLMS) { if(cur.textures[tmu]!=lightmaptexs[lmid+1].id) { glActiveTexture_(GL_TEXTURE0_ARB+tmu); glBindTexture(GL_TEXTURE_2D, cur.textures[tmu] = lightmaptexs[lmid+1].id); changed = true; } tmu++; } if(b.vslot.slot->shader->type&SHADER_ENVMAP && b.es.envmap!=EMID_CUSTOM) { GLuint emtex = lookupenvmap(b.es.envmap); if(cur.textures[tmu]!=emtex) { glActiveTexture_(GL_TEXTURE0_ARB+tmu); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cur.textures[tmu] = emtex); changed = true; } } } if(changed) glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); if(cur.dynlightmask != b.va->dynlightmask) { cur.visibledynlights = setdynlights(b.va); cur.dynlightmask = b.va->dynlightmask; } } static inline void disableenv(renderstate &cur) { glDisable(GL_TEXTURE_CUBE_MAP_ARB); glDisableClientState(GL_NORMAL_ARRAY); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_R); } static inline void enableenv(renderstate &cur) { setuptmu(cur.glowtmu, "T , P @ Pa", "= Pa"); glEnableClientState(GL_NORMAL_ARRAY); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_R); glMatrixMode(GL_TEXTURE); glLoadMatrixf(envmatrix.v); glMatrixMode(GL_MODELVIEW); glEnable(GL_TEXTURE_CUBE_MAP_ARB); } static inline void disableglow(renderstate &cur) { glDisable(GL_TEXTURE_2D); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } static inline void enableglow(renderstate &cur, bool shouldsetuptmu = true) { if(shouldsetuptmu) setuptmu(cur.glowtmu, "P + T", "= Pa"); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glEnable(GL_TEXTURE_2D); } static void changeenv(renderstate &cur, int pass, Slot &slot, VSlot &vslot, geombatch *b = NULL) { if(pass==RENDERPASS_ENVMAP) { bool specmask = slot.sts.length() && slot.sts[0].t->bpp >= 4; if(cur.envscale != vslot.envscale) { if(vslot.envscale.x != vslot.envscale.y || vslot.envscale.y != vslot.envscale.z) { if(hasBC && !specmask) { if(cur.envscale.x == cur.envscale.y && cur.envscale.y == cur.envscale.z) glBlendFunc(GL_CONSTANT_COLOR_EXT, GL_ONE_MINUS_CONSTANT_COLOR_EXT); glBlendColor_(vslot.envscale.x, vslot.envscale.y, vslot.envscale.z, 1); cur.envscale = vslot.envscale; } else { if(cur.envscale.x != cur.envscale.y || cur.envscale.y != cur.envscale.z) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // fake it, take the average and do a constant blend float envscale = (min(vslot.envscale.x, min(vslot.envscale.y, vslot.envscale.z)) + max(vslot.envscale.x, max(vslot.envscale.y, vslot.envscale.z)))/2; glColor4f(1, 1, 1, envscale); cur.envscale = vec(envscale, envscale, envscale); } } else { if(cur.envscale.x != cur.envscale.y || cur.envscale.y != cur.envscale.z) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 1, 1, vslot.envscale.x); cur.envscale = vslot.envscale; } } if(cur.specmask != specmask) { if(!specmask) glDisable(GL_TEXTURE_2D); else if(specmask) glEnable(GL_TEXTURE_2D); cur.specmask = specmask; } GLuint tex = 0; if(b) { if(b->es.envmap==EMID_CUSTOM) return; tex = lookupenvmap(b->es.envmap); } else { if(!(slot.texmask&(1<id; break; } } } glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cur.textures[cur.glowtmu] = tex); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); return; } if(slot.texmask&(1<= 0 || vslot.envscale.x != vslot.envscale.y || vslot.envscale.y != vslot.envscale.z || !vslot.envscale.x) { cur.skipped |= 1<id) glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cur.textures[cur.glowtmu] = t.t->id); break; } } } static void changeglow(renderstate &cur, int pass, Slot &slot, VSlot &vslot) { vec color = vslot.glowcolor; if(vslot.pulseglowspeed) { float k = lastmillis*vslot.pulseglowspeed; k -= floor(k); k = fabs(k*2 - 1); color.lerp(color, vslot.pulseglowcolor, k); } if(pass==RENDERPASS_GLOW) { if(cur.glowcolor!=color) glColor3fv(color.v); } else { if(cur.glowcolor!=color || cur.envscale.x) { if(color==vec(1, 1, 1)) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); setuptmu(cur.glowtmu, "P + T", "= Pa"); } else if((hasTE3 || hasTE4) && cur.colorscale == vec(1, 1, 1)) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); if(cur.glowcolor==vec(1, 1, 1)) { if(hasTE3) setuptmu(cur.glowtmu, "TPC3", "= Pa"); else if(hasTE4) setuptmu(cur.glowtmu, "TCP14", "= Pa"); } memcpy(cur.color, color.v, sizeof(color)); glColor4fv(cur.color); } else { cur.skipped |= 1<id) glBindTexture(GL_TEXTURE_2D, cur.textures[cur.glowtmu] = t.t->id); break; } } cur.glowcolor = color; } static void changecolor(renderstate &cur, int pass, Slot &slot, VSlot &vslot) { if(vslot.colorscale == vec(1, 1, 1)) { if(cur.causticstmu >= 0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.causticstmu+1); setuptmu(cur.causticstmu+1, "= P"); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } else if(pass==RENDERPASS_LIGHTMAP) setuptmu(cur.diffusetmu, "= T"); } else if(cur.colorscale == vec(1, 1, 1)) { if(cur.causticstmu >= 0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.causticstmu+1); setuptmu(cur.causticstmu+1, "C * P"); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } else if(pass==RENDERPASS_LIGHTMAP) setuptmu(cur.diffusetmu, "C * T"); if(cur.mtglow && !cur.envscale.x && cur.glowcolor != vec(1, 1, 1)) { cur.glowcolor = vec(-1, -1, -1); cur.mtglow = false; glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glDisable(GL_TEXTURE_2D); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } } cur.colorscale = vslot.colorscale; memcpy(cur.color, vslot.colorscale.v, sizeof(vslot.colorscale)); } static void changeslottmus(renderstate &cur, int pass, Slot &slot, VSlot &vslot) { if(pass==RENDERPASS_LIGHTMAP || pass==RENDERPASS_COLOR || pass==RENDERPASS_ENVMAP || pass==RENDERPASS_DYNLIGHT) { GLuint diffusetex = slot.sts.empty() ? notexture->id : slot.sts[0].t->id; if(cur.textures[cur.diffusetmu]!=diffusetex) glBindTexture(GL_TEXTURE_2D, cur.textures[cur.diffusetmu] = diffusetex); } if(renderpath==R_FIXEDFUNCTION) { if(pass==RENDERPASS_LIGHTMAP || pass==RENDERPASS_COLOR) { if(cur.alphaing) { float alpha = cur.alphaing > 1 ? vslot.alphafront : vslot.alphaback; if(cur.colorscale != vslot.colorscale) { changecolor(cur, pass, slot, vslot); if(cur.alphascale != alpha) { cur.alphascale = alpha; cur.color[3] = alpha; } glColor4fv(cur.color); } else if(cur.alphascale != alpha) { cur.alphascale = alpha; cur.color[3] = alpha; glColor4fv(cur.color); } } else if(cur.colorscale != vslot.colorscale) { changecolor(cur, pass, slot, vslot); glColor4fv(cur.color); } vslot.skipped = 0; } else if(pass==RENDERPASS_DYNLIGHT) { if(cur.colorscale != vslot.colorscale) { cur.colorscale = vslot.colorscale; glColor3f(cur.lightcolor.x*vslot.colorscale.x, cur.lightcolor.y*vslot.colorscale.y, cur.lightcolor.z*vslot.colorscale.z); } } if((pass==RENDERPASS_LIGHTMAP || pass==RENDERPASS_ENVMAP) && slot.shader->type&SHADER_ENVMAP && slot.ffenv && hasCM && maxtmus >= 2 && envpass) { if(cur.glowtmu<0) { cur.skipped |= 1< 1 ? vslot.alphafront : vslot.alphaback; if(cur.colorscale != vslot.colorscale || cur.alphascale != alpha) { cur.colorscale = vslot.colorscale; cur.alphascale = alpha; setenvparamf("colorparams", SHPARAM_PIXEL, 6, 2*alpha*vslot.colorscale.x, 2*alpha*vslot.colorscale.y, 2*alpha*vslot.colorscale.z, alpha); GLfloat fogc[4] = { alpha*cur.fogcolor[0], alpha*cur.fogcolor[1], alpha*cur.fogcolor[2], cur.fogcolor[3] }; glFogfv(GL_FOG_COLOR, fogc); } } else if(cur.colorscale != vslot.colorscale) { cur.colorscale = vslot.colorscale; setenvparamf("colorparams", SHPARAM_PIXEL, 6, 2*vslot.colorscale.x, 2*vslot.colorscale.y, 2*vslot.colorscale.z, 1); } int tmu = cur.lightmaptmu+1, envmaptmu = -1; if(slot.shader->type&SHADER_NORMALSLMS) tmu++; if(slot.shader->type&SHADER_ENVMAP) envmaptmu = tmu++; loopvj(slot.sts) { Slot::Tex &t = slot.sts[j]; if(t.type==TEX_DIFFUSE || t.combined>=0) continue; if(t.type==TEX_ENVMAP) { if(envmaptmu>=0 && cur.textures[envmaptmu]!=t.t->id) { glActiveTexture_(GL_TEXTURE0_ARB+envmaptmu); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cur.textures[envmaptmu] = t.t->id); } continue; } else if(cur.textures[tmu]!=t.t->id) { glActiveTexture_(GL_TEXTURE0_ARB+tmu); glBindTexture(GL_TEXTURE_2D, cur.textures[tmu] = t.t->id); } tmu++; } glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } cur.slot = &slot; cur.vslot = &vslot; } static void changeshader(renderstate &cur, Shader *s, Slot &slot, VSlot &vslot, bool shadowed) { if(glaring) { static Shader *noglareshader = NULL, *noglareblendshader = NULL, *noglarealphashader = NULL; Shader *fallback; if(cur.blending) { if(!noglareblendshader) noglareblendshader = lookupshaderbyname("noglareblendworld"); fallback = noglareblendshader; } else if(cur.alphaing) { if(!noglarealphashader) noglarealphashader = lookupshaderbyname("noglarealphaworld"); fallback = noglarealphashader; } else { if(!noglareshader) noglareshader = lookupshaderbyname("noglareworld"); fallback = noglareshader; } if(s->hasoption(4)) s->setvariant(cur.visibledynlights, 4, slot, vslot, fallback); else s->setvariant(cur.blending ? 1 : 0, 4, slot, vslot, fallback); } else if(fading && !cur.blending && !cur.alphaing) { if(shadowed) s->setvariant(cur.visibledynlights, 3, slot, vslot); else s->setvariant(cur.visibledynlights, 2, slot, vslot); } else if(shadowed) s->setvariant(cur.visibledynlights, 1, slot, vslot); else if(!cur.visibledynlights) s->set(slot, vslot); else s->setvariant(cur.visibledynlights-1, 0, slot, vslot); } static void changetexgen(renderstate &cur, int dim, Slot &slot, VSlot &vslot) { if(cur.texgenslot != &slot || cur.texgenvslot != &vslot) { Texture *curtex = !cur.texgenslot || cur.texgenslot->sts.empty() ? notexture : cur.texgenslot->sts[0].t, *tex = slot.sts.empty() ? notexture : slot.sts[0].t; if(!cur.texgenvslot || slot.sts.empty() || (curtex->xs != tex->xs || curtex->ys != tex->ys || cur.texgenvslot->rotation != vslot.rotation || cur.texgenvslot->scale != vslot.scale || cur.texgenvslot->xoffset != vslot.xoffset || cur.texgenvslot->yoffset != vslot.yoffset || cur.texgenvslot->scrollS != vslot.scrollS || cur.texgenvslot->scrollT != vslot.scrollT)) { float xs = vslot.rotation>=2 && vslot.rotation<=4 ? -tex->xs : tex->xs, ys = (vslot.rotation>=1 && vslot.rotation<=2) || vslot.rotation==5 ? -tex->ys : tex->ys, scrollS = vslot.scrollS, scrollT = vslot.scrollT; if((vslot.rotation&5)==1) swap(scrollS, scrollT); scrollS *= lastmillis*tex->xs/xs; scrollT *= lastmillis*tex->ys/ys; if(cur.texgenscrollS != scrollS || cur.texgenscrollT != scrollT) { cur.texgenscrollS = scrollS; cur.texgenscrollT = scrollT; cur.texgendim = -1; } } cur.texgenslot = &slot; cur.texgenvslot = &vslot; } if(renderpath==R_FIXEDFUNCTION) { bool mtglow = cur.mtglow && !cur.envscale.x; if(cur.texgendim == dim && (cur.mttexgen || !mtglow)) return; glMatrixMode(GL_TEXTURE); if(cur.texgendim!=dim) { glLoadIdentity(); if(dim <= 2) glTranslatef(cur.texgenscrollS, cur.texgenscrollT, 0.0f); } if(mtglow) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glLoadIdentity(); if(dim <= 2) glTranslatef(cur.texgenscrollS, cur.texgenscrollT, 0.0f); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } cur.mttexgen = mtglow; glMatrixMode(GL_MODELVIEW); } else { if(cur.texgendim == dim) return; setenvparamf("texgenscroll", SHPARAM_VERTEX, 0, cur.texgenscrollS, cur.texgenscrollT); } cur.texgendim = dim; } static void renderbatch(renderstate &cur, int pass, geombatch &b) { geombatch *shadowed = NULL; int rendered = -1; for(geombatch *curbatch = &b;; curbatch = &geombatches[curbatch->batch]) { ushort len = curbatch->es.length[curbatch->va->shadowed ? 0 : 1]; if(len) { if(rendered < 0) { if(renderpath!=R_FIXEDFUNCTION) changeshader(cur, b.vslot.slot->shader, *b.vslot.slot, b.vslot, false); rendered = 0; gbatches++; } ushort minvert = curbatch->es.minvert[0], maxvert = curbatch->es.maxvert[0]; if(!curbatch->va->shadowed) { minvert = min(minvert, curbatch->es.minvert[1]); maxvert = max(maxvert, curbatch->es.maxvert[1]); } drawtris(len, curbatch->edata, minvert, maxvert); vtris += len/3; } if(curbatch->es.length[1] > len && !shadowed) shadowed = curbatch; if(curbatch->batch < 0) break; } if(shadowed) for(geombatch *curbatch = shadowed;; curbatch = &geombatches[curbatch->batch]) { if(curbatch->va->shadowed && curbatch->es.length[1] > curbatch->es.length[0]) { if(rendered < 1) { if(renderpath!=R_FIXEDFUNCTION) changeshader(cur, b.vslot.slot->shader, *b.vslot.slot, b.vslot, true); rendered = 1; gbatches++; } ushort len = curbatch->es.length[1] - curbatch->es.length[0]; drawtris(len, curbatch->edata + curbatch->es.length[0], curbatch->es.minvert[1], curbatch->es.maxvert[1]); vtris += len/3; } if(curbatch->batch < 0) break; } } static void resetbatches() { geombatches.setsize(0); firstbatch = -1; numbatches = 0; } static void renderbatches(renderstate &cur, int pass) { cur.slot = NULL; cur.vslot = NULL; int curbatch = firstbatch; if(curbatch >= 0) { if(cur.alphaing) { if(cur.depthmask) { cur.depthmask = false; glDepthMask(GL_FALSE); } } else if(!cur.depthmask) { cur.depthmask = true; glDepthMask(GL_TRUE); } if(!cur.colormask) { cur.colormask = true; glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, cur.alphaing ? GL_FALSE : GL_TRUE); } } while(curbatch >= 0) { geombatch &b = geombatches[curbatch]; curbatch = b.next; if(cur.vbuf != b.va->vbuf) changevbuf(cur, pass, b.va); if(cur.vslot != &b.vslot) { changeslottmus(cur, pass, *b.vslot.slot, b.vslot); if(cur.texgendim != b.es.dim || (cur.texgendim <= 2 && cur.texgenvslot != &b.vslot) || (!cur.mttexgen && cur.mtglow && !cur.envscale.x)) changetexgen(cur, b.es.dim, *b.vslot.slot, b.vslot); } else if(cur.texgendim != b.es.dim) changetexgen(cur, b.es.dim, *b.vslot.slot, b.vslot); if(pass == RENDERPASS_LIGHTMAP) changebatchtmus(cur, pass, b); else if(pass == RENDERPASS_ENVMAP) changeenv(cur, pass, *b.vslot.slot, b.vslot, &b); renderbatch(cur, pass, b); } if(pass == RENDERPASS_LIGHTMAP && cur.mtglow) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glDisable(cur.envscale.x ? GL_TEXTURE_CUBE_MAP_ARB : GL_TEXTURE_2D); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); cur.mtglow = false; } resetbatches(); } void renderzpass(renderstate &cur, vtxarray *va) { if(cur.vbuf!=va->vbuf) changevbuf(cur, RENDERPASS_Z, va); if(!cur.depthmask) { cur.depthmask = true; glDepthMask(GL_TRUE); } if(cur.colormask) { cur.colormask = false; glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } extern int apple_glsldepth_bug; int firsttex = 0, numtexs = va->texs, numtris = va->tris; ushort *edata = va->edata; if(cur.alphaing) { firsttex += va->texs + va->blends; edata += 3*(va->tris + va->blendtris); numtexs = va->alphaback + va->alphafront; numtris = va->alphabacktris + va->alphafronttris; xtravertsva += 3*numtris; } else xtravertsva += va->verts; if(renderpath!=R_ASMGLSLANG || !apple_glsldepth_bug) { nocolorshader->set(); drawvatris(va, 3*numtris, edata); } else { static Shader *nocolorglslshader = NULL; if(!nocolorglslshader) nocolorglslshader = lookupshaderbyname("nocolorglsl"); int lastflags = 0, lastdraw = 0, offset = 0; for(int i = firsttex; i < firsttex + numtexs; i++) { int flags = lookupvslot(va->eslist[i].texture).slot->shader->type&SHADER_GLSLANG; if(flags != lastflags && offset > lastdraw) { (lastflags ? nocolorglslshader : nocolorshader)->set(); drawvatris(va, offset-lastdraw, edata+lastdraw); lastdraw = offset; } lastflags = flags; offset += va->eslist[i].length[1]; } if(offset > lastdraw) { (lastflags ? nocolorglslshader : nocolorshader)->set(); drawvatris(va, offset-lastdraw, va->edata+lastdraw); } } } vector foggedvas; #define startvaquery(va, flush) \ do { \ if(va->query) \ { \ flush; \ startquery(va->query); \ } \ } while(0) #define endvaquery(va, flush) \ do { \ if(va->query) \ { \ flush; \ endquery(va->query); \ } \ } while(0) void renderfoggedvas(renderstate &cur, bool doquery = false) { static Shader *fogshader = NULL; if(!fogshader) fogshader = lookupshaderbyname("fogworld"); fogshader->set(); glDisable(GL_TEXTURE_2D); glColor3ubv(watercolor.v); loopv(foggedvas) { vtxarray *va = foggedvas[i]; if(cur.vbuf!=va->vbuf) changevbuf(cur, RENDERPASS_FOG, va); if(doquery) startvaquery(va, ); drawvatris(va, 3*va->tris, va->edata); vtris += va->tris; if(doquery) endvaquery(va, ); } glEnable(GL_TEXTURE_2D); foggedvas.setsize(0); } void rendershadowmappass(renderstate &cur, vtxarray *va) { if(cur.vbuf!=va->vbuf) changevbuf(cur, RENDERPASS_SHADOWMAP, va); elementset *texs = va->eslist; ushort *edata = va->edata; loopi(va->texs) { elementset &es = texs[i]; int len = es.length[1] - es.length[0]; if(len > 0) { drawtris(len, &edata[es.length[0]], es.minvert[1], es.maxvert[1]); vtris += len/3; } edata += es.length[1]; } } VAR(batchgeom, 0, 1, 1); void renderva(renderstate &cur, vtxarray *va, int pass = RENDERPASS_LIGHTMAP, bool fogpass = false, bool doquery = false) { switch(pass) { case RENDERPASS_GLOW: if(!(va->texmask&(1<texmask&(1<verts; va->shadowed = false; va->dynlightmask = 0; if(fogpass ? va->geommax.z<=reflectz-waterfog : va->curvfc==VFC_FOGGED) { foggedvas.add(va); break; } if(renderpath!=R_FIXEDFUNCTION && !envmapping && !glaring && !cur.alphaing) { va->shadowed = isshadowmapreceiver(va); calcdynlightmask(va); } if(doquery) startvaquery(va, { if(geombatches.length()) renderbatches(cur, pass); }); mergetexs(cur, va); if(doquery) endvaquery(va, { if(geombatches.length()) renderbatches(cur, pass); }); else if(!batchgeom && geombatches.length()) renderbatches(cur, pass); break; case RENDERPASS_LIGHTMAP_BLEND: { if(doquery) startvaquery(va, { if(geombatches.length()) renderbatches(cur, RENDERPASS_LIGHTMAP); }); mergetexs(cur, va, &va->eslist[va->texs], va->blends, va->edata + 3*va->tris); if(doquery) endvaquery(va, { if(geombatches.length()) renderbatches(cur, RENDERPASS_LIGHTMAP); }); else if(!batchgeom && geombatches.length()) renderbatches(cur, RENDERPASS_LIGHTMAP); break; } case RENDERPASS_DYNLIGHT: if(cur.dynlightpos.dist_to_bb(va->geommin, va->geommax) >= cur.dynlightradius) break; vverts += va->verts; mergetexs(cur, va); if(!batchgeom && geombatches.length()) renderbatches(cur, pass); break; case RENDERPASS_FOG: if(cur.vbuf!=va->vbuf) changevbuf(cur, pass, va); drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; break; case RENDERPASS_SHADOWMAP: if(isshadowmapreceiver(va)) rendershadowmappass(cur, va); break; case RENDERPASS_CAUSTICS: if(cur.vbuf!=va->vbuf) changevbuf(cur, pass, va); drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; break; case RENDERPASS_Z: if(doquery) startvaquery(va, ); renderzpass(cur, va); if(doquery) endvaquery(va, ); break; } } GLuint attenxytex = 0, attenztex = 0; static GLuint createattenxytex(int size) { uchar *data = new uchar[size*size], *dst = data; loop(y, size) loop(x, size) { float dx = 2*float(x)/(size-1) - 1, dy = 2*float(y)/(size-1) - 1; float atten = max(0.0f, 1.0f - dx*dx - dy*dy); *dst++ = uchar(atten*255); } GLuint tex = 0; glGenTextures(1, &tex); createtexture(tex, size, size, data, 3, 1, GL_ALPHA); delete[] data; return tex; } static GLuint createattenztex(int size) { uchar *data = new uchar[size], *dst = data; loop(z, size) { float dz = 2*float(z)/(size-1) - 1; float atten = dz*dz; *dst++ = uchar(atten*255); } GLuint tex = 0; glGenTextures(1, &tex); createtexture(tex, size, 1, data, 3, 1, GL_ALPHA, GL_TEXTURE_1D); delete[] data; return tex; } #define NUMCAUSTICS 32 static Texture *caustictex[NUMCAUSTICS] = { NULL }; void loadcaustics(bool force) { static bool needcaustics = false; if(force) needcaustics = true; if(!caustics || !needcaustics) return; useshaderbyname("caustic"); if(caustictex[0]) return; loopi(NUMCAUSTICS) { defformatstring(name)( renderpath==R_FIXEDFUNCTION ? "packages/caustics/caust%.2d" : "packages/caustics/caust%.2d", i); caustictex[i] = textureload(name); } } void cleanupva() { clearvas(worldroot); clearqueries(); if(attenxytex) { glDeleteTextures(1, &attenxytex); attenxytex = 0; } if(attenztex) { glDeleteTextures(1, &attenztex); attenztex = 0; } loopi(NUMCAUSTICS) caustictex[i] = NULL; } VARR(causticscale, 0, 50, 10000); VARR(causticmillis, 0, 75, 1000); VARFP(caustics, 0, 1, 1, loadcaustics()); void setupcaustics(int tmu, float blend, GLfloat *color = NULL) { if(!caustictex[0]) loadcaustics(true); GLfloat s[4] = { 0.011f, 0, 0.0066f, 0 }; GLfloat t[4] = { 0, 0.011f, 0.0066f, 0 }; loopk(3) { s[k] *= 100.0f/causticscale; t[k] *= 100.0f/causticscale; } int tex = (lastmillis/causticmillis)%NUMCAUSTICS; float frac = float(lastmillis%causticmillis)/causticmillis; if(color) color[3] = frac; else glColor4f(1, 1, 1, frac); loopi(2) { glActiveTexture_(GL_TEXTURE0_ARB+tmu+i); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, caustictex[(tex+i)%NUMCAUSTICS]->id); if(renderpath==R_FIXEDFUNCTION) { setuptexgen(); if(color) setuptmu(tmu+i, !i ? "$1 , $0 @ Ca" : "= P"); else setuptmu(tmu+i, !i ? "= T" : "T , P @ Ca"); glTexGenfv(GL_S, GL_OBJECT_PLANE, s); glTexGenfv(GL_T, GL_OBJECT_PLANE, t); } } if(renderpath!=R_FIXEDFUNCTION) { static Shader *causticshader = NULL; if(!causticshader) causticshader = lookupshaderbyname("caustic"); causticshader->set(); setlocalparamfv("texgenS", SHPARAM_VERTEX, 0, s); setlocalparamfv("texgenT", SHPARAM_VERTEX, 1, t); setlocalparamf("frameoffset", SHPARAM_PIXEL, 0, blend*(1-frac), blend*frac, blend); } } void setupTMUs(renderstate &cur, float causticspass, bool fogpass) { if(renderpath==R_FIXEDFUNCTION) { if(nolights) cur.lightmaptmu = -1; else if(maxtmus>=3) { if(maxtmus>=4 && (hasTEX || hasTE4) && causticspass>=1) { cur.causticstmu = 0; cur.diffusetmu = 2; cur.lightmaptmu = 3; if(maxtmus>=5 && glowpass && !cur.alphaing) cur.glowtmu = 4; } else if(glowpass && !cur.alphaing) cur.glowtmu = 2; } if(cur.glowtmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); setuptmu(cur.glowtmu, "P + T", "= Pa"); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } if(cur.causticstmu>=0) setupcaustics(cur.causticstmu, causticspass, cur.color); } else { // need to invalidate vertex params in case they were used somewhere else for streaming params invalidateenvparams(SHPARAM_VERTEX, 10, RESERVEDSHADERPARAMS + MAXSHADERPARAMS - 10); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_COLOR_ARRAY); loopi(8-2) { glActiveTexture_(GL_TEXTURE2_ARB+i); glEnable(GL_TEXTURE_2D); } glActiveTexture_(GL_TEXTURE0_ARB); setenvparamf("colorparams", SHPARAM_PIXEL, 6, 2, 2, 2, 1); setenvparamf("camera", SHPARAM_VERTEX, 4, camera1->o.x, camera1->o.y, camera1->o.z, 1); setenvparamf("ambient", SHPARAM_PIXEL, 5, ambientcolor.x/255.0f, ambientcolor.y/255.0f, ambientcolor.z/255.0f); setenvparamf("millis", SHPARAM_VERTEX, 6, lastmillis/1000.0f, lastmillis/1000.0f, lastmillis/1000.0f); } glColor4fv(cur.color); if(cur.lightmaptmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); setuptmu(cur.lightmaptmu, "P * T x 2", "= Pa"); glEnable(GL_TEXTURE_2D); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); glEnable(GL_TEXTURE_2D); setuptmu(cur.diffusetmu, cur.diffusetmu>0 ? "P * T" : "= T", cur.alphaing ? "= Ca" : (cur.diffusetmu>0 ? "= Ta" : "Ca * Ta")); } // diffusetmu glEnableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } void cleanupTMUs(renderstate &cur, float causticspass, bool fogpass) { if(cur.lightmaptmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); resettmu(cur.lightmaptmu); glDisable(GL_TEXTURE_2D); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } if(cur.glowtmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); resettmu(cur.glowtmu); if(cur.envscale.x) disableenv(cur); else disableglow(cur); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } if(cur.causticstmu>=0) loopi(2) { glActiveTexture_(GL_TEXTURE0_ARB+cur.causticstmu+i); resettmu(cur.causticstmu+i); disabletexgen(); glDisable(GL_TEXTURE_2D); } if(cur.lightmaptmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); resettmu(cur.diffusetmu); glDisable(GL_TEXTURE_2D); } glDisableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); if(renderpath!=R_FIXEDFUNCTION) { glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_COLOR_ARRAY); loopi(8-2) { glActiveTexture_(GL_TEXTURE2_ARB+i); glDisable(GL_TEXTURE_2D); } } if(cur.lightmaptmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); glEnable(GL_TEXTURE_2D); } } #define FIRSTVA (reflecting ? reflectedva : visibleva) #define NEXTVA (reflecting ? va->rnext : va->next) static void rendergeommultipass(renderstate &cur, int pass, bool fogpass) { cur.vbuf = 0; cur.texgendim = -1; for(vtxarray *va = FIRSTVA; va; va = NEXTVA) { if(!va->texs) continue; if(refracting) { if((refracting < 0 ? va->geommin.z > reflectz : va->geommax.z <= reflectz) || va->occluded >= OCCLUDE_GEOM) continue; if(ishiddencube(va->o, va->size)) continue; } else if(reflecting) { if(va->geommax.z <= reflectz) continue; } else if(va->occluded >= OCCLUDE_GEOM) continue; if(fogpass ? va->geommax.z <= reflectz-waterfog : va->curvfc==VFC_FOGGED) continue; renderva(cur, va, pass, fogpass); } if(geombatches.length()) renderbatches(cur, pass); } VAR(oqgeom, 0, 1, 1); VAR(dbgffsm, 0, 0, 1); VAR(dbgffdl, 0, 0, 1); VAR(ffdlscissor, 0, 1, 1); static void setupenvpass(renderstate &cur) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 1, 1, 1); cur.envscale = vec(-1, -1, -1); cur.glowtmu = 0; setuptmu(0, "= T", "= Ca"); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_CUBE_MAP_ARB); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_R); glMatrixMode(GL_TEXTURE); glLoadMatrixf(envmatrix.v); glMatrixMode(GL_MODELVIEW); glEnableClientState(GL_NORMAL_ARRAY); glActiveTexture_(GL_TEXTURE1_ARB); glClientActiveTexture_(GL_TEXTURE1_ARB); cur.specmask = false; cur.diffusetmu = 1; setuptmu(1, "= P", "Pa * Ta"); glEnableClientState(GL_TEXTURE_COORD_ARRAY); } static void cleanuptexgen(renderstate &cur) { if(cur.texgendim >= 0 && cur.texgendim <= 2) { glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } } static void cleanupenvpass(renderstate &cur) { glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_2D); resettmu(1); cleanuptexgen(cur); glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); resettmu(0); glDisableClientState(GL_NORMAL_ARRAY); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_R); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glDisable(GL_TEXTURE_CUBE_MAP_ARB); glEnable(GL_TEXTURE_2D); } void rendergeom(float causticspass, bool fogpass) { if(causticspass && ((renderpath==R_FIXEDFUNCTION && maxtmus<2) || !causticscale || !causticmillis)) causticspass = 0; bool mainpass = !reflecting && !refracting && !envmapping && !glaring, doOQ = hasOQ && oqfrags && oqgeom && mainpass, doZP = doOQ && zpass, doSM = shadowmap && !envmapping && !glaring && renderpath!=R_FIXEDFUNCTION; renderstate cur; if(mainpass) { flipqueries(); vtris = vverts = 0; } if(!doZP) { if(shadowmap && hasFBO && mainpass) rendershadowmap(); setupTMUs(cur, causticspass, fogpass); if(doSM) pushshadowmap(); } int hasdynlights = finddynlights(); resetbatches(); glEnableClientState(GL_VERTEX_ARRAY); int blends = 0; for(vtxarray *va = FIRSTVA; va; va = NEXTVA) { if(!va->texs) continue; if(refracting) { if((refracting < 0 ? va->geommin.z > reflectz : va->geommax.z <= reflectz) || va->occluded >= OCCLUDE_GEOM) continue; if(ishiddencube(va->o, va->size)) continue; } else if(reflecting) { if(va->geommax.z <= reflectz) continue; } else if(doOQ && (zpass || va->distance > oqdist) && !insideva(va, camera1->o)) { if(va->parent && va->parent->occluded >= OCCLUDE_BB) { va->query = NULL; va->occluded = OCCLUDE_PARENT; continue; } va->occluded = va->query && va->query->owner == va && checkquery(va->query) ? min(va->occluded+1, int(OCCLUDE_BB)) : OCCLUDE_NOTHING; va->query = newquery(va); if((!va->query && zpass) || !va->occluded) va->occluded = pvsoccluded(va->geommin, va->geommax) ? OCCLUDE_GEOM : OCCLUDE_NOTHING; if(va->occluded >= OCCLUDE_GEOM) { if(va->query) { if(!zpass && geombatches.length()) renderbatches(cur, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP); renderquery(cur, va->query, va); } continue; } } else { va->query = NULL; va->occluded = pvsoccluded(va->geommin, va->geommax) ? OCCLUDE_GEOM : OCCLUDE_NOTHING; if(va->occluded >= OCCLUDE_GEOM) continue; } if(!doZP) blends += va->blends; renderva(cur, va, doZP ? RENDERPASS_Z : (nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP), fogpass, doOQ); } if(geombatches.length()) renderbatches(cur, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP); if(!cur.colormask) { cur.colormask = true; glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } if(!cur.depthmask) { cur.depthmask = true; glDepthMask(GL_TRUE); } bool multipassing = false; if(doZP) { glFlush(); if(shadowmap && hasFBO && mainpass) { glDisableClientState(GL_VERTEX_ARRAY); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } rendershadowmap(); glEnableClientState(GL_VERTEX_ARRAY); } setupTMUs(cur, causticspass, fogpass); if(doSM) pushshadowmap(); if(!multipassing) { multipassing = true; glDepthFunc(GL_LEQUAL); } cur.vbuf = 0; cur.texgendim = -1; for(vtxarray *va = visibleva; va; va = va->next) { if(!va->texs || va->occluded >= OCCLUDE_GEOM) continue; blends += va->blends; renderva(cur, va, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP, fogpass); } if(geombatches.length()) renderbatches(cur, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP); for(vtxarray *va = visibleva; va; va = va->next) { if(!va->texs || va->occluded < OCCLUDE_GEOM) continue; else if((va->parent && va->parent->occluded >= OCCLUDE_BB) || (va->query && checkquery(va->query))) { va->occluded = OCCLUDE_BB; continue; } else { va->occluded = pvsoccluded(va->geommin, va->geommax) ? OCCLUDE_GEOM : OCCLUDE_NOTHING; if(va->occluded >= OCCLUDE_GEOM) continue; } blends += va->blends; renderva(cur, va, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP, fogpass); } if(geombatches.length()) renderbatches(cur, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP); } if(blends && (renderpath!=R_FIXEDFUNCTION || !nolights)) { if(!multipassing) { multipassing = true; glDepthFunc(GL_LEQUAL); } glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); cur.vbuf = 0; cur.texgendim = -1; cur.blending = true; if(cur.lightmaptmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); setuptmu(cur.lightmaptmu, "P * T x 2", "= Ta"); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } for(vtxarray *va = FIRSTVA; va; va = NEXTVA) { if(!va->blends) continue; if(refracting) { if(refracting < 0 ? va->geommin.z > reflectz : va->geommax.z <= reflectz) continue; if(ishiddencube(va->o, va->size)) continue; if(va->occluded >= OCCLUDE_GEOM) continue; } else if(reflecting) { if(va->geommax.z <= reflectz) continue; } else if(va->occluded >= OCCLUDE_GEOM) continue; if(fogpass ? va->geommax.z <= reflectz-waterfog : va->curvfc==VFC_FOGGED) continue; renderva(cur, va, RENDERPASS_LIGHTMAP_BLEND, fogpass); } if(geombatches.length()) renderbatches(cur, RENDERPASS_LIGHTMAP); cur.blending = false; glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDisable(GL_BLEND); glDepthMask(GL_TRUE); } if(doSM) popshadowmap(); cleanupTMUs(cur, causticspass, fogpass); if(foggedvas.length()) renderfoggedvas(cur, doOQ && !zpass); if(renderpath==R_FIXEDFUNCTION ? (glowpass && cur.skipped) || (causticspass>=1 && cur.causticstmu<0) || (shadowmap && shadowmapcasters) || hasdynlights : causticspass) { if(!multipassing) { multipassing = true; glDepthFunc(GL_LEQUAL); } glDepthMask(GL_FALSE); glEnable(GL_BLEND); if(renderpath==R_FIXEDFUNCTION && glowpass && cur.skipped&(1<=1 && cur.causticstmu<0 : causticspass) { setupcaustics(0, causticspass); glBlendFunc(GL_ZERO, renderpath==R_FIXEDFUNCTION ? GL_SRC_COLOR : GL_ONE_MINUS_SRC_COLOR); glFogfv(GL_FOG_COLOR, renderpath==R_FIXEDFUNCTION ? onefog : zerofog); if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); rendergeommultipass(cur, RENDERPASS_CAUSTICS, fogpass); if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); loopi(2) { glActiveTexture_(GL_TEXTURE0_ARB+i); resettmu(i); if(renderpath==R_FIXEDFUNCTION || !i) { resettmu(i); disabletexgen(); } if(i) glDisable(GL_TEXTURE_2D); } glActiveTexture_(GL_TEXTURE0_ARB); } if(renderpath==R_FIXEDFUNCTION && shadowmap && shadowmapcasters) { glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); glFogfv(GL_FOG_COLOR, zerofog); pushshadowmap(); if(dbgffsm) { glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); glColor3f(1, 0, 1); } rendergeommultipass(cur, RENDERPASS_SHADOWMAP, fogpass); if(dbgffsm) { glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); } popshadowmap(); } if(renderpath==R_FIXEDFUNCTION && hasdynlights) { glBlendFunc(GL_SRC_ALPHA, dbgffdl ? GL_ZERO : GL_ONE); glFogfv(GL_FOG_COLOR, zerofog); if(!attenxytex) attenxytex = createattenxytex(64); glBindTexture(GL_TEXTURE_2D, attenxytex); setuptmu(0, "= C", "= Ta"); setuptexgen(); glActiveTexture_(GL_TEXTURE1_ARB); setuptmu(1, "= P", "Pa - Ta"); setuptexgen(1); if(!attenztex) attenztex = createattenztex(64); glBindTexture(GL_TEXTURE_1D, attenztex); glEnable(GL_TEXTURE_1D); glActiveTexture_(GL_TEXTURE2_ARB); glClientActiveTexture_(GL_TEXTURE2_ARB); cur.diffusetmu = 2; setuptmu(2, "P * T x 4", "= Pa"); glEnable(GL_TEXTURE_2D); glEnableClientState(GL_TEXTURE_COORD_ARRAY); for(int n = 0; getdynlight(n, cur.dynlightpos, cur.dynlightradius, cur.lightcolor); n++) { cur.lightcolor.mul(0.5f); cur.colorscale = vec(1, 1, 1); glColor3f(cur.lightcolor.x, cur.lightcolor.y, cur.lightcolor.z); if(ffdlscissor) { float sx1, sy1, sx2, sy2; calcspherescissor(cur.dynlightpos, cur.dynlightradius, sx1, sy1, sx2, sy2); pushscissor(sx1, sy1, sx2, sy2); } changedynlightpos(cur); rendergeommultipass(cur, RENDERPASS_DYNLIGHT, fogpass); if(ffdlscissor) popscissor(); } glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_2D); resettmu(2); cleanuptexgen(cur); glActiveTexture_(GL_TEXTURE1_ARB); glDisable(GL_TEXTURE_1D); resettmu(1); disabletexgen(1); glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); resettmu(0); disabletexgen(); } glFogfv(GL_FOG_COLOR, cur.fogcolor); glDisable(GL_BLEND); glDepthMask(GL_TRUE); } if(multipassing) glDepthFunc(GL_LESS); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); } void renderalphageom(bool fogpass) { static vector alphavas; alphavas.setsize(0); bool hasback = false; for(vtxarray *va = FIRSTVA; va; va = NEXTVA) { if(!va->alphabacktris && !va->alphafronttris) continue; if(refracting) { if((refracting < 0 ? va->geommin.z > reflectz : va->geommax.z <= reflectz) || va->occluded >= OCCLUDE_BB) continue; if(ishiddencube(va->o, va->size)) continue; if(va->occluded >= OCCLUDE_GEOM && pvsoccluded(va->geommin, va->geommax)) continue; } else if(reflecting) { if(va->geommax.z <= reflectz) continue; } else { if(va->occluded >= OCCLUDE_BB) continue; if(va->occluded >= OCCLUDE_GEOM && pvsoccluded(va->geommin, va->geommax)) continue; } if(fogpass ? va->geommax.z <= reflectz-waterfog : va->curvfc==VFC_FOGGED) continue; alphavas.add(va); if(va->alphabacktris) hasback = true; } if(alphavas.empty()) return; resetbatches(); renderstate cur; cur.alphaing = 1; glEnableClientState(GL_VERTEX_ARRAY); glGetFloatv(GL_FOG_COLOR, cur.fogcolor); loop(front, 2) if(front || hasback) { cur.alphaing = front+1; if(!front) glCullFace(GL_FRONT); cur.vbuf = 0; cur.texgendim = -1; loopv(alphavas) renderva(cur, alphavas[i], RENDERPASS_Z); if(cur.depthmask) { cur.depthmask = false; glDepthMask(GL_FALSE); } cur.colormask = true; glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); setupTMUs(cur, 0, fogpass); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); if(renderpath==R_FIXEDFUNCTION) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); else glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); cur.vbuf = 0; cur.texgendim = -1; cur.skipped = 0; cur.colorscale = vec(1, 1, 1); loopk(3) cur.color[k] = 1; cur.alphascale = -1; loopv(alphavas) if(front || alphavas[i]->alphabacktris) renderva(cur, alphavas[i], RENDERPASS_LIGHTMAP, fogpass); if(geombatches.length()) renderbatches(cur, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP); cleanupTMUs(cur, 0, fogpass); if(renderpath==R_FIXEDFUNCTION && glowpass && cur.skipped) { if(cur.depthmask) { cur.depthmask = false; glDepthMask(GL_FALSE); } if(cur.skipped&(1<alphabacktris) renderva(cur, alphavas[i], RENDERPASS_ENVMAP, fogpass); if(geombatches.length()) renderbatches(cur, RENDERPASS_ENVMAP); cleanupenvpass(cur); } if(cur.skipped&(1<alphabacktris) renderva(cur, alphavas[i], RENDERPASS_GLOW, fogpass); if(geombatches.length()) renderbatches(cur, RENDERPASS_GLOW); cleanuptexgen(cur); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glFogfv(GL_FOG_COLOR, cur.fogcolor); } if(!front) { cur.diffusetmu = 0; cur.lightmaptmu = 1; cur.glowtmu = -1; setupTMUs(cur, 0, fogpass); } } else if(renderpath!=R_FIXEDFUNCTION) { glFogfv(GL_FOG_COLOR, cur.fogcolor); } if(!cur.depthmask) { cur.depthmask = true; glDepthMask(GL_TRUE); } glDisable(GL_BLEND); glDepthFunc(GL_LESS); if(!front) glCullFace(GL_BACK); } glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, fading ? GL_FALSE : GL_TRUE); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); } void findreflectedvas(vector &vas, int prevvfc = VFC_PART_VISIBLE) { loopv(vas) { vtxarray *va = vas[i]; if(prevvfc >= VFC_NOT_VISIBLE) va->curvfc = prevvfc; if(va->curvfc == VFC_FOGGED || va->curvfc == PVS_FOGGED || va->o.z+va->size <= reflectz || isfoggedcube(va->o, va->size)) continue; bool render = true; if(va->curvfc == VFC_FULL_VISIBLE) { if(va->occluded >= OCCLUDE_BB) continue; if(va->occluded >= OCCLUDE_GEOM) render = false; } else if(va->curvfc == PVS_FULL_VISIBLE) continue; if(render) { if(va->curvfc >= VFC_NOT_VISIBLE) va->distance = (int)vadist(va, camera1->o); vtxarray **vprev = &reflectedva, *vcur = reflectedva; while(vcur && va->distance > vcur->distance) { vprev = &vcur->rnext; vcur = vcur->rnext; } va->rnext = *vprev; *vprev = va; } if(va->children.length()) findreflectedvas(va->children, va->curvfc); } } void renderreflectedgeom(bool causticspass, bool fogpass) { if(reflecting) { reflectedva = NULL; findreflectedvas(varoot); rendergeom(causticspass ? 1 : 0, fogpass); } else rendergeom(causticspass ? 1 : 0, fogpass); } static vtxarray *prevskyva = NULL; void renderskyva(vtxarray *va, bool explicitonly = false) { if(!prevskyva || va->vbuf != prevskyva->vbuf) { if(!prevskyva) glEnableClientState(GL_VERTEX_ARRAY); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->skybuf); } glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); } drawvatris(va, explicitonly ? va->explicitsky : va->sky+va->explicitsky, explicitonly ? va->skydata+va->sky : va->skydata); if(!explicitonly) xtraverts += va->sky/3; xtraverts += va->explicitsky/3; prevskyva = va; } int renderedsky = 0, renderedexplicitsky = 0, renderedskyfaces = 0, renderedskyclip = INT_MAX; static inline void updateskystats(vtxarray *va) { renderedsky += va->sky; renderedexplicitsky += va->explicitsky; renderedskyfaces |= va->skyfaces&0x3F; if(!(va->skyfaces&0x1F) || camera1->o.z < va->skyclip) renderedskyclip = min(renderedskyclip, va->skyclip); else renderedskyclip = 0; } void renderreflectedskyvas(vector &vas, int prevvfc = VFC_PART_VISIBLE) { loopv(vas) { vtxarray *va = vas[i]; if(prevvfc >= VFC_NOT_VISIBLE) va->curvfc = prevvfc; if((va->curvfc == VFC_FULL_VISIBLE && va->occluded >= OCCLUDE_BB) || va->curvfc==PVS_FULL_VISIBLE) continue; if(va->o.z+va->size <= reflectz || ishiddencube(va->o, va->size)) continue; if(va->sky+va->explicitsky) { updateskystats(va); renderskyva(va); } if(va->children.length()) renderreflectedskyvas(va->children, va->curvfc); } } bool rendersky(bool explicitonly) { prevskyva = NULL; renderedsky = renderedexplicitsky = renderedskyfaces = 0; renderedskyclip = INT_MAX; if(reflecting) { renderreflectedskyvas(varoot); } else for(vtxarray *va = visibleva; va; va = va->next) { if((va->occluded >= OCCLUDE_BB && va->skyfaces&0x80) || !(va->sky+va->explicitsky)) continue; // count possibly visible sky even if not actually rendered updateskystats(va); if(explicitonly && !va->explicitsky) continue; renderskyva(va, explicitonly); } if(prevskyva) { glDisableClientState(GL_VERTEX_ARRAY); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } } return renderedsky+renderedexplicitsky > 0; } sandboxgamemaker-2.7.1+dfsg/src/engine/shader.cpp0000664000175000017500000024442011615526106021671 0ustar showardshoward// shader.cpp: OpenGL assembly/GLSL shader management #include "engine.h" struct GlobalShaderParamState : ShaderParamState { uint version; GlobalShaderParamState() : version(0) {} }; Shader *Shader::lastshader = NULL; Shader *defaultshader = NULL, *rectshader = NULL, *cubemapshader = NULL, *notextureshader = NULL, *nocolorshader = NULL, *foggedshader = NULL, *foggednotextureshader = NULL, *stdworldshader = NULL, *lineshader = NULL, *foggedlineshader = NULL; static hashtable shaders; static Shader *curshader = NULL; static vector curparams; static GlobalShaderParamState vertexparamstate[RESERVEDSHADERPARAMS + MAXSHADERPARAMS], pixelparamstate[RESERVEDSHADERPARAMS + MAXSHADERPARAMS]; static bool dirtyenvparams = false, standardshader = false, initshaders = false, forceshaders = true; static uint paramversion = 0; VAR(reservevpparams, 1, 16, 0); VAR(maxvpenvparams, 1, 0, 0); VAR(maxvplocalparams, 1, 0, 0); VAR(maxfpenvparams, 1, 0, 0); VAR(maxfplocalparams, 1, 0, 0); VAR(maxtexcoords, 1, 0, 0); VAR(maxvsuniforms, 1, 0, 0); VAR(maxfsuniforms, 1, 0, 0); VAR(maxvaryings, 1, 0, 0); VAR(dbgshader, 0, 0, 2); void loadshaders() { if(renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) { GLint val; glGetProgramiv_(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &val); maxvpenvparams = val; glGetProgramiv_(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &val); maxvplocalparams = val; glGetProgramiv_(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &val); maxfpenvparams = val; glGetProgramiv_(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &val); maxfplocalparams = val; } if(renderpath==R_GLSLANG || renderpath==R_ASMGLSLANG) { GLint val; glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, &val); maxvsuniforms = val/4; glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, &val); maxfsuniforms = val/4; glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, &val); maxvaryings = val; } if(renderpath != R_FIXEDFUNCTION) { GLint val; glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &val); maxtexcoords = val; } initshaders = true; standardshader = true; execfile(renderpath==R_GLSLANG ? "data/glsl.cfg" : "data/stdshader.cfg"); standardshader = false; initshaders = false; defaultshader = lookupshaderbyname("default"); stdworldshader = lookupshaderbyname("stdworld"); if(!defaultshader || !stdworldshader) fatal("cannot find shader definitions"); extern Slot dummyslot; dummyslot.shader = stdworldshader; extern int ati_line_bug; rectshader = lookupshaderbyname("rect"); cubemapshader = lookupshaderbyname("cubemap"); notextureshader = lookupshaderbyname("notexture"); nocolorshader = lookupshaderbyname("nocolor"); foggedshader = lookupshaderbyname("fogged"); foggednotextureshader = lookupshaderbyname("foggednotexture"); lineshader = lookupshaderbyname(ati_line_bug && renderpath == R_ASMGLSLANG ? "notextureglsl" : "notexture"); foggedlineshader = lookupshaderbyname(ati_line_bug && renderpath == R_ASMGLSLANG ? "foggednotextureglsl" : "foggednotexture"); if(renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) { glEnable(GL_VERTEX_PROGRAM_ARB); glEnable(GL_FRAGMENT_PROGRAM_ARB); } defaultshader->set(); } Shader *lookupshaderbyname(const char *name) { Shader *s = shaders.access(name); return s && s->detailshader ? s : NULL; } static bool compileasmshader(GLenum type, GLuint &idx, const char *def, const char *tname, const char *name, bool msg = true, bool nativeonly = false) { glGenPrograms_(1, &idx); glBindProgram_(type, idx); def += strspn(def, " \t\r\n"); glProgramString_(type, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen(def), def); GLint err = -1, native = 1; glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &err); extern int apple_vp_bug; if(type!=GL_VERTEX_PROGRAM_ARB || !apple_vp_bug) glGetProgramiv_(type, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native); if(msg && err!=-1) { conoutf(CON_ERROR, "COMPILE ERROR (%s:%s) - %s", tname, name, glGetString(GL_PROGRAM_ERROR_STRING_ARB)); if(err>=0 && err<(int)strlen(def)) { loopi(err) putchar(*def++); puts(" <> "); while(*def) putchar(*def++); } } else if(msg && !native) conoutf(CON_ERROR, "%s:%s EXCEEDED NATIVE LIMITS", tname, name); glBindProgram_(type, 0); if(err!=-1 || (!native && nativeonly)) { glDeletePrograms_(1, &idx); idx = 0; } return native!=0; } static void showglslinfo(GLhandleARB obj, const char *tname, const char *name, const char *source) { GLint length = 0; glGetObjectParameteriv_(obj, GL_OBJECT_INFO_LOG_LENGTH_ARB, &length); if(length > 1) { GLcharARB *log = new GLcharARB[length]; glGetInfoLog_(obj, length, &length, log); conoutf(CON_ERROR, "GLSL ERROR (%s:%s)", tname, name); puts(log); if(source) loopi(1000) { const char *next = strchr(source, '\n'); printf("%d: ", i+1); fwrite(source, 1, next ? next - source + 1 : strlen(source), stdout); if(!next) { putchar('\n'); break; } source = next + 1; } delete[] log; } } static void compileglslshader(GLenum type, GLhandleARB &obj, const char *def, const char *tname, const char *name, bool msg = true) { const GLcharARB *source = (const GLcharARB*)(def + strspn(def, " \t\r\n")); obj = glCreateShaderObject_(type); glShaderSource_(obj, 1, &source, NULL); glCompileShader_(obj); GLint success; glGetObjectParameteriv_(obj, GL_OBJECT_COMPILE_STATUS_ARB, &success); if(!success) { if(msg) showglslinfo(obj, tname, name, source); glDeleteObject_(obj); obj = 0; } else if(dbgshader > 1 && msg) showglslinfo(obj, tname, name, source); } VAR(dbgubo, 0, 0, 1); static void bindglsluniform(Shader &s, UniformLoc &u) { u.loc = glGetUniformLocation_(s.program, u.name); if(!u.blockname) return; if(hasUBO) { GLuint bidx = glGetUniformBlockIndex_(s.program, u.blockname); GLuint uidx = GL_INVALID_INDEX; glGetUniformIndices_(s.program, 1, &u.name, &uidx); if(bidx != GL_INVALID_INDEX && uidx != GL_INVALID_INDEX) { GLint sizeval = 0, offsetval = 0, strideval = 0; glGetActiveUniformBlockiv_(s.program, bidx, GL_UNIFORM_BLOCK_DATA_SIZE, &sizeval); if(sizeval <= 0) return; glGetActiveUniformsiv_(s.program, 1, &uidx, GL_UNIFORM_OFFSET, &offsetval); if(u.stride > 0) { glGetActiveUniformsiv_(s.program, 1, &uidx, GL_UNIFORM_ARRAY_STRIDE, &strideval); if(strideval > u.stride) return; } u.offset = offsetval; u.size = sizeval; glUniformBlockBinding_(s.program, bidx, u.binding); if(dbgubo) conoutf(CON_DEBUG, "UBO: %s:%s:%d, offset: %d, size: %d, stride: %d", u.name, u.blockname, u.binding, offsetval, sizeval, strideval); } } else if(hasBUE) { GLint size = glGetUniformBufferSize_(s.program, u.loc), stride = 0; if(size <= 0) return; if(u.stride > 0) { defformatstring(elem1name)("%s[1]", u.name); GLint elem1loc = glGetUniformLocation_(s.program, elem1name); if(elem1loc == -1) return; GLintptr elem0off = glGetUniformOffset_(s.program, u.loc), elem1off = glGetUniformOffset_(s.program, elem1loc); stride = elem1off - elem0off; if(stride > u.stride) return; } u.offset = 0; u.size = size; if(dbgubo) conoutf(CON_DEBUG, "BUE: %s:%s:%d, offset: %d, size: %d, stride: %d", u.name, u.blockname, u.binding, 0, size, stride); } } static void linkglslprogram(Shader &s, bool msg = true) { s.program = s.vsobj && s.psobj ? glCreateProgramObject_() : 0; GLint success = 0; if(s.program) { glAttachObject_(s.program, s.vsobj); glAttachObject_(s.program, s.psobj); loopv(s.attriblocs) { AttribLoc &a = s.attriblocs[i]; glBindAttribLocation_(s.program, a.loc, a.name); } glLinkProgram_(s.program); glGetObjectParameteriv_(s.program, GL_OBJECT_LINK_STATUS_ARB, &success); } if(success) { glUseProgramObject_(s.program); loopi(8) { defformatstring(arg)("tex%d", i); GLint loc = glGetUniformLocation_(s.program, arg); if(loc != -1) glUniform1i_(loc, i); } loopv(s.defaultparams) { ShaderParam ¶m = s.defaultparams[i]; string pname; if(param.type==SHPARAM_UNIFORM) copystring(pname, param.name); else formatstring(pname)("%s%d", param.type==SHPARAM_VERTEX ? "v" : "p", param.index); param.loc = glGetUniformLocation_(s.program, pname); } loopv(s.uniformlocs) bindglsluniform(s, s.uniformlocs[i]); glUseProgramObject_(0); } else if(s.program) { if(msg) showglslinfo(s.program, "PROG", s.name, NULL); glDeleteObject_(s.program); s.program = 0; } } bool checkglslsupport() { #if 0 /* check if GLSL profile supports loops */ const GLcharARB *source = "uniform int N;\n" "uniform vec4 delta;\n" "void main(void) {\n" " vec4 test = vec4(0.0, 0.0, 0.0, 0.0);\n" " for(int i = 0; i < N; i++) test += delta;\n" " gl_FragColor = test;\n" "}\n"; #else const GLcharARB *source = "void main(void) {\n" " gl_FragColor = vec4(0.0);\n" "}\n"; #endif GLhandleARB obj = glCreateShaderObject_(GL_FRAGMENT_SHADER_ARB); if(!obj) return false; glShaderSource_(obj, 1, &source, NULL); glCompileShader_(obj); GLint success; glGetObjectParameteriv_(obj, GL_OBJECT_COMPILE_STATUS_ARB, &success); if(!success) { glDeleteObject_(obj); return false; } GLhandleARB program = glCreateProgramObject_(); if(!program) { glDeleteObject_(obj); return false; } glAttachObject_(program, obj); glLinkProgram_(program); glGetObjectParameteriv_(program, GL_OBJECT_LINK_STATUS_ARB, &success); glDeleteObject_(obj); glDeleteObject_(program); return success!=0; } #define ALLOCEXTPARAM 0xFF #define UNUSEDEXTPARAM 0xFE static int addextparam(Shader &s, const char *name, int type, int index, int loc) { if(!(s.numextparams%4)) { LocalShaderParamState *extparams = new LocalShaderParamState[s.numextparams+4]; if(s.extparams) { memcpy(extparams, s.extparams, s.numextparams*sizeof(LocalShaderParamState)); delete[] s.extparams; } s.extparams = extparams; } int extindex = s.numextparams; LocalShaderParamState &ext = s.extparams[extindex]; ext.name = name; ext.type = type; ext.index = index; ext.loc = loc; s.numextparams++; return extindex; } static void allocglsluniformparam(Shader &s, int type, int index, bool local = false) { ShaderParamState &val = (type==SHPARAM_VERTEX ? vertexparamstate[index] : pixelparamstate[index]); int loc = val.name ? glGetUniformLocation_(s.program, val.name) : -1; if(loc == -1) { defformatstring(altname)("%s%d", type==SHPARAM_VERTEX ? "v" : "p", index); loc = glGetUniformLocation_(s.program, altname); } if(loc >= 0) loopi(s.numextparams) { LocalShaderParamState &ext = s.extparams[i]; if(ext.loc != loc) continue; if(ext.type==SHPARAM_LOOKUP) { ext.name = val.name; ext.type = type; ext.index = local ? -1 : index; } if(type==SHPARAM_VERTEX) s.extvertparams[index] = i; else s.extpixparams[index] = i; return; } if(loc == -1) { if(type==SHPARAM_VERTEX) s.extvertparams[index] = local ? UNUSEDEXTPARAM : ALLOCEXTPARAM; else s.extpixparams[index] = local ? UNUSEDEXTPARAM : ALLOCEXTPARAM; return; } int extindex = addextparam(s, val.name, type, local ? -1 : index, loc); if(type==SHPARAM_VERTEX) s.extvertparams[index] = extindex; else s.extpixparams[index] = extindex; } static void setglsluniformformat(Shader &s, const char *name, GLenum format, int size) { switch(format) { case GL_FLOAT: case GL_FLOAT_VEC2_ARB: case GL_FLOAT_VEC3_ARB: break; case GL_FLOAT_VEC4_ARB: default: return; } if(size > 1 || !strncmp(name, "gl_", 3)) return; int loc = glGetUniformLocation_(s.program, name); if(loc < 0) return; loopvj(s.defaultparams) if(s.defaultparams[j].loc == loc) { s.defaultparams[j].format = format; return; } loopj(s.numextparams) if(s.extparams[j].loc == loc) { s.extparams[j].format = format; return; } int extindex = addextparam(s, NULL, SHPARAM_LOOKUP, -1, loc); if(extindex >= 0) s.extparams[extindex].format = format; } static void allocglslactiveuniforms(Shader &s) { GLint numactive = 0; glGetObjectParameteriv_(s.program, GL_OBJECT_ACTIVE_UNIFORMS_ARB, &numactive); string name; loopi(numactive) { GLsizei namelen = 0; GLint size = 0; GLenum format = GL_FLOAT_VEC4_ARB; name[0] = '\0'; glGetActiveUniform_(s.program, i, sizeof(name)-1, &namelen, &size, &format, name); if(namelen <= 0) continue; name[clamp(int(namelen), 0, (int)sizeof(name)-2)] = '\0'; setglsluniformformat(s, name, format, size); } } static inline bool duplicateenvparam(GlobalShaderParamState ¶m) { loopj(RESERVEDSHADERPARAMS) { GlobalShaderParamState &vp = vertexparamstate[j]; if(vp.name && !vp.local && vp.version > param.version && !strcmp(vp.name, param.name)) return true; GlobalShaderParamState &pp = pixelparamstate[j]; if(pp.name && !pp.local && pp.version > param.version && !strcmp(pp.name, param.name)) return true; } return false; } void Shader::allocenvparams(Slot *slot) { if(!(type & SHADER_GLSLANG)) return; if(slot) { #define UNIFORMTEX(name, tmu) \ { \ loc = glGetUniformLocation_(program, name); \ int val = tmu; \ if(loc != -1) glUniform1i_(loc, val); \ } int loc, tmu = 2; if(type & SHADER_NORMALSLMS) { UNIFORMTEX("lmcolor", 1); UNIFORMTEX("lmdir", 2); tmu++; } else UNIFORMTEX("lightmap", 1); if(type & SHADER_ENVMAP) UNIFORMTEX("envmap", tmu++); UNIFORMTEX("shadowmap", 7); int stex = 0; loopv(slot->sts) { Slot::Tex &t = slot->sts[i]; switch(t.type) { case TEX_DIFFUSE: UNIFORMTEX("diffusemap", 0); break; case TEX_NORMAL: UNIFORMTEX("normalmap", tmu++); break; case TEX_GLOW: UNIFORMTEX("glowmap", tmu++); break; case TEX_DECAL: UNIFORMTEX("decal", tmu++); break; case TEX_SPEC: if(t.combined<0) UNIFORMTEX("specmap", tmu++); break; case TEX_DEPTH: if(t.combined<0) UNIFORMTEX("depthmap", tmu++); break; case TEX_UNKNOWN: { defformatstring(sname)("stex%d", stex++); UNIFORMTEX(sname, tmu++); break; } } } } if(!extvertparams) { extvertparams = new uchar[2*RESERVEDSHADERPARAMS]; extpixparams = extvertparams + RESERVEDSHADERPARAMS; } memset(extvertparams, ALLOCEXTPARAM, 2*RESERVEDSHADERPARAMS); loopi(RESERVEDSHADERPARAMS) if(vertexparamstate[i].name && !vertexparamstate[i].local && !duplicateenvparam(vertexparamstate[i])) allocglsluniformparam(*this, SHPARAM_VERTEX, i); loopi(RESERVEDSHADERPARAMS) if(pixelparamstate[i].name && !pixelparamstate[i].local && !duplicateenvparam(pixelparamstate[i])) allocglsluniformparam(*this, SHPARAM_PIXEL, i); allocglslactiveuniforms(*this); } static inline void setuniformval(LocalShaderParamState &l, const float *val) { if(memcmp(l.curval, val, sizeof(l.curval))) { memcpy(l.curval, val, sizeof(l.curval)); switch(l.format) { case GL_FLOAT: glUniform1fv_(l.loc, 1, l.curval); break; case GL_FLOAT_VEC2_ARB: glUniform2fv_(l.loc, 1, l.curval); break; case GL_FLOAT_VEC3_ARB: glUniform3fv_(l.loc, 1, l.curval); break; case GL_FLOAT_VEC4_ARB: glUniform4fv_(l.loc, 1, l.curval); break; } } } static inline void flushparam(int type, int index) { ShaderParamState &val = (type==SHPARAM_VERTEX ? vertexparamstate[index] : pixelparamstate[index]); if(Shader::lastshader && Shader::lastshader->type&SHADER_GLSLANG) { uchar &extindex = (type==SHPARAM_VERTEX ? Shader::lastshader->extvertparams[index] : Shader::lastshader->extpixparams[index]); if(extindex == ALLOCEXTPARAM) allocglsluniformparam(*Shader::lastshader, type, index, val.local); if(extindex < Shader::lastshader->numextparams) setuniformval(Shader::lastshader->extparams[extindex], val.val); } else if(val.dirty==ShaderParamState::DIRTY) { glProgramEnvParameter4fv_(type==SHPARAM_VERTEX ? GL_VERTEX_PROGRAM_ARB : GL_FRAGMENT_PROGRAM_ARB, index, val.val); val.dirty = ShaderParamState::CLEAN; } } static inline bool sortparamversions(const GlobalShaderParamState *x, const GlobalShaderParamState *y) { return x->version < y->version; } static uint resetparamversions() { GlobalShaderParamState *params[2*(RESERVEDSHADERPARAMS + MAXSHADERPARAMS)]; loopi(RESERVEDSHADERPARAMS + MAXSHADERPARAMS) { params[2*i+0] = &vertexparamstate[i]; params[2*i+1] = &pixelparamstate[i]; } quicksort(params, 2*(RESERVEDSHADERPARAMS + MAXSHADERPARAMS), sortparamversions); paramversion = 0; loopi(2*(RESERVEDSHADERPARAMS + MAXSHADERPARAMS)) params[i]->version = ++paramversion; return paramversion; } static inline ShaderParamState &setparamf(const char *name, int type, int index, float x, float y, float z, float w) { GlobalShaderParamState &val = (type==SHPARAM_VERTEX ? vertexparamstate[index] : pixelparamstate[index]); val.name = name; val.version = ++paramversion > 0 ? paramversion : resetparamversions(); if(val.dirty==ShaderParamState::INVALID || val.val[0]!=x || val.val[1]!=y || val.val[2]!=z || val.val[3]!=w) { val.val[0] = x; val.val[1] = y; val.val[2] = z; val.val[3] = w; val.dirty = ShaderParamState::DIRTY; } return val; } static inline ShaderParamState &setparamfv(const char *name, int type, int index, const float *v) { GlobalShaderParamState &val = (type==SHPARAM_VERTEX ? vertexparamstate[index] : pixelparamstate[index]); val.name = name; val.version = ++paramversion > 0 ? paramversion : resetparamversions(); if(val.dirty==ShaderParamState::INVALID || memcmp(val.val, v, sizeof(val.val))) { memcpy(val.val, v, sizeof(val.val)); val.dirty = ShaderParamState::DIRTY; } return val; } void setenvparamf(const char *name, int type, int index, float x, float y, float z, float w) { ShaderParamState &val = setparamf(name, type, index, x, y, z, w); val.local = false; if(val.dirty==ShaderParamState::DIRTY) dirtyenvparams = true; } void setenvparamfv(const char *name, int type, int index, const float *v) { ShaderParamState &val = setparamfv(name, type, index, v); val.local = false; if(val.dirty==ShaderParamState::DIRTY) dirtyenvparams = true; } void flushenvparamf(const char *name, int type, int index, float x, float y, float z, float w) { ShaderParamState &val = setparamf(name, type, index, x, y, z, w); val.local = false; flushparam(type, index); } void flushenvparamfv(const char *name, int type, int index, const float *v) { ShaderParamState &val = setparamfv(name, type, index, v); val.local = false; flushparam(type, index); } void setlocalparamf(const char *name, int type, int index, float x, float y, float z, float w) { ShaderParamState &val = setparamf(name, type, index, x, y, z, w); val.local = true; flushparam(type, index); } void setlocalparamfv(const char *name, int type, int index, const float *v) { ShaderParamState &val = setparamfv(name, type, index, v); val.local = true; flushparam(type, index); } void invalidateenvparams(int type, int start, int count) { GlobalShaderParamState *paramstate = type==SHPARAM_VERTEX ? vertexparamstate : pixelparamstate; int end = min(start + count, RESERVEDSHADERPARAMS + MAXSHADERPARAMS); while(start < end) { paramstate[start].dirty = ShaderParamState::INVALID; start++; } } void Shader::flushenvparams(Slot *slot) { if(type & SHADER_GLSLANG) { if(!used) allocenvparams(slot); loopi(numextparams) { LocalShaderParamState &ext = extparams[i]; if(ext.index >= 0) setuniformval(ext, ext.type==SHPARAM_VERTEX ? vertexparamstate[ext.index].val : pixelparamstate[ext.index].val); } } else if(dirtyenvparams) { loopi(RESERVEDSHADERPARAMS) { ShaderParamState &val = vertexparamstate[i]; if(val.local || val.dirty!=ShaderParamState::DIRTY) continue; glProgramEnvParameter4fv_(GL_VERTEX_PROGRAM_ARB, i, val.val); val.dirty = ShaderParamState::CLEAN; } loopi(RESERVEDSHADERPARAMS) { ShaderParamState &val = pixelparamstate[i]; if(val.local || val.dirty!=ShaderParamState::DIRTY) continue; glProgramEnvParameter4fv_(GL_FRAGMENT_PROGRAM_ARB, i, val.val); val.dirty = ShaderParamState::CLEAN; } dirtyenvparams = false; } used = true; } static inline void setglslslotparam(const ShaderParam &p, LocalShaderParamState &l, uint &mask, int i) { if(!(mask&(1< &defaultparams, Slot &slot, VSlot &vslot) { uint unimask = 0; loopv(vslot.params) { ShaderParam &p = vslot.params[i]; if(!defaultparams.inrange(p.loc)) continue; LocalShaderParamState &l = defaultparams[p.loc]; setglslslotparam(p, l, unimask, p.loc); } loopv(slot.params) { ShaderParam &p = slot.params[i]; if(!defaultparams.inrange(p.loc)) continue; LocalShaderParamState &l = defaultparams[p.loc]; setglslslotparam(p, l, unimask, p.loc); } loopv(defaultparams) { LocalShaderParamState &l = defaultparams[i]; setglslslotparam(l, l, unimask, i); } } static inline void setasmslotparam(const ShaderParam &p, LocalShaderParamState &l, uint &mask) { if(!(mask&(1< &defaultparams, Slot &slot, VSlot &vslot) { uint vertmask = 0, pixmask = 0; loopv(vslot.params) { ShaderParam &p = vslot.params[i]; if(!defaultparams.inrange(p.loc) || p.type==SHPARAM_UNIFORM) continue; LocalShaderParamState &l = defaultparams[p.loc]; setasmslotparam(p, l, l.type==SHPARAM_VERTEX ? vertmask : pixmask); } loopv(slot.params) { ShaderParam &p = slot.params[i]; if(!defaultparams.inrange(p.loc) || p.type==SHPARAM_UNIFORM) continue; LocalShaderParamState &l = defaultparams[p.loc]; setasmslotparam(p, l, l.type==SHPARAM_VERTEX ? vertmask : pixmask); } loopv(defaultparams) { LocalShaderParamState &l = defaultparams[i]; if(l.type!=SHPARAM_UNIFORM) setasmslotparam(l, l, l.type==SHPARAM_VERTEX ? vertmask : pixmask); } } void Shader::setslotparams(Slot &slot, VSlot &vslot) { if(type & SHADER_GLSLANG) setglslslotparams(defaultparams, slot, vslot); else setasmslotparams(defaultparams, slot, vslot); } void Shader::bindprograms() { if(this == lastshader || type&(SHADER_DEFERRED|SHADER_INVALID)) return; if(type & SHADER_GLSLANG) { glUseProgramObject_(program); } else { if(lastshader && lastshader->type & SHADER_GLSLANG) glUseProgramObject_(0); glBindProgram_(GL_VERTEX_PROGRAM_ARB, vs); glBindProgram_(GL_FRAGMENT_PROGRAM_ARB, ps); } lastshader = this; } VARFN(shaders, useshaders, -1, -1, 1, initwarning("shaders")); VARF(shaderprecision, 0, 0, 2, initwarning("shader quality")); VARF(forceglsl, 0, 0, 1, initwarning("shaders")); bool Shader::compile() { if(type & SHADER_GLSLANG) { if(!vsstr) vsobj = !reusevs || reusevs->type&SHADER_INVALID ? 0 : reusevs->vsobj; else compileglslshader(GL_VERTEX_SHADER_ARB, vsobj, vsstr, "VS", name, dbgshader || !variantshader); if(!psstr) psobj = !reuseps || reuseps->type&SHADER_INVALID ? 0 : reuseps->psobj; else compileglslshader(GL_FRAGMENT_SHADER_ARB, psobj, psstr, "PS", name, dbgshader || !variantshader); linkglslprogram(*this, !variantshader); return program!=0; } else { if(renderpath!=R_ASMSHADER && renderpath!=R_ASMGLSLANG) return false; if(!vsstr) vs = !reusevs || reusevs->type&SHADER_INVALID ? 0 : reusevs->vs; else if(!compileasmshader(GL_VERTEX_PROGRAM_ARB, vs, vsstr, "VS", name, dbgshader || !variantshader, variantshader!=NULL)) native = false; if(!psstr) ps = !reuseps || reuseps->type&SHADER_INVALID ? 0 : reuseps->ps; else if(!compileasmshader(GL_FRAGMENT_PROGRAM_ARB, ps, psstr, "PS", name, dbgshader || !variantshader, variantshader!=NULL)) native = false; return vs && ps && (!variantshader || native); } } void Shader::cleanup(bool invalid) { detailshader = NULL; used = false; native = true; if(vs) { if(reusevs) glDeletePrograms_(1, &vs); vs = 0; } if(ps) { if(reuseps) glDeletePrograms_(1, &ps); ps = 0; } if(vsobj) { if(reusevs) glDeleteObject_(vsobj); vsobj = 0; } if(psobj) { if(reuseps) glDeleteObject_(psobj); psobj = 0; } if(program) { glDeleteObject_(program); program = 0; } numextparams = 0; DELETEA(extparams); DELETEA(extvertparams); extpixparams = NULL; loopv(defaultparams) memset(defaultparams[i].curval, -1, sizeof(defaultparams[i].curval)); if(standard || invalid) { type = SHADER_INVALID; loopi(MAXVARIANTROWS) variants[i].setsize(0); DELETEA(vsstr); DELETEA(psstr); DELETEA(defer); defaultparams.setsize(0); attriblocs.setsize(0); uniformlocs.setsize(0); altshader = NULL; loopi(MAXSHADERDETAIL) fastshader[i] = this; reusevs = reuseps = NULL; } } static void genattriblocs(Shader &s, const char *vs, const char *ps) { static int len = strlen("#pragma CUBE2_attrib"); string name; int loc; while((vs = strstr(vs, "#pragma CUBE2_attrib"))) { if(sscanf(vs, "#pragma CUBE2_attrib %s %d", name, &loc) == 2) s.attriblocs.add(AttribLoc(getshaderparamname(name), loc)); vs += len; } } static void genuniformlocs(Shader &s, const char *vs, const char *ps) { static int len = strlen("#pragma CUBE2_uniform"); string name, blockname; int binding, stride; while((vs = strstr(vs, "#pragma CUBE2_uniform"))) { int numargs = sscanf(vs, "#pragma CUBE2_uniform %s %s %d %d", name, blockname, &binding, &stride); if(numargs >= 3) s.uniformlocs.add(UniformLoc(getshaderparamname(name), getshaderparamname(blockname), binding, numargs >= 4 ? stride : 0)); else if(numargs >= 1) s.uniformlocs.add(UniformLoc(getshaderparamname(name))); vs += len; } } Shader *newshader(int type, const char *name, const char *vs, const char *ps, Shader *variant = NULL, int row = 0) { if(Shader::lastshader) { if(renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) { glBindProgram_(GL_VERTEX_PROGRAM_ARB, 0); glBindProgram_(GL_FRAGMENT_PROGRAM_ARB, 0); } if(renderpath==R_GLSLANG || renderpath==R_ASMGLSLANG) glUseProgramObject_(0); Shader::lastshader = NULL; } Shader *exists = shaders.access(name); char *rname = exists ? exists->name : newstring(name); Shader &s = shaders[rname]; s.name = rname; s.vsstr = newstring(vs); s.psstr = newstring(ps); DELETEA(s.defer); s.type = type; s.variantshader = variant; s.standard = standardshader; if(forceshaders) s.forced = true; s.reusevs = s.reuseps = NULL; if(variant) { int row = 0, col = 0; if(!vs[0] || sscanf(vs, "%d , %d", &row, &col) >= 1) { DELETEA(s.vsstr); s.reusevs = !vs[0] ? variant : (variant->variants[row].inrange(col) ? variant->variants[row][col] : NULL); } row = col = 0; if(!ps[0] || sscanf(ps, "%d , %d", &row, &col) >= 1) { DELETEA(s.psstr); s.reuseps = !ps[0] ? variant : (variant->variants[row].inrange(col) ? variant->variants[row][col] : NULL); } } if(variant) loopv(variant->defaultparams) s.defaultparams.add(variant->defaultparams[i]); else loopv(curparams) s.defaultparams.add(curparams[i]); s.attriblocs.setsize(0); s.uniformlocs.setsize(0); if(type & SHADER_GLSLANG) { genattriblocs(s, vs, ps); genuniformlocs(s, vs, ps); } if(renderpath!=R_FIXEDFUNCTION && !s.compile()) { s.cleanup(true); if(variant) shaders.remove(rname); return NULL; } if(variant) variant->variants[row].add(&s); s.fixdetailshader(); return &s; } static const char *findglslmain(const char *s) { const char *main = strstr(s, "main"); if(!main) return NULL; for(; main >= s; main--) switch(*main) { case '\r': case '\n': case ';': return main + 1; } return s; } static uint findusedtexcoords(const char *str) { uint used = 0; for(;;) { const char *tc = strstr(str, "result.texcoord["); if(!tc) break; tc += strlen("result.texcoord["); int n = strtol(tc, (char **)&str, 10); if(n<0 || n>=16) continue; used |= 1<=(int)sizeof(texcoords)) continue; while(*str && *str!=']') str++; if(*str==']') { if(*++str!='.') { texcoords[n] = 0xF; continue; } for(;;) { switch(*++str) { case 'r': case 'x': texcoords[n] |= 1; continue; case 'g': case 'y': texcoords[n] |= 2; continue; case 'b': case 'z': texcoords[n] |= 4; continue; case 'a': case 'w': texcoords[n] |= 8; continue; } break; } } } loopi(sizeof(texcoords)) if(texcoords[i]>0 && texcoords[i]<0xF) { loopk(4) if(!(texcoords[i]&(1< &vsbuf, vector &psbuf, int fogtc, int fogcomp) { char *fogcoord = strstr(vsbuf.getbuf(), "result.fogcoord"); if(!fogcoord) return; static const int fogcoordlen = strlen("result.fogcoord"); char *afterfogcoord = fogcoord + fogcoordlen; if(*afterfogcoord=='.') afterfogcoord += 2; defformatstring(repfogcoord)("result.texcoord[%d].%c", fogtc, fogcomp==3 ? 'w' : 'x'+fogcomp); memcpy(fogcoord, repfogcoord, afterfogcoord - fogcoord); vsbuf.insert(afterfogcoord - vsbuf.getbuf(), repfogcoord + (afterfogcoord - fogcoord), strlen(repfogcoord) - (afterfogcoord - fogcoord)); char *fogoption = strstr(psbuf.getbuf(), "OPTION ARB_fog_linear;"); if(!fogoption) return; static const int fogoptionlen = strlen("OPTION ARB_fog_linear;"); memcpy(fogoption, "TEMP emufogcolor; ", fogoptionlen); char *str = psbuf.getbuf(); for(;;) { static const int colorlen = strlen("result.color"); str = strstr(str, "result.color"); if(!str) break; if(str[colorlen]!='.' || (str[colorlen+1]!='a' && str[colorlen+1]!='w')) memcpy(str, " emufogcolor", colorlen); str += colorlen; } defformatstring(fogtcstr)("fragment.texcoord[%d].%c", fogtc, fogcomp==3 ? 'w' : 'x'+fogcomp); static const int fragfogcoordlen = strlen("fragment.fogcoord.x"); str = strstr(psbuf.getbuf(), "fragment.fogcoord.x"); if(str) { memcpy(str, fogtcstr, fragfogcoordlen); psbuf.insert(&str[fragfogcoordlen] - psbuf.getbuf(), &fogtcstr[fragfogcoordlen], strlen(fogtcstr) - fragfogcoordlen); } char *end = strstr(psbuf.getbuf(), "END"); if(end) psbuf.setsize(end - psbuf.getbuf()); defformatstring(calcfog)( "TEMP emufog;\n" "SUB emufog.x, state.fog.params.z, %s;\n" "MUL_SAT emufog.x, emufog.x, state.fog.params.w;\n" "LRP result.color.rgb, emufog.x, emufogcolor, state.fog.color;\n" "END\n", fogtcstr); psbuf.put(calcfog, strlen(calcfog)+1); } VAR(reserveshadowmaptc, 1, 0, 0); VAR(reservedynlighttc, 1, 0, 0); VAR(minimizedynlighttcusage, 1, 0, 0); static void gengenericvariant(Shader &s, const char *sname, const char *vs, const char *ps, int row) { bool vschanged = false, pschanged = false; vector vsv, psv; vsv.put(vs, strlen(vs)+1); psv.put(ps, strlen(ps)+1); static const int len = strlen("#pragma CUBE2_variant"), olen = strlen("override"); for(char *vspragma = vsv.getbuf();; vschanged = true) { vspragma = strstr(vspragma, "#pragma CUBE2_variant"); if(!vspragma) break; memset(vspragma, ' ', len); vspragma += len; if(!strncmp(vspragma, "override", olen)) { memset(vspragma, ' ', olen); vspragma += olen; char *end = vspragma + strcspn(vspragma, "\n\r"); int endlen = strspn(end, "\n\r"); memset(end, ' ', endlen); } } for(char *pspragma = psv.getbuf();; pschanged = true) { pspragma = strstr(pspragma, "#pragma CUBE2_variant"); if(!pspragma) break; memset(pspragma, ' ', len); pspragma += len; if(!strncmp(pspragma, "override", olen)) { memset(pspragma, ' ', olen); pspragma += olen; char *end = pspragma + strcspn(pspragma, "\n\r"); int endlen = strspn(end, "\n\r"); memset(end, ' ', endlen); } } defformatstring(varname)("%s", s.variants[row].length(), row, sname); defformatstring(reuse)("%d", row); newshader(s.type, varname, vschanged ? vsv.getbuf() : reuse, pschanged ? psv.getbuf() : reuse, &s, row); } static bool genwatervariant(Shader &s, const char *sname, vector &vs, vector &ps, int row) { char *vspragma = strstr(vs.getbuf(), "#pragma CUBE2_water"); if(!vspragma) return false; char *pspragma = strstr(ps.getbuf(), "#pragma CUBE2_water"); if(!pspragma) return false; vspragma += strcspn(vspragma, "\n"); if(*vspragma) vspragma++; pspragma += strcspn(pspragma, "\n"); if(*pspragma) pspragma++; if(s.type & SHADER_GLSLANG) { const char *fadedef = "waterfade = gl_Vertex.z*waterfadeparams.x + waterfadeparams.y;\n"; vs.insert(vspragma-vs.getbuf(), fadedef, strlen(fadedef)); const char *fadeuse = "gl_FragColor.a = waterfade;\n"; ps.insert(pspragma-ps.getbuf(), fadeuse, strlen(fadeuse)); const char *fadedecl = "uniform vec4 waterfadeparams; varying float waterfade;\n"; const char *vsmain = findglslmain(vs.getbuf()), *psmain = findglslmain(ps.getbuf()); vs.insert(vsmain ? vsmain - vs.getbuf() : 0, fadedecl, strlen(fadedecl)); ps.insert(psmain ? psmain - ps.getbuf() : 0, fadedecl, strlen(fadedecl)); } else { int fadetc = -1, fadecomp = -1; if(!findunusedtexcoordcomponent(vs.getbuf(), fadetc, fadecomp)) { uint usedtc = findusedtexcoords(vs.getbuf()); int reservetc = row%2 ? reserveshadowmaptc : reservedynlighttc; loopi(maxtexcoords-reservetc) if(!(usedtc&(1<=0) { defformatstring(fadedef)("MAD result.texcoord[%d].%c, vertex.position.z, program.env[8].x, program.env[8].y;\n", fadetc, fadecomp==3 ? 'w' : 'x'+fadecomp); vs.insert(vspragma-vs.getbuf(), fadedef, strlen(fadedef)); defformatstring(fadeuse)("MOV result.color.a, fragment.texcoord[%d].%c;\n", fadetc, fadecomp==3 ? 'w' : 'x'+fadecomp); ps.insert(pspragma-ps.getbuf(), fadeuse, strlen(fadeuse)); } else // fallback - use fog value, works under water but not above { const char *fogfade = "MAD result.color.a, fragment.fogcoord.x, program.env[8].z, program.env[8].w;\n"; ps.insert(pspragma-ps.getbuf(), fogfade, strlen(fogfade)); } } defformatstring(name)("%s", sname); Shader *variant = newshader(s.type, name, vs.getbuf(), ps.getbuf(), &s, row); return variant!=NULL; } static void genwatervariant(Shader &s, const char *sname, const char *vs, const char *ps, int row = 2) { vector vsw, psw; vsw.put(vs, strlen(vs)+1); psw.put(ps, strlen(ps)+1); genwatervariant(s, sname, vsw, psw, row); } static void gendynlightvariant(Shader &s, const char *sname, const char *vs, const char *ps, int row = 0) { int numlights = 0, lights[MAXDYNLIGHTS]; int emufogtc = -1, emufogcomp = -1; if(s.type & SHADER_GLSLANG) numlights = maxvaryings < 48 || minimizedynlighttcusage ? 1 : MAXDYNLIGHTS; else { uint usedtc = findusedtexcoords(vs); int reservetc = row%2 ? reserveshadowmaptc : reservedynlighttc; if(maxtexcoords-reservetc<0) return; int limit = minimizedynlighttcusage ? 1 : MAXDYNLIGHTS; loopi(maxtexcoords-reservetc) if(!(usedtc&(1<=limit) break; } extern int emulatefog; if(emulatefog && reservetc>0 && numlights+1 vspragma) vsmain = vs; psmain = findglslmain(ps); if(psmain > pspragma) psmain = ps; } vector vsdl, psdl; loopi(MAXDYNLIGHTS) { vsdl.setsize(0); psdl.setsize(0); if(vsmain >= vs) vsdl.put(vs, vsmain - vs); if(psmain >= ps) psdl.put(ps, psmain - ps); if(s.type & SHADER_GLSLANG) { loopk(i+1) { defformatstring(pos)("%sdynlight%d%s%s", !k || k==numlights ? "uniform vec4 " : " ", k, k < numlights ? "pos" : "offset", k==i || k+1==numlights ? ";\n" : ","); if(k=numlights) formatstring(tc)( "%s" "MAD dynlightdir.xyz, fragment.texcoord[%d], program.env[%d].w, program.env[%d];\n", k==numlights ? "TEMP dynlightdir;\n" : "", lights[0], k-1, k-1); else if(ati_dph_bug || lights[k]==emufogtc) formatstring(tc)( "MAD result.texcoord[%d].xyz, vertex.position, program.env[%d].w, program.env[%d];\n", lights[k], 10+k, 10+k); else formatstring(tc)( "MAD result.texcoord[%d].xyz, vertex.position, program.env[%d].w, program.env[%d];\n" "MOV result.texcoord[%d].w, 1;\n", lights[k], 10+k, 10+k, lights[k]); if(k < numlights) vsdl.put(tc, strlen(tc)); else psdl.put(tc, strlen(tc)); if(s.type & SHADER_GLSLANG) formatstring(dl)( "%s.rgb += dynlight%dcolor.rgb * (1.0 - clamp(dot(dynlight%ddir, dynlight%ddir), 0.0, 1.0));\n", pslight, k, k, k); else if(k>=numlights) formatstring(dl)( "DP3_SAT dynlight.x, dynlightdir, dynlightdir;\n" "SUB dynlight.x, 1, dynlight.x;\n" "MAD %s.rgb, program.env[%d], dynlight.x, %s;\n", pslight, 10+k, pslight); else if(ati_dph_bug || lights[k]==emufogtc) formatstring(dl)( "%s" "DP3_SAT dynlight.x, fragment.texcoord[%d], fragment.texcoord[%d];\n" "SUB dynlight.x, 1, dynlight.x;\n" "MAD %s.rgb, program.env[%d], dynlight.x, %s;\n", !k ? "TEMP dynlight;\n" : "", lights[k], lights[k], pslight, 10+k, pslight); else formatstring(dl)( "%s" "DPH_SAT dynlight.x, -fragment.texcoord[%d], fragment.texcoord[%d];\n" "MAD %s.rgb, program.env[%d], dynlight.x, %s;\n", !k ? "TEMP dynlight;\n" : "", lights[k], lights[k], pslight, 10+k, pslight); psdl.put(dl, strlen(dl)); } vsdl.put(vspragma, strlen(vspragma)+1); psdl.put(pspragma, strlen(pspragma)+1); if(emufogtc >= 0 && i+1 == numlights) genemufog(vsdl, psdl, emufogtc, emufogcomp); defformatstring(name)("%s", i+1, sname); Shader *variant = newshader(s.type, name, vsdl.getbuf(), psdl.getbuf(), &s, row); if(!variant) return; if(row < 4) genwatervariant(s, name, vsdl, psdl, row+2); } } static void genshadowmapvariant(Shader &s, const char *sname, const char *vs, const char *ps, int row = 1) { int smtc = -1, emufogtc = -1, emufogcomp = -1; if(!(s.type & SHADER_GLSLANG)) { uint usedtc = findusedtexcoords(vs); if(maxtexcoords-reserveshadowmaptc<0) return; loopi(maxtexcoords-reserveshadowmaptc) if(!(usedtc&(1<0 && !(usedtc&(1<<(maxtexcoords-reserveshadowmaptc))) && strstr(ps, "OPTION ARB_fog_linear;")) { if(!strstr(vs, "result.fogcoord") || !findunusedtexcoordcomponent(vs, emufogtc, emufogcomp)) return; smtc = maxtexcoords-reserveshadowmaptc; } if(smtc<0) return; } const char *vspragma = strstr(vs, "#pragma CUBE2_shadowmap"), *pspragma = strstr(ps, "#pragma CUBE2_shadowmap"); string pslight; vspragma += strcspn(vspragma, "\n"); if(*vspragma) vspragma++; if(sscanf(pspragma, "#pragma CUBE2_shadowmap %s", pslight)!=1) return; pspragma += strcspn(pspragma, "\n"); if(*pspragma) pspragma++; const char *vsmain = vs, *psmain = ps; if(s.type & SHADER_GLSLANG) { vsmain = findglslmain(vs); if(vsmain > vspragma) vsmain = vs; psmain = findglslmain(ps); if(psmain > pspragma) psmain = ps; } vector vssm, pssm; if(vsmain >= vs) vssm.put(vs, vsmain - vs); if(psmain >= ps) pssm.put(ps, psmain - ps); if(s.type & SHADER_GLSLANG) { const char *tc = "varying vec3 shadowmaptc;\n"; vssm.put(tc, strlen(tc)); pssm.put(tc, strlen(tc)); const char *smtex = "uniform sampler2D shadowmap;\n" "uniform vec4 shadowmapambient;\n"; pssm.put(smtex, strlen(smtex)); } vssm.put(vsmain, vspragma-vsmain); pssm.put(psmain, pspragma-psmain); extern int smoothshadowmappeel; if(s.type & SHADER_GLSLANG) { const char *tc = "shadowmaptc = vec3(gl_TextureMatrix[2] * gl_Vertex);\n"; vssm.put(tc, strlen(tc)); const char *sm = smoothshadowmappeel ? "vec4 smvals = texture2D(shadowmap, shadowmaptc.xy);\n" "vec2 smdiff = clamp(smvals.xz - shadowmaptc.zz*smvals.y, 0.0, 1.0);\n" "float shadowed = clamp((smdiff.x > 0.0 ? smvals.w : 0.0) - 8.0*smdiff.y, 0.0, 1.0);\n" : "vec4 smvals = texture2D(shadowmap, shadowmaptc.xy);\n" "float smtest = shadowmaptc.z*smvals.y;\n" "float shadowed = smtest < smvals.x && smtest > smvals.z ? smvals.w : 0.0;\n"; pssm.put(sm, strlen(sm)); defformatstring(smlight)( "%s.rgb -= shadowed*clamp(%s.rgb - shadowmapambient.rgb, 0.0, 1.0);\n", pslight, pslight, pslight); pssm.put(smlight, strlen(smlight)); } else { defformatstring(tc)( "DP4 result.texcoord[%d].x, state.matrix.texture[2].row[0], vertex.position;\n" "DP4 result.texcoord[%d].y, state.matrix.texture[2].row[1], vertex.position;\n" "DP4 result.texcoord[%d].z, state.matrix.texture[2].row[2], vertex.position;\n", smtc, smtc, smtc); vssm.put(tc, strlen(tc)); defformatstring(sm)( smoothshadowmappeel ? "TEMP smvals, smdiff, smambient;\n" "TEX smvals, fragment.texcoord[%d], texture[7], 2D;\n" "MAD_SAT smdiff.xz, -fragment.texcoord[%d].z, smvals.y, smvals;\n" "CMP smvals.w, -smdiff.x, smvals.w, 0;\n" "MAD_SAT smvals.w, -8, smdiff.z, smvals.w;\n" : "TEMP smvals, smtest, smambient;\n" "TEX smvals, fragment.texcoord[%d], texture[7], 2D;\n" "MUL smtest.z, fragment.texcoord[%d].z, smvals.y;\n" "SLT smtest.xz, smtest.z, smvals;\n" "MAD_SAT smvals.w, smvals.w, smtest.x, -smtest.z;\n", smtc, smtc); pssm.put(sm, strlen(sm)); formatstring(sm)( "SUB_SAT smambient.rgb, %s, program.env[7];\n" "MAD %s.rgb, smvals.w, -smambient, %s;\n", pslight, pslight, pslight); pssm.put(sm, strlen(sm)); } if(!hasFBO) for(char *s = pssm.getbuf();;) { s = strstr(s, "smvals.w"); if(!s) break; s[7] = 'y'; s += 8; } vssm.put(vspragma, strlen(vspragma)+1); pssm.put(pspragma, strlen(pspragma)+1); if(emufogtc >= 0) genemufog(vssm, pssm, emufogtc, emufogcomp); defformatstring(name)("%s", sname); Shader *variant = newshader(s.type, name, vssm.getbuf(), pssm.getbuf(), &s, row); if(!variant) return; genwatervariant(s, name, vssm.getbuf(), pssm.getbuf(), row+2); if(strstr(vs, "#pragma CUBE2_dynlight")) gendynlightvariant(s, name, vssm.getbuf(), pssm.getbuf(), row); } static void genfogshader(vector &vsbuf, vector &psbuf, const char *vs, const char *ps) { const char *vspragma = strstr(vs, "#pragma CUBE2_fog"), *pspragma = strstr(ps, "#pragma CUBE2_fog"); if(!vspragma && !pspragma) return; static const int pragmalen = strlen("#pragma CUBE2_fog"); const char *vsend = strrchr(vs, '}'); if(vsend) { vsbuf.put(vs, vsend - vs); const char *vsdef = "\n#define FOG_COORD "; const char *vsfog = "\ngl_FogFragCoord = -dot((FOG_COORD), gl_ModelViewMatrixTranspose[2]);\n"; int clen = 0; if(vspragma) { vspragma += pragmalen; while(*vspragma && !isspace(*vspragma)) vspragma++; vspragma += strspn(vspragma, " \t\v\f"); clen = strcspn(vspragma, "\r\n"); } if(clen <= 0) { vspragma = "gl_Vertex"; clen = strlen(vspragma); } vsbuf.put(vsdef, strlen(vsdef)); vsbuf.put(vspragma, clen); vsbuf.put(vsfog, strlen(vsfog)); vsbuf.put(vsend, strlen(vsend)+1); } const char *psend = strrchr(ps, '}'); if(psend) { psbuf.put(ps, psend - ps); const char *psdef = "\n#define FOG_COLOR "; const char *psfog = pspragma && !strncmp(pspragma+pragmalen, "rgba", 4) ? "\ngl_FragColor = mix((FOG_COLOR), gl_FragColor, clamp((gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0));\n" : "\ngl_FragColor.rgb = mix((FOG_COLOR).rgb, gl_FragColor.rgb, clamp((gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0));\n"; int clen = 0; if(pspragma) { pspragma += pragmalen; while (isalpha(*pspragma)) pspragma++; while(*pspragma && !isspace(*pspragma)) pspragma++; pspragma += strspn(pspragma, " \t\v\f"); clen = strcspn(pspragma, "\r\n"); } if(clen <= 0) { pspragma = "gl_Fog.color"; clen = strlen(pspragma); } psbuf.put(psdef, strlen(psdef)); psbuf.put(pspragma, clen); psbuf.put(psfog, strlen(psfog)); psbuf.put(psend, strlen(psend)+1); } } static void genuniformdefs(vector &vsbuf, vector &psbuf, const char *vs, const char *ps, Shader *variant = NULL) { if(variant ? variant->defaultparams.empty() : curparams.empty()) return; const char *vsmain = findglslmain(vs), *psmain = findglslmain(ps); if(!vsmain || !psmain) return; vsbuf.put(vs, vsmain - vs); psbuf.put(ps, psmain - ps); if(variant) loopv(variant->defaultparams) { defformatstring(uni)("\nuniform vec4 %s;\n", variant->defaultparams[i].name); vsbuf.put(uni, strlen(uni)); psbuf.put(uni, strlen(uni)); } else loopv(curparams) { defformatstring(uni)("\nuniform vec4 %s;\n", curparams[i].name); vsbuf.put(uni, strlen(uni)); psbuf.put(uni, strlen(uni)); } vsbuf.put(vsmain, strlen(vsmain)+1); psbuf.put(psmain, strlen(psmain)+1); } VAR(defershaders, 0, 1, 1); void defershader(int *type, const char *name, const char *contents) { Shader *exists = shaders.access(name); if(exists && !(exists->type&SHADER_INVALID)) return; if(!defershaders) { execute(contents); return; } char *rname = exists ? exists->name : newstring(name); Shader &s = shaders[rname]; s.name = rname; DELETEA(s.defer); s.defer = newstring(contents); s.type = SHADER_DEFERRED | *type; s.standard = standardshader; } void useshader(Shader *s) { if(!(s->type&SHADER_DEFERRED) || !s->defer) return; char *defer = s->defer; s->defer = NULL; bool wasstandard = standardshader, wasforcing = forceshaders; int oldflags = identflags; standardshader = s->standard; forceshaders = false; identflags &= ~IDF_PERSIST; curparams.shrink(0); execute(defer); identflags = oldflags; forceshaders = wasforcing; standardshader = wasstandard; delete[] defer; if(s->type&SHADER_DEFERRED) { DELETEA(s->defer); s->type = SHADER_INVALID; } } void fixshaderdetail() { // must null out separately because fixdetailshader can recursively set it enumerate(shaders, Shader, s, { if(!s.forced) s.detailshader = NULL; }); enumerate(shaders, Shader, s, { if(s.forced) s.fixdetailshader(); }); linkslotshaders(); } int Shader::uniformlocversion() { static int version = 0; if(++version >= 0) return version; version = 0; enumerate(shaders, Shader, s, { loopvj(s.uniformlocs) s.uniformlocs[j].version = -1; }); return version; } VARF(nativeshaders, 0, 1, 1, fixshaderdetail()); VARFP(shaderdetail, 0, MAXSHADERDETAIL, MAXSHADERDETAIL, fixshaderdetail()); void Shader::fixdetailshader(bool force, bool recurse) { Shader *alt = this; detailshader = NULL; do { Shader *cur = shaderdetail < MAXSHADERDETAIL ? alt->fastshader[shaderdetail] : alt; if(cur->type&SHADER_DEFERRED && force) useshader(cur); if(!(cur->type&SHADER_INVALID)) { if(cur->type&SHADER_DEFERRED) break; detailshader = cur; if(cur->native || !nativeshaders) break; } alt = alt->altshader; } while(alt && alt!=this); if(recurse && detailshader) loopi(MAXVARIANTROWS) loopvj(detailshader->variants[i]) detailshader->variants[i][j]->fixdetailshader(force, false); } Shader *useshaderbyname(const char *name) { Shader *s = shaders.access(name); if(!s) return NULL; if(!s->detailshader) s->fixdetailshader(); s->forced = true; return s; } void shader(int *type, char *name, char *vs, char *ps) { if(lookupshaderbyname(name)) return; if((*type & SHADER_GLSLANG ? renderpath!=R_GLSLANG && renderpath!=R_ASMGLSLANG : renderpath==R_GLSLANG) || (!hasCM && strstr(ps, *type & SHADER_GLSLANG ? "textureCube" : "CUBE;")) || (!hasTR && strstr(ps, *type & SHADER_GLSLANG ? "texture2DRect" : "RECT;"))) { curparams.shrink(0); return; } extern int mesa_program_bug; if(renderpath!=R_FIXEDFUNCTION) { defformatstring(info)("shader %s", name); renderprogress(loadprogress, info); } if((renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) && mesa_program_bug && initshaders && !(*type & SHADER_GLSLANG)) { glEnable(GL_VERTEX_PROGRAM_ARB); glEnable(GL_FRAGMENT_PROGRAM_ARB); } vector vsbuf, psbuf, vsbak, psbak; #define GENSHADER(cond, body) \ if(cond) \ { \ if(vsbuf.length()) { vsbak.setsize(0); vsbak.put(vs, strlen(vs)+1); vs = vsbak.getbuf(); vsbuf.setsize(0); } \ if(psbuf.length()) { psbak.setsize(0); psbak.put(ps, strlen(ps)+1); ps = psbak.getbuf(); psbuf.setsize(0); } \ body; \ if(vsbuf.length()) vs = vsbuf.getbuf(); \ if(psbuf.length()) ps = psbuf.getbuf(); \ } if(renderpath!=R_FIXEDFUNCTION) { if(*type & SHADER_GLSLANG) { GENSHADER(curparams.length(), genuniformdefs(vsbuf, psbuf, vs, ps)); GENSHADER(strstr(vs, "#pragma CUBE2_fog") || strstr(ps, "#pragma CUBE2_fog"), genfogshader(vsbuf, psbuf, vs, ps)); } } Shader *s = newshader(*type, name, vs, ps); if(s && renderpath!=R_FIXEDFUNCTION) { // '#' is a comment in vertex/fragment programs, while '#pragma' allows an escape for GLSL, so can handle both at once if(strstr(vs, "#pragma CUBE2_water")) genwatervariant(*s, s->name, vs, ps); if(strstr(vs, "#pragma CUBE2_shadowmap")) genshadowmapvariant(*s, s->name, vs, ps); if(strstr(vs, "#pragma CUBE2_dynlight")) gendynlightvariant(*s, s->name, vs, ps); } if((renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) && mesa_program_bug && initshaders && !(*type & SHADER_GLSLANG)) { glDisable(GL_VERTEX_PROGRAM_ARB); glDisable(GL_FRAGMENT_PROGRAM_ARB); } curparams.shrink(0); } void variantshader(int *type, char *name, int *row, char *vs, char *ps) { if(*row < 0) { shader(type, name, vs, ps); return; } if(renderpath==R_FIXEDFUNCTION && standardshader) return; Shader *s = lookupshaderbyname(name); if(!s) return; defformatstring(varname)("%s", s->variants[*row].length(), *row, name); //defformatstring(info)("shader %s", varname); //renderprogress(loadprogress, info); extern int mesa_program_bug; if((renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) && mesa_program_bug && initshaders && !(*type & SHADER_GLSLANG)) { glEnable(GL_VERTEX_PROGRAM_ARB); glEnable(GL_FRAGMENT_PROGRAM_ARB); } vector vsbuf, psbuf, vsbak, psbak; if(renderpath!=R_FIXEDFUNCTION) { if(*type & SHADER_GLSLANG) { GENSHADER(s->defaultparams.length(), genuniformdefs(vsbuf, psbuf, vs, ps, s)); GENSHADER(strstr(vs, "#pragma CUBE2_fog") || strstr(ps, "#pragma CUBE2_fog"), genfogshader(vsbuf, psbuf, vs, ps)); } } Shader *v = newshader(*type, varname, vs, ps, s, *row); if(v && renderpath!=R_FIXEDFUNCTION) { // '#' is a comment in vertex/fragment programs, while '#pragma' allows an escape for GLSL, so can handle both at once if(strstr(vs, "#pragma CUBE2_dynlight")) gendynlightvariant(*s, varname, vs, ps, *row); if(strstr(ps, "#pragma CUBE2_variant") || strstr(vs, "#pragma CUBE2_variant")) gengenericvariant(*s, varname, vs, ps, *row); } if((renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) && mesa_program_bug && initshaders && !(*type & SHADER_GLSLANG)) { glDisable(GL_VERTEX_PROGRAM_ARB); glDisable(GL_FRAGMENT_PROGRAM_ARB); } } void setshader(char *name) { curparams.shrink(0); Shader *s = shaders.access(name); if(!s) { if(renderpath!=R_FIXEDFUNCTION) conoutf(CON_ERROR, "no such shader: %s", name); } else curshader = s; } ShaderParam *findshaderparam(Slot &s, const char *name, int type = -1, int index = -1) { loopv(s.params) { ShaderParam ¶m = s.params[i]; if((name && param.name && !strcmp(name, param.name)) || (param.type==type && param.index==index)) return ¶m; } if(!s.shader->detailshader) return NULL; loopv(s.shader->detailshader->defaultparams) { ShaderParam ¶m = s.shader->detailshader->defaultparams[i]; if((name && param.name && !strcmp(name, param.name)) || (param.type==type && param.index==index)) return ¶m; } return NULL; } ShaderParam *findshaderparam(VSlot &s, const char *name, int type = -1, int index = -1) { loopv(s.params) { ShaderParam ¶m = s.params[i]; if((name && param.name && !strcmp(name, param.name)) || (param.type==type && param.index==index)) return ¶m; } return findshaderparam(*s.slot, name, type, index); } void resetslotshader() { curshader = NULL; curparams.shrink(0); } void setslotshader(Slot &s) { s.shader = curshader; if(!s.shader) { s.shader = stdworldshader; return; } loopv(curparams) s.params.add(curparams[i]); } static void linkslotshaderparams(vector ¶ms, Shader *sh, bool load) { if(sh) loopv(params) { int loc = -1; ShaderParam ¶m = params[i]; loopv(sh->defaultparams) { ShaderParam &dparam = sh->defaultparams[i]; if(param.name ? dparam.name==param.name : dparam.type==param.type && dparam.index==param.index) { if(memcmp(param.val, dparam.val, sizeof(param.val))) loc = i; break; } } param.loc = loc; } else if(load) loopv(params) params[i].loc = -1; } void linkslotshader(Slot &s, bool load) { if(!s.shader) return; if(load && !s.shader->detailshader) s.shader->fixdetailshader(); Shader *sh = s.shader->detailshader; linkslotshaderparams(s.params, sh, load); } void linkvslotshader(VSlot &s, bool load) { if(!s.slot->shader) return; Shader *sh = s.slot->shader->detailshader; linkslotshaderparams(s.params, sh, load); if(!sh) return; if(s.slot->texmask&(1<val[k], 0.0f, 1.0f); ShaderParam *pulseparam = findshaderparam(s, "pulseglowcolor"), *speedparam = findshaderparam(s, "pulseglowspeed"); if(pulseparam) loopk(3) s.pulseglowcolor[k] = clamp(pulseparam->val[k], 0.0f, 1.0f); if(speedparam) s.pulseglowspeed = speedparam->val[0]/1000.0f; } if(sh->type&SHADER_ENVMAP) { ShaderParam *envparam = findshaderparam(s, "envscale"); if(envparam) loopk(3) s.envscale[k] = clamp(envparam->val[k], 0.0f, 1.0f); } } void altshader(char *origname, char *altname) { Shader *orig = shaders.access(origname), *alt = shaders.access(altname); if(!orig || !alt) return; orig->altshader = alt; orig->fixdetailshader(false); } void fastshader(char *nice, char *fast, int *detail) { Shader *ns = shaders.access(nice), *fs = shaders.access(fast); if(!ns || !fs) return; loopi(min(*detail+1, MAXSHADERDETAIL)) ns->fastshader[i] = fs; ns->fixdetailshader(false); } COMMAND(shader, "isss"); COMMAND(variantshader, "isiss"); COMMAND(setshader, "s"); COMMAND(altshader, "ss"); COMMAND(fastshader, "ssi"); COMMAND(defershader, "iss"); ICOMMAND(forceshader, "s", (const char *name), useshaderbyname(name)); void isshaderdefined(char *name) { Shader *s = lookupshaderbyname(name); intret(s ? 1 : 0); } void isshadernative(char *name) { Shader *s = lookupshaderbyname(name); intret(s && s->native ? 1 : 0); } COMMAND(isshaderdefined, "s"); COMMAND(isshadernative, "s"); static hashset shaderparamnames(256); const char *getshaderparamname(const char *name) { const char **exists = shaderparamnames.access(name); if(exists) return *exists; name = newstring(name); shaderparamnames[name] = name; return name; } void addshaderparam(const char *name, int type, int n, float x, float y, float z, float w) { if((type==SHPARAM_VERTEX || type==SHPARAM_PIXEL) && (n<0 || n>=MAXSHADERPARAMS)) { conoutf(CON_ERROR, "shader param index must be 0..%d\n", MAXSHADERPARAMS-1); return; } if(name) name = getshaderparamname(name); loopv(curparams) { ShaderParam ¶m = curparams[i]; if(param.type == type && (name ? param.name==name : param.index == n)) { param.val[0] = x; param.val[1] = y; param.val[2] = z; param.val[3] = w; return; } } ShaderParam param = {name, type, n, -1, {x, y, z, w}}; curparams.add(param); } ICOMMAND(setvertexparam, "iffff", (int *n, float *x, float *y, float *z, float *w), addshaderparam(NULL, SHPARAM_VERTEX, *n, *x, *y, *z, *w)); ICOMMAND(setpixelparam, "iffff", (int *n, float *x, float *y, float *z, float *w), addshaderparam(NULL, SHPARAM_PIXEL, *n, *x, *y, *z, *w)); ICOMMAND(setuniformparam, "sffff", (char *name, float *x, float *y, float *z, float *w), addshaderparam(name, SHPARAM_UNIFORM, -1, *x, *y, *z, *w)); ICOMMAND(setshaderparam, "sffff", (char *name, float *x, float *y, float *z, float *w), addshaderparam(name, SHPARAM_LOOKUP, -1, *x, *y, *z, *w)); ICOMMAND(defvertexparam, "siffff", (char *name, int *n, float *x, float *y, float *z, float *w), addshaderparam(name[0] ? name : NULL, SHPARAM_VERTEX, *n, *x, *y, *z, *w)); ICOMMAND(defpixelparam, "siffff", (char *name, int *n, float *x, float *y, float *z, float *w), addshaderparam(name[0] ? name : NULL, SHPARAM_PIXEL, *n, *x, *y, *z, *w)); ICOMMAND(defuniformparam, "sffff", (char *name, float *x, float *y, float *z, float *w), addshaderparam(name, SHPARAM_UNIFORM, -1, *x, *y, *z, *w)); #define NUMPOSTFXBINDS 10 struct postfxtex { GLuint id; int scale, used; postfxtex() : id(0), scale(0), used(-1) {} }; vector postfxtexs; int postfxbinds[NUMPOSTFXBINDS]; GLuint postfxfb = 0; int postfxw = 0, postfxh = 0; struct postfxpass { Shader *shader; vec4 params; uint inputs, freeinputs; int outputbind, outputscale; postfxpass() : shader(NULL), inputs(1), freeinputs(1), outputbind(0), outputscale(0) {} }; vector postfxpasses; static int allocatepostfxtex(int scale) { loopv(postfxtexs) { postfxtex &t = postfxtexs[i]; if(t.scale==scale && t.used < 0) return i; } postfxtex &t = postfxtexs.add(); t.scale = scale; glGenTextures(1, &t.id); createtexture(t.id, max(screen->w>>scale, 1), max(screen->h>>scale, 1), NULL, 3, 1, GL_RGB, GL_TEXTURE_RECTANGLE_ARB); return postfxtexs.length()-1; } void cleanuppostfx(bool fullclean) { if(fullclean && postfxfb) { glDeleteFramebuffers_(1, &postfxfb); postfxfb = 0; } loopv(postfxtexs) glDeleteTextures(1, &postfxtexs[i].id); postfxtexs.shrink(0); postfxw = 0; postfxh = 0; } void renderpostfx() { if(postfxpasses.empty() || renderpath==R_FIXEDFUNCTION) return; if(postfxw != screen->w || postfxh != screen->h) { cleanuppostfx(false); postfxw = screen->w; postfxh = screen->h; } int binds[NUMPOSTFXBINDS]; loopi(NUMPOSTFXBINDS) binds[i] = -1; loopv(postfxtexs) postfxtexs[i].used = -1; binds[0] = allocatepostfxtex(0); postfxtexs[binds[0]].used = 0; glBindTexture(GL_TEXTURE_RECTANGLE_ARB, postfxtexs[binds[0]].id); glCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, screen->w, screen->h); if(hasFBO && postfxpasses.length() > 1) { if(!postfxfb) glGenFramebuffers_(1, &postfxfb); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, postfxfb); } setenvparamf("millis", SHPARAM_VERTEX, 1, lastmillis/1000.0f, lastmillis/1000.0f, lastmillis/1000.0f); loopv(postfxpasses) { postfxpass &p = postfxpasses[i]; int tex = -1; if(!postfxpasses.inrange(i+1)) { if(hasFBO && postfxpasses.length() > 1) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); } else { tex = allocatepostfxtex(p.outputscale); if(hasFBO) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_RECTANGLE_ARB, postfxtexs[tex].id, 0); } int w = tex >= 0 ? max(screen->w>>postfxtexs[tex].scale, 1) : screen->w, h = tex >= 0 ? max(screen->h>>postfxtexs[tex].scale, 1) : screen->h; glViewport(0, 0, w, h); p.shader->set(); setlocalparamfv("params", SHPARAM_VERTEX, 0, p.params.v); setlocalparamfv("params", SHPARAM_PIXEL, 0, p.params.v); int tw = w, th = h, tmu = 0; loopj(NUMPOSTFXBINDS) if(p.inputs&(1<= 0) { if(!tmu) { tw = max(screen->w>>postfxtexs[binds[j]].scale, 1); th = max(screen->h>>postfxtexs[binds[j]].scale, 1); } else glActiveTexture_(GL_TEXTURE0_ARB + tmu); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, postfxtexs[binds[j]].id); ++tmu; } if(tmu) glActiveTexture_(GL_TEXTURE0_ARB); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(-1, -1); glTexCoord2f(tw, 0); glVertex2f( 1, -1); glTexCoord2f(0, th); glVertex2f(-1, 1); glTexCoord2f(tw, th); glVertex2f( 1, 1); glEnd(); loopj(NUMPOSTFXBINDS) if(p.freeinputs&(1<= 0) { postfxtexs[binds[j]].used = -1; binds[j] = -1; } if(tex >= 0) { if(binds[p.outputbind] >= 0) postfxtexs[binds[p.outputbind]].used = -1; binds[p.outputbind] = tex; postfxtexs[tex].used = p.outputbind; if(!hasFBO) { glBindTexture(GL_TEXTURE_RECTANGLE_ARB, postfxtexs[tex].id); glCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, w, h); } } } } static bool addpostfx(const char *name, int outputbind, int outputscale, uint inputs, uint freeinputs, const vec4 ¶ms) { if(!hasTR || !*name) return false; Shader *s = useshaderbyname(name); if(!s) { conoutf(CON_ERROR, "no such postfx shader: %s", name); return false; } postfxpass &p = postfxpasses.add(); p.shader = s; p.outputbind = outputbind; p.outputscale = outputscale; p.inputs = inputs; p.freeinputs = freeinputs; p.params = params; return true; } void clearpostfx() { postfxpasses.shrink(0); cleanuppostfx(false); } COMMAND(clearpostfx, ""); ICOMMAND(addpostfx, "siisffff", (char *name, int *bind, int *scale, char *inputs, float *x, float *y, float *z, float *w), { int inputmask = inputs[0] ? 0 : 1; int freemask = inputs[0] ? 0 : 1; bool freeinputs = true; for(; *inputs; inputs++) if(isdigit(*inputs)) { inputmask |= 1<<(*inputs-'0'); if(freeinputs) freemask |= 1<<(*inputs-'0'); } else if(*inputs=='+') freeinputs = false; else if(*inputs=='-') freeinputs = true; inputmask &= (1<=maxtmus) return; tmu &t = tmus[n]; if(t.mode!=GL_MODULATE) { t.mode = GL_MODULATE; glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, t.mode); } if(t.rgb.scale != 1) { t.rgb.scale = 1; glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, t.rgb.scale); } if(t.alpha.scale != 1) { t.alpha.scale = 1; glTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, t.alpha.scale); } } void scaletmu(int n, int rgbscale, int alphascale) { if(renderpath!=R_FIXEDFUNCTION || n>=maxtmus) return; tmu &t = tmus[n]; if(rgbscale && t.rgb.scale != rgbscale) { t.rgb.scale = rgbscale; glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, t.rgb.scale); } if(alphascale && t.alpha.scale != alphascale) { t.alpha.scale = alphascale; glTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, t.alpha.scale); } } void colortmu(int n, float r, float g, float b, float a) { if(renderpath!=R_FIXEDFUNCTION || n>=maxtmus) return; tmu &t = tmus[n]; if(t.color[0] != r || t.color[1] != g || t.color[2] != b || t.color[3] != a) { t.color[0] = r; t.color[1] = g; t.color[2] = b; t.color[3] = a; glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, t.color); } } void committmufunc(GLenum mode, bool rgb, tmufunc &dst, tmufunc &src) { if(dst.combine!=src.combine) glTexEnvi(GL_TEXTURE_ENV, rgb ? GL_COMBINE_RGB_ARB : GL_COMBINE_ALPHA_ARB, src.combine); loopi(3) { if(dst.sources[i]!=src.sources[i]) glTexEnvi(GL_TEXTURE_ENV, (rgb ? GL_SOURCE0_RGB_ARB : GL_SOURCE0_ALPHA_ARB)+i, src.sources[i]); if(dst.ops[i]!=src.ops[i]) glTexEnvi(GL_TEXTURE_ENV, (rgb ? GL_OPERAND0_RGB_ARB : GL_OPERAND0_ALPHA_ARB)+i, src.ops[i]); } if(mode==GL_COMBINE4_NV) { if(dst.sources[3]!=src.sources[3]) glTexEnvi(GL_TEXTURE_ENV, rgb ? GL_SOURCE3_RGB_NV : GL_SOURCE3_ALPHA_NV, src.sources[3]); if(dst.ops[3]!=src.ops[3]) glTexEnvi(GL_TEXTURE_ENV, rgb ? GL_OPERAND3_RGB_NV : GL_OPERAND3_ALPHA_NV, src.ops[3]); } if(dst.scale!=src.scale) glTexEnvi(GL_TEXTURE_ENV, rgb ? GL_RGB_SCALE_ARB : GL_ALPHA_SCALE, src.scale); dst = src; } void setuptmu(int n, const char *rgbfunc, const char *alphafunc) { if(renderpath!=R_FIXEDFUNCTION || n>=maxtmus) return; static tmu init = INITTMU; tmu f = tmus[n]; f.mode = GL_COMBINE_ARB; if(rgbfunc) parsetmufunc(f, f.rgb, rgbfunc); else f.rgb = init.rgb; if(alphafunc) parsetmufunc(f, f.alpha, alphafunc); else f.alpha = init.alpha; tmu &t = tmus[n]; if(t.mode!=f.mode) { t.mode = f.mode; glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, t.mode); } committmufunc(f.mode, true, t.rgb, f.rgb); committmufunc(f.mode, false, t.alpha, f.alpha); } VAR(nolights, 1, 0, 0); VAR(nowater, 1, 0, 0); VAR(nomasks, 1, 0, 0); void inittmus() { if(hasTE && hasMT) { GLint val; glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &val); maxtmus = max(1, min(MAXTMUS, int(val))); loopi(maxtmus) { glActiveTexture_(GL_TEXTURE0_ARB+i); resettmu(i); } glActiveTexture_(GL_TEXTURE0_ARB); } else if(hasTE) { maxtmus = 1; resettmu(0); } if(renderpath==R_FIXEDFUNCTION) { if(maxtmus<4) caustics = 0; if(maxtmus<2) { nolights = nowater = nomasks = 1; extern int lightmodels; lightmodels = 0; } } } void cleanupshaders() { cleanuppostfx(true); defaultshader = notextureshader = nocolorshader = foggedshader = foggednotextureshader = NULL; enumerate(shaders, Shader, s, s.cleanup()); Shader::lastshader = NULL; if(renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) { glBindProgram_(GL_VERTEX_PROGRAM_ARB, 0); glBindProgram_(GL_FRAGMENT_PROGRAM_ARB, 0); glDisable(GL_VERTEX_PROGRAM_ARB); glDisable(GL_FRAGMENT_PROGRAM_ARB); } if(renderpath==R_GLSLANG || renderpath==R_ASMGLSLANG) glUseProgramObject_(0); loopi(RESERVEDSHADERPARAMS + MAXSHADERPARAMS) { vertexparamstate[i].dirty = ShaderParamState::INVALID; pixelparamstate[i].dirty = ShaderParamState::INVALID; } tmu invalidtmu = INVALIDTMU; loopi(MAXTMUS) tmus[i] = invalidtmu; } void reloadshaders() { identflags &= ~IDF_PERSIST; loadshaders(); identflags |= IDF_PERSIST; if(renderpath==R_FIXEDFUNCTION) return; linkslotshaders(); enumerate(shaders, Shader, s, { if(!s.standard && !(s.type&(SHADER_DEFERRED|SHADER_INVALID)) && !s.variantshader) { defformatstring(info)("shader %s", s.name); renderprogress(0.0, info); if(!s.compile()) s.cleanup(true); loopi(MAXVARIANTROWS) loopvj(s.variants[i]) { Shader *v = s.variants[i][j]; if((v->reusevs && v->reusevs->type&SHADER_INVALID) || (v->reuseps && v->reuseps->type&SHADER_INVALID) || !v->compile()) v->cleanup(true); } } if(s.forced && !s.detailshader) s.fixdetailshader(); }); } void setupblurkernel(int radius, float sigma, float *weights, float *offsets) { if(radius<1 || radius>MAXBLURRADIUS) return; sigma *= 2*radius; float total = 1.0f/sigma; weights[0] = total; offsets[0] = 0; // rely on bilinear filtering to sample 2 pixels at once // transforms a*X + b*Y into (u+v)*[X*u/(u+v) + Y*(1 - u/(u+v))] loopi(radius) { float weight1 = exp(-((2*i)*(2*i)) / (2*sigma*sigma)) / sigma, weight2 = exp(-((2*i+1)*(2*i+1)) / (2*sigma*sigma)) / sigma, scale = weight1 + weight2, offset = 2*i+1 + weight2 / scale; weights[i+1] = scale; offsets[i+1] = offset; total += 2*scale; } loopi(radius+1) weights[i] /= total; for(int i = radius+1; i <= MAXBLURRADIUS; i++) weights[i] = offsets[i] = 0; } void setblurshader(int pass, int size, int radius, float *weights, float *offsets, GLenum target) { if(radius<1 || radius>MAXBLURRADIUS) return; static Shader *blurshader[7][2] = { { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL } }, *blurrectshader[7][2] = { { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL } }; Shader *&s = (target == GL_TEXTURE_RECTANGLE_ARB ? blurrectshader : blurshader)[radius-1][pass]; if(!s) { defformatstring(name)("blur%c%d%s", 'x'+pass, radius, target == GL_TEXTURE_RECTANGLE_ARB ? "rect" : ""); s = lookupshaderbyname(name); } s->set(); setlocalparamfv("weights", SHPARAM_PIXEL, 0, weights); setlocalparamfv("weights2", SHPARAM_PIXEL, 2, &weights[4]); setlocalparamf("offsets", SHPARAM_VERTEX, 1, pass==0 ? offsets[1]/size : offsets[0]/size, pass==1 ? offsets[1]/size : offsets[0]/size, (offsets[2] - offsets[1])/size, (offsets[3] - offsets[2])/size); loopk(4) { static const char *names[4] = { "offset4", "offset5", "offset6", "offset7" }; setlocalparamf(names[k], SHPARAM_PIXEL, 3+k, pass==0 ? offsets[4+k]/size : offsets[0]/size, pass==1 ? offsets[4+k]/size : offsets[0]/size, 0, 0); } } sandboxgamemaker-2.7.1+dfsg/src/engine/bih.cpp0000664000175000017500000002505611642642476021200 0ustar showardshoward#include "engine.h" bool BIH::triintersect(tri &t, const vec &o, const vec &ray, float maxdist, float &dist, int mode, tri *noclip) { vec p; p.cross(ray, t.c); float det = t.b.dot(p); if(det == 0) return false; vec r(o); r.sub(t.a); float u = r.dot(p) / det; if(u < 0 || u > 1) return false; vec q; q.cross(r, t.b); float v = ray.dot(q) / det; if(v < 0 || u + v > 1) return false; float f = t.c.dot(q) / det; if(f < 0 || f > maxdist) return false; if(!(mode&RAY_SHADOW) && &t >= noclip) return false; if(t.tex && (mode&RAY_ALPHAPOLY)==RAY_ALPHAPOLY && (t.tex->alphamask || (lightmapping <= 1 && (loadalphamask(t.tex), t.tex->alphamask)))) { int si = clamp(int(t.tex->xs * (t.tc[0] + u*(t.tc[2] - t.tc[0]) + v*(t.tc[4] - t.tc[0]))), 0, t.tex->xs-1), ti = clamp(int(t.tex->ys * (t.tc[1] + u*(t.tc[3] - t.tc[1]) + v*(t.tc[5] - t.tc[1]))), 0, t.tex->ys-1); if(!(t.tex->alphamask[ti*((t.tex->xs+7)/8) + si/8] & (1<<(si%8)))) return false; } dist = f; return true; } struct BIHStack { BIHNode *node; float tmin, tmax; }; inline bool BIH::traverse(const vec &o, const vec &ray, const vec &invray, float maxdist, float &dist, int mode, BIHNode *curnode, float tmin, float tmax) { BIHStack stack[128]; int stacksize = 0; ivec order(ray.x>0 ? 0 : 1, ray.y>0 ? 0 : 1, ray.z>0 ? 0 : 1); for(;;) { int axis = curnode->axis(); int nearidx = order[axis], faridx = nearidx^1; float nearsplit = (curnode->split[nearidx] - o[axis])*invray[axis], farsplit = (curnode->split[faridx] - o[axis])*invray[axis]; if(nearsplit <= tmin) { if(farsplit < tmax) { if(!curnode->isleaf(faridx)) { curnode = &nodes[curnode->childindex(faridx)]; tmin = max(tmin, farsplit); continue; } else if(triintersect(tris[curnode->childindex(faridx)], o, ray, maxdist, dist, mode, noclip)) return true; } } else if(curnode->isleaf(nearidx)) { if(triintersect(tris[curnode->childindex(nearidx)], o, ray, maxdist, dist, mode, noclip)) return true; if(farsplit < tmax) { if(!curnode->isleaf(faridx)) { curnode = &nodes[curnode->childindex(faridx)]; tmin = max(tmin, farsplit); continue; } else if(triintersect(tris[curnode->childindex(faridx)], o, ray, maxdist, dist, mode, noclip)) return true; } } else { if(farsplit < tmax) { if(!curnode->isleaf(faridx)) { if(stacksize < int(sizeof(stack)/sizeof(stack[0]))) { BIHStack &save = stack[stacksize++]; save.node = &nodes[curnode->childindex(faridx)]; save.tmin = max(tmin, farsplit); save.tmax = tmax; } else { if(traverse(o, ray, invray, maxdist, dist, mode, &nodes[curnode->childindex(nearidx)], tmin, min(tmax, nearsplit))) return true; curnode = &nodes[curnode->childindex(faridx)]; tmin = min(tmin, farsplit); tmax = tmax; continue; } } else if(triintersect(tris[curnode->childindex(faridx)], o, ray, maxdist, dist, mode, noclip)) return true; } curnode = &nodes[curnode->childindex(nearidx)]; tmax = min(tmax, nearsplit); continue; } if(stacksize <= 0) return false; BIHStack &restore = stack[--stacksize]; curnode = restore.node; tmin = restore.tmin; tmax = restore.tmax; } } inline bool BIH::traverse(const vec &o, const vec &ray, float maxdist, float &dist, int mode) { if(!numnodes) return false; vec invray(ray.x ? 1/ray.x : 1e16f, ray.y ? 1/ray.y : 1e16f, ray.z ? 1/ray.z : 1e16f); float tmin, tmax; float t1 = (bbmin.x - o.x)*invray.x, t2 = (bbmax.x - o.x)*invray.x; if(invray.x > 0) { tmin = t1; tmax = t2; } else { tmin = t2; tmax = t1; } t1 = (bbmin.y - o.y)*invray.y; t2 = (bbmax.y - o.y)*invray.y; if(invray.y > 0) { tmin = max(tmin, t1); tmax = min(tmax, t2); } else { tmin = max(tmin, t2); tmax = min(tmax, t1); } t1 = (bbmin.z - o.z)*invray.z; t2 = (bbmax.z - o.z)*invray.z; if(invray.z > 0) { tmin = max(tmin, t1); tmax = min(tmax, t2); } else { tmin = max(tmin, t2); tmax = min(tmax, t1); } if(tmin >= maxdist || tmin>=tmax) return false; tmax = min(tmax, maxdist); return BIH::traverse(o, ray, invray, maxdist, dist, mode, &nodes[0], tmin, tmax); } void BIH::build(vector &buildnodes, ushort *indices, int numindices, const vec &vmin, const vec &vmax, int depth) { maxdepth = max(maxdepth, depth); int axis = 2; loopk(2) if(vmax[k] - vmin[k] > vmax[axis] - vmin[axis]) axis = k; vec leftmin, leftmax, rightmin, rightmax; float splitleft, splitright; int left, right; loopk(3) { leftmin = rightmin = vec(1e16f, 1e16f, 1e16f); leftmax = rightmax = vec(-1e16f, -1e16f, -1e16f); float split = 0.5f*(vmax[axis] + vmin[axis]); for(left = 0, right = numindices, splitleft = SHRT_MIN, splitright = SHRT_MAX; left < right;) { tri &tri = tris[indices[left]]; float amin = min(tri.a[axis], min(tri.b[axis], tri.c[axis])), amax = max(tri.a[axis], max(tri.b[axis], tri.c[axis])); if(max(split - amin, 0.0f) > max(amax - split, 0.0f)) { ++left; splitleft = max(splitleft, amax); leftmin.min(tri.a).min(tri.b).min(tri.c); leftmax.max(tri.a).max(tri.b).max(tri.c); } else { --right; swap(indices[left], indices[right]); splitright = min(splitright, amin); rightmin.min(tri.a).min(tri.b).min(tri.c); rightmax.max(tri.a).max(tri.b).max(tri.c); } } if(left > 0 && right < numindices) break; axis = (axis+1)%3; } if(!left || right==numindices) { leftmin = rightmin = vec(1e16f, 1e16f, 1e16f); leftmax = rightmax = vec(-1e16f, -1e16f, -1e16f); left = right = numindices/2; splitleft = SHRT_MIN; splitright = SHRT_MAX; loopi(numindices) { tri &tri = tris[indices[i]]; if(i < left) { splitleft = max(splitleft, max(tri.a[axis], max(tri.b[axis], tri.c[axis]))); leftmin.min(tri.a).min(tri.b).min(tri.c); leftmax.max(tri.a).max(tri.b).max(tri.c); } else { splitright = min(splitright, min(tri.a[axis], min(tri.b[axis], tri.c[axis]))); rightmin.min(tri.a).min(tri.b).min(tri.c); rightmax.max(tri.a).max(tri.b).max(tri.c); } } } int node = buildnodes.length(); buildnodes.add(); buildnodes[node].split[0] = short(ceil(splitleft)); buildnodes[node].split[1] = short(floor(splitright)); if(left==1) buildnodes[node].child[0] = (axis<<14) | indices[0]; else { buildnodes[node].child[0] = (axis<<14) | buildnodes.length(); build(buildnodes, indices, left, leftmin, leftmax, depth+1); } if(numindices-right==1) buildnodes[node].child[1] = (1<<15) | (left==1 ? 1<<14 : 0) | indices[right]; else { buildnodes[node].child[1] = (left==1 ? 1<<14 : 0) | buildnodes.length(); build(buildnodes, &indices[right], numindices-right, rightmin, rightmax, depth+1); } } BIH::BIH(vector *t) : maxdepth(0), numnodes(0), nodes(NULL), numtris(0), tris(NULL), noclip(NULL), bbmin(1e16f, 1e16f, 1e16f), bbmax(-1e16f, -1e16f, -1e16f) { numtris = t[0].length() + t[1].length(); if(!numtris) return; tris = new tri[numtris]; noclip = &tris[t[0].length()]; memcpy(tris, t[0].getbuf(), t[0].length()*sizeof(tri)); memcpy(noclip, t[1].getbuf(), t[1].length()*sizeof(tri)); loopi(numtris) { tri &tri = tris[i]; bbmin.min(tri.a).min(tri.b).min(tri.c); bbmax.max(tri.a).max(tri.b).max(tri.c); } radius = max(max(max(fabs(bbmin.x), fabs(bbmin.y)), fabs(bbmin.z)), max(max(fabs(bbmax.x), fabs(bbmax.y)), fabs(bbmax.z))); radius *= radius; vector buildnodes; ushort *indices = new ushort[numtris]; loopi(numtris) indices[i] = i; maxdepth = 0; build(buildnodes, indices, numtris, bbmin, bbmax); delete[] indices; numnodes = buildnodes.length(); nodes = new BIHNode[numnodes]; memcpy(nodes, buildnodes.getbuf(), numnodes*sizeof(BIHNode)); // convert tri.b/tri.c to edges loopi(numtris) { tri &tri = tris[i]; tri.b.sub(tri.a); tri.c.sub(tri.a); } } bool mmintersect(const extentity &e, const vec &o, const vec &ray, float maxdist, int mode, float &dist) { extern vector mapmodels; if(!mapmodels.inrange(e.attr[1])) return false; model *m = mapmodels[e.attr[1]].m; if(!m) { m = loadmodel(NULL, e.attr[1]); if(!m) return false; } if(mode&RAY_SHADOW) { if(!m->shadow || e.flags&extentity::F_NOSHADOW) return false; } else if((mode&RAY_ENTS)!=RAY_ENTS && (!m->collide || e.flags&extentity::F_NOCOLLIDE)) return false; if(!m->bih && (lightmapping > 1 || !m->setBIH())) return false; vec mo = vec(o).sub(e.o), mray(ray); float v = mo.dot(mray), inside = m->bih->radius - mo.squaredlen(); if((inside < 0 && v > 0) || inside + v*v < 0) return false; int yaw = e.attr[0]; if(yaw != 0) { if(yaw < 0) yaw = 360 + yaw%360; else if(yaw >= 360) yaw %= 360; const vec2 &rot = sincos360[yaw]; mo.rotate_around_z(rot.x, -rot.y); mray.rotate_around_z(rot.x, -rot.y); } return m->bih->traverse(mo, mray, maxdist ? maxdist : 1e16f, dist, mode); } sandboxgamemaker-2.7.1+dfsg/src/engine/lightning.h0000664000175000017500000000762511400572336022055 0ustar showardshoward#define MAXLIGHTNINGSTEPS 64 #define LIGHTNINGSTEP 8 int lnjitterx[2][MAXLIGHTNINGSTEPS], lnjittery[2][MAXLIGHTNINGSTEPS]; int lnjitterframe = 0, lastlnjitter = 0; VARR(lnjittermillis, 0, 100, 1000); VARR(lnjitterradius, 0, 4, 100); FVAR(lnjitterscale, 0, 0.5f, 10); VAR(lnscrollmillis, 1, 300, 5000); FVAR(lnscrollscale, 0, 0.125f, 10); FVAR(lnblendpower, 0, 0.25f, 1000); static void calclightningjitter(int frame) { loopi(MAXLIGHTNINGSTEPS) { lnjitterx[lnjitterframe][i] = -lnjitterradius + rnd(2*lnjitterradius + 1); lnjittery[lnjitterframe][i] = -lnjitterradius + rnd(2*lnjitterradius + 1); } } static void setuplightning() { if(!lastlnjitter || lastmillis-lastlnjitter > lnjittermillis) { if(!lastlnjitter) calclightningjitter(lnjitterframe); lastlnjitter = lastmillis - (lastmillis%lnjittermillis); calclightningjitter(lnjitterframe ^= 1); } } static void renderlightning(Texture *tex, const vec &o, const vec &d, float sz) { vec step(d); step.sub(o); float len = step.magnitude(); int numsteps = clamp(int(ceil(len/LIGHTNINGSTEP)), 2, MAXLIGHTNINGSTEPS); step.div(numsteps+1); int jitteroffset = detrnd(int(d.x+d.y+d.z), MAXLIGHTNINGSTEPS); vec cur(o), up, right; up.orthogonal(step); up.normalize(); right.cross(up, step); right.normalize(); float scroll = -float(lastmillis%lnscrollmillis)/lnscrollmillis, scrollscale = lnscrollscale*(LIGHTNINGSTEP*tex->ys)/(sz*tex->xs), blend = pow(clamp(float(lastmillis - lastlnjitter)/lnjittermillis, 0.0f, 1.0f), lnblendpower), jitter0 = (1-blend)*lnjitterscale*sz/lnjitterradius, jitter1 = blend*lnjitterscale*sz/lnjitterradius; glBegin(GL_TRIANGLE_STRIP); loopj(numsteps) { vec next(cur); next.add(step); if(j+1==numsteps) next = d; else { int lj = (j+jitteroffset)%MAXLIGHTNINGSTEPS; next.add(vec(right).mul((jitter1*lnjitterx[lnjitterframe][lj] + jitter0*lnjitterx[lnjitterframe^1][lj]))); next.add(vec(up).mul((jitter1*lnjittery[lnjitterframe][lj] + jitter0*lnjittery[lnjitterframe^1][lj]))); } vec dir1 = next, dir2 = next, across; dir1.sub(cur); dir2.sub(camera1->o); across.cross(dir2, dir1).normalize().mul(sz); glTexCoord2f(scroll, 1); glVertex3f(cur.x-across.x, cur.y-across.y, cur.z-across.z); glTexCoord2f(scroll, 0); glVertex3f(cur.x+across.x, cur.y+across.y, cur.z+across.z); scroll += scrollscale; if(j+1==numsteps) { glTexCoord2f(scroll, 1); glVertex3f(next.x-across.x, next.y-across.y, next.z-across.z); glTexCoord2f(scroll, 0); glVertex3f(next.x+across.x, next.y+across.y, next.z+across.z); } cur = next; } glEnd(); } struct lightningrenderer : listrenderer { lightningrenderer() : listrenderer("packages/particles/lightning", 2, PT_LIGHTNING|PT_TRACK|PT_GLARE) {} void startrender() { glDisable(GL_CULL_FACE); } void endrender() { glEnable(GL_CULL_FACE); } void update() { setuplightning(); } void seedemitter(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int gravity) { pe.maxfade = max(pe.maxfade, fade); pe.extendbb(o, size); pe.extendbb(d, size); } void renderpart(listparticle *p, const vec &o, const vec &d, int blend, int ts, uchar *color) { blend = min(blend<<2, 255); if(type&PT_MOD) //multiply alpha into color glColor3ub((color[0]*blend)>>8, (color[1]*blend)>>8, (color[2]*blend)>>8); else glColor4ub(color[0], color[1], color[2], blend); renderlightning(tex, o, d, p->size); } }; static lightningrenderer lightnings; sandboxgamemaker-2.7.1+dfsg/src/engine/varray.h0000664000175000017500000001620611425020070021357 0ustar showardshowardnamespace varray { #ifndef VARRAY_INTERNAL enum { ATTRIB_VERTEX = 1<<0, ATTRIB_COLOR = 1<<1, ATTRIB_NORMAL = 1<<2, ATTRIB_TEXCOORD0 = 1<<3, ATTRIB_TEXCOORD1 = 1<<4, MAXATTRIBS = 5 }; extern vector data; extern void enable(); extern void begin(GLenum mode); extern void defattrib(int type, int size, GLenum format); template static inline void attrib(T x) { T *buf = (T *)data.pad(sizeof(T)); buf[0] = x; } template static inline void attrib(T x, T y) { T *buf = (T *)data.pad(2*sizeof(T)); buf[0] = x; buf[1] = y; } template static inline void attrib(T x, T y, T z) { T *buf = (T *)data.pad(3*sizeof(T)); buf[0] = x; buf[1] = y; buf[2] = z; } template static inline void attrib(T x, T y, T z, T w) { T *buf = (T *)data.pad(4*sizeof(T)); buf[0] = x; buf[1] = y; buf[2] = z; buf[3] = w; } template static inline void attribv(const T *v) { data.put((const uchar *)v, N*sizeof(T)); } extern int end(); extern void disable(); #else struct attribinfo { int type, size, formatsize; GLenum format; attribinfo() : type(0), size(0), formatsize(0), format(GL_FALSE) {} bool operator==(const attribinfo &a) const { return type == a.type && size == a.size && format == a.format; } bool operator!=(const attribinfo &a) const { return type != a.type || size != a.size || format != a.format; } }; vector data; static attribinfo attribs[MAXATTRIBS], lastattribs[MAXATTRIBS]; static int enabled = 0, numattribs = 0, attribmask = 0, numlastattribs = 0, lastattribmask = 0, vertexsize = 0; static GLenum primtype = GL_TRIANGLES; static uchar *lastbuf = NULL; static bool changedattribs = false; void enable() { enabled = 0; numlastattribs = lastattribmask = 0; lastbuf = NULL; } void begin(GLenum mode) { primtype = mode; } void defattrib(int type, int size, GLenum format) { if(type == ATTRIB_VERTEX) { numattribs = 0; vertexsize = 0; } changedattribs = true; attribmask |= type; attribinfo &a = attribs[numattribs++]; a.type = type; a.size = size; a.format = format; switch(format) { case GL_UNSIGNED_BYTE: a.formatsize = 1; break; case GL_BYTE: a.formatsize = 1; break; case GL_UNSIGNED_SHORT: a.formatsize = 2; break; case GL_SHORT: a.formatsize = 2; break; case GL_UNSIGNED_INT: a.formatsize = 4; break; case GL_INT: a.formatsize = 4; break; case GL_FLOAT: a.formatsize = 4; break; case GL_DOUBLE: a.formatsize = 8; break; default: a.formatsize = 0; break; } a.formatsize *= size; vertexsize += a.formatsize; } static inline void setattrib(const attribinfo &a, uchar *buf) { switch(a.type) { case ATTRIB_VERTEX: if(!(enabled&a.type)) glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(a.size, a.format, vertexsize, buf); break; case ATTRIB_COLOR: if(!(enabled&a.type)) glEnableClientState(GL_COLOR_ARRAY); glColorPointer(a.size, a.format, vertexsize, buf); break; case ATTRIB_NORMAL: if(!(enabled&a.type)) glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(a.format, vertexsize, buf); break; case ATTRIB_TEXCOORD0: if(!(enabled&a.type)) glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(a.size, a.format, vertexsize, buf); break; case ATTRIB_TEXCOORD1: glClientActiveTexture_(GL_TEXTURE1_ARB); if(!(enabled&a.type)) glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(a.size, a.format, vertexsize, buf); glClientActiveTexture_(GL_TEXTURE0_ARB); break; } enabled |= a.type; } static inline void unsetattrib(const attribinfo &a) { switch(a.type) { case ATTRIB_VERTEX: glDisableClientState(GL_VERTEX_ARRAY); break; case ATTRIB_COLOR: glDisableClientState(GL_COLOR_ARRAY); break; case ATTRIB_NORMAL: glDisableClientState(GL_NORMAL_ARRAY); break; case ATTRIB_TEXCOORD0: glDisableClientState(GL_TEXTURE_COORD_ARRAY); break; case ATTRIB_TEXCOORD1: glClientActiveTexture_(GL_TEXTURE1_ARB); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glClientActiveTexture_(GL_TEXTURE0_ARB); break; } } int end() { if(data.empty()) return 0; uchar *buf = data.getbuf(); bool forceattribs = numattribs != numlastattribs || buf != lastbuf; if(forceattribs || changedattribs) { int diffmask = enabled & lastattribmask & ~attribmask; if(diffmask) loopi(numlastattribs) { const attribinfo &a = lastattribs[i]; if(diffmask & a.type) unsetattrib(a); } loopi(numattribs) { const attribinfo &a = attribs[i]; if(forceattribs || a != lastattribs[i]) { setattrib(a, buf); lastattribs[i] = a; } buf += a.formatsize; } lastbuf = buf; numlastattribs = numattribs; lastattribmask = attribmask; changedattribs = false; } int numvertexes = data.length()/vertexsize; glDrawArrays(primtype, 0, numvertexes); data.setsize(0); return numvertexes; } void disable() { if(!enabled) return; if(enabled&ATTRIB_VERTEX) glDisableClientState(GL_VERTEX_ARRAY); if(enabled&ATTRIB_COLOR) glDisableClientState(GL_COLOR_ARRAY); if(enabled&ATTRIB_NORMAL) glDisableClientState(GL_NORMAL_ARRAY); if(enabled&ATTRIB_TEXCOORD0) glDisableClientState(GL_TEXTURE_COORD_ARRAY); if(enabled&ATTRIB_TEXCOORD1) { glClientActiveTexture_(GL_TEXTURE1_ARB); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glClientActiveTexture_(GL_TEXTURE0_ARB); } enabled = 0; } #endif } sandboxgamemaker-2.7.1+dfsg/src/engine/lightmap.h0000664000175000017500000000723511642642476021707 0ustar showardshoward#define LM_MINW 2 #define LM_MINH 2 #define LM_MAXW 128 #define LM_MAXH 128 #define LM_PACKW 512 #define LM_PACKH 512 struct PackNode { PackNode *child1, *child2; ushort x, y, w, h; int available; PackNode() : child1(0), child2(0), x(0), y(0), w(LM_PACKW), h(LM_PACKH), available(min(LM_PACKW, LM_PACKH)) {} PackNode(ushort x, ushort y, ushort w, ushort h) : child1(0), child2(0), x(x), y(y), w(w), h(h), available(min(w, h)) {} void clear() { DELETEP(child1); DELETEP(child2); } ~PackNode() { clear(); } bool insert(ushort &tx, ushort &ty, ushort tw, ushort th); }; enum { LM_DIFFUSE = 0, LM_BUMPMAP0, LM_BUMPMAP1, LM_TYPE = 0x0F, LM_ALPHA = 1<<4, LM_FLAGS = 0xF0 }; struct LightMap { int type, bpp, tex, offsetx, offsety; PackNode packroot; uint lightmaps, lumels; int unlitx, unlity; uchar *data; LightMap() : type(LM_DIFFUSE), bpp(3), tex(-1), offsetx(-1), offsety(-1), lightmaps(0), lumels(0), unlitx(-1), unlity(-1), data(NULL) { } ~LightMap() { if(data) delete[] data; } void finalize() { packroot.clear(); packroot.available = 0; } void copy(ushort tx, ushort ty, uchar *src, ushort tw, ushort th); bool insert(ushort &tx, ushort &ty, uchar *src, ushort tw, ushort th); }; extern vector lightmaps; struct LightMapTexture { int w, h, type; GLuint id; int unlitx, unlity; LightMapTexture() : w(0), h(0), type(LM_DIFFUSE), id(0), unlitx(-1), unlity(-1) {} }; extern vector lightmaptexs; extern bvec ambientcolor, skylightcolor; extern void clearlights(); extern void initlights(); extern void clearlightcache(int e = -1); extern void resetlightmaps(bool fullclean = true); extern void brightencube(cube &c); extern void setsurfaces(cube &c, const surfaceinfo *surfs, const vertinfo *verts, int numverts); extern void setsurface(cube &c, int orient, const surfaceinfo &surf, const vertinfo *verts, int numverts); extern void previewblends(const ivec &bo, const ivec &bs); struct lerpvert { vec normal; float u, v; bool operator==(const lerpvert &l) const { return u == l.u && v == l.v; } bool operator!=(const lerpvert &l) const { return u != l.u || v != l.v; } }; struct lerpbounds { const lerpvert *min; const lerpvert *max; float u, ustep; vec normal, nstep; int winding; }; extern void calcnormals(bool lerptjoints = false); extern void clearnormals(); extern void findnormal(const vec &key, const vec &surface, vec &v); extern void calclerpverts(const vec2 *c, const vec *n, lerpvert *lv, int &numv); extern void initlerpbounds(const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end); extern void lerpnormal(float v, const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end, vec &normal, vec &nstep); #define CHECK_CALCLIGHT_PROGRESS_LOCKED(exit, show_calclight_progress, before, after) \ if(check_calclight_progress) \ { \ if(!calclight_canceled) \ { \ before; \ show_calclight_progress(); \ check_calclight_canceled(); \ after; \ } \ if(calclight_canceled) { exit; } \ } #define CHECK_CALCLIGHT_PROGRESS(exit, show_calclight_progress) CHECK_CALCLIGHT_PROGRESS_LOCKED(exit, show_calclight_progress, , ) extern bool calclight_canceled; extern volatile bool check_calclight_progress; extern void check_calclight_canceled(); extern int lightmapping; sandboxgamemaker-2.7.1+dfsg/src/engine/console.cpp0000664000175000017500000005621411615526106022067 0ustar showardshoward// console.cpp: the console buffer, its display, and command line control #include "engine.h" struct cline { char *line; int type, outtime; }; vector conlines; int commandmillis = -1; string commandbuf; char *commandaction = NULL, *commandprompt = NULL; int commandpos = -1; VARFP(maxcon, 10, 200, 1000, { while(conlines.length() > maxcon) delete[] conlines.pop().line; }); #define CONSTRLEN 512 void conline(int type, const char *sf) // add a line to the console buffer { cline cl; cl.line = conlines.length()>maxcon ? conlines.pop().line : newstring("", CONSTRLEN-1); // constrain the buffer size cl.type = type; cl.outtime = totalmillis; // for how long to keep line on screen conlines.insert(0, cl); copystring(cl.line, sf, CONSTRLEN); } void conoutfv(int type, const char *fmt, va_list args) { static char buf[CONSTRLEN]; vformatstring(buf, fmt, args, sizeof(buf)); conline(type, buf); filtertext(buf, buf); logoutf("%s", buf); } void conoutf(const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(CON_INFO, fmt, args); va_end(args); } void conoutf(int type, const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(type, fmt, args); va_end(args); } VAR(fullconsole, 0, 0, 1); ICOMMAND(toggleconsole, "", (), { fullconsole ^= 1; }); int rendercommand(int x, int y, int w) { if(commandmillis < 0) return 0; defformatstring(s)("%s %s", commandprompt ? commandprompt : ">", commandbuf); int width, height; text_bounds(s, width, height, w); y -= height; draw_text(s, x, y, 0xFF, 0xFF, 0xFF, 0xFF, (commandpos>=0) ? (commandpos+1+(commandprompt?strlen(commandprompt):1)) : strlen(s), w); return height; } VARP(consize, 0, 5, 100); VARP(miniconsize, 0, 5, 100); VARP(miniconwidth, 0, 40, 100); VARP(confade, 0, 30, 60); VARP(miniconfade, 0, 30, 60); VARP(fullconsize, 0, 75, 100); HVARP(confilter, 0, 0x7FFFFFF, 0x7FFFFFF); HVARP(fullconfilter, 0, 0x7FFFFFF, 0x7FFFFFF); HVARP(miniconfilter, 0, 0, 0x7FFFFFF); int conskip = 0, miniconskip = 0; void setconskip(int &skip, int filter, int n) { int offset = abs(n), dir = n < 0 ? -1 : 1; skip = clamp(skip, 0, conlines.length()-1); while(offset) { skip += dir; if(!conlines.inrange(skip)) { skip = clamp(skip, 0, conlines.length()-1); return; } if(conlines[skip].type&filter) --offset; } } ICOMMAND(conskip, "i", (int *n), setconskip(conskip, fullconsole ? fullconfilter : confilter, *n)); ICOMMAND(miniconskip, "i", (int *n), setconskip(miniconskip, miniconfilter, *n)); ICOMMAND(clearconsole, "", (), { while(conlines.length()) delete[] conlines.pop().line; }); int drawconlines(int conskip, int confade, int conwidth, int conheight, int conoff, int filter, int y = 0, int dir = 1) { int numl = conlines.length(), offset = min(conskip, numl); if(confade) { if(!conskip) { numl = 0; loopvrev(conlines) if(totalmillis-conlines[i].outtime < confade*1000) { numl = i+1; break; } } else offset--; } int totalheight = 0; loopi(numl) //determine visible height { // shuffle backwards to fill if necessary int idx = offset+i < numl ? offset+i : --offset; if(!(conlines[idx].type&filter)) continue; char *line = conlines[idx].line; int width, height; text_bounds(line, width, height, conwidth); if(totalheight + height > conheight) { numl = i; if(offset == idx) ++offset; break; } totalheight += height; } if(dir > 0) y = conoff; loopi(numl) { int idx = offset + (dir > 0 ? numl-i-1 : i); if(!(conlines[idx].type&filter)) continue; char *line = conlines[idx].line; int width, height; text_bounds(line, width, height, conwidth); if(dir <= 0) y -= height; draw_text(line, conoff, y, 0xFF, 0xFF, 0xFF, 0xFF, -1, conwidth); if(dir > 0) y += height; } return y+conoff; } int renderconsole(int w, int h, int abovehud) // render buffer taking into account time & scrolling { int conpad = fullconsole ? 0 : FONTH/4, conoff = fullconsole ? FONTH : FONTH/3, conheight = min(fullconsole ? ((h*fullconsize/100)/FONTH)*FONTH : FONTH*consize, h - 2*(conpad + conoff)), conwidth = w - 2*(conpad + conoff) - (fullconsole ? 0 : game::clipconsole(w, h)); extern void consolebox(int x1, int y1, int x2, int y2); if(fullconsole) consolebox(conpad, conpad, conwidth+conpad+2*conoff, conheight+conpad+2*conoff); int y = drawconlines(conskip, fullconsole ? 0 : confade, conwidth, conheight, conpad+conoff, fullconsole ? fullconfilter : confilter); if(!fullconsole && (miniconsize && miniconwidth)) drawconlines(miniconskip, miniconfade, (miniconwidth*(w - 2*(conpad + conoff)))/100, min(FONTH*miniconsize, abovehud - y), conpad+conoff, miniconfilter, abovehud, -1); return fullconsole ? conheight + 2*(conpad + conoff) : y; } // keymap is defined externally in keymap.cfg struct keym { enum { ACTION_DEFAULT = 0, ACTION_SPECTATOR, ACTION_EDITING, NUMACTIONS }; int code; char *name; char *actions[NUMACTIONS]; bool pressed; keym() : code(-1), name(NULL), pressed(false) { loopi(NUMACTIONS) actions[i] = newstring(""); } ~keym() { DELETEA(name); loopi(NUMACTIONS) DELETEA(actions[i]); } }; hashtable keyms(128); void keymap(int *code, char *key) { if(identflags&IDF_OVERRIDDEN) { conoutf(CON_ERROR, "cannot override keymap %s", code); return; } keym &km = keyms[*code]; km.code = *code; DELETEA(km.name); km.name = newstring(key); } COMMAND(keymap, "is"); keym *keypressed = NULL; char *keyaction = NULL; const char *getkeyname(int code) { keym *km = keyms.access(code); return km ? km->name : NULL; } void searchbinds(char *action, int type) { vector names; enumerate(keyms, keym, km, { if(!strcmp(km.actions[type], action)) { if(names.length()) names.add(' '); names.put(km.name, strlen(km.name)); } }); names.add('\0'); result(names.getbuf()); } keym *findbind(char *key) { enumerate(keyms, keym, km, { if(!strcasecmp(km.name, key)) return &km; }); return NULL; } void getbind(char *key, int type) { keym *km = findbind(key); result(km ? km->actions[type] : ""); } void bindkey(char *key, char *action, int state, const char *cmd) { if(identflags&IDF_OVERRIDDEN) { conoutf(CON_ERROR, "cannot override %s \"%s\"", cmd, key); return; } keym *km = findbind(key); if(!km) { conoutf(CON_ERROR, "unknown key \"%s\"", key); return; } char *&binding = km->actions[state]; if(!keypressed || keyaction!=binding) delete[] binding; // trim white-space to make searchbinds more reliable while(isspace(*action)) action++; int len = strlen(action); while(len>0 && isspace(action[len-1])) len--; binding = newstring(action, len); } ICOMMAND(bind, "ss", (char *key, char *action), bindkey(key, action, keym::ACTION_DEFAULT, "bind")); ICOMMAND(specbind, "ss", (char *key, char *action), bindkey(key, action, keym::ACTION_SPECTATOR, "specbind")); ICOMMAND(editbind, "ss", (char *key, char *action), bindkey(key, action, keym::ACTION_EDITING, "editbind")); ICOMMAND(getbind, "s", (char *key), getbind(key, keym::ACTION_DEFAULT)); ICOMMAND(getspecbind, "s", (char *key), getbind(key, keym::ACTION_SPECTATOR)); ICOMMAND(geteditbind, "s", (char *key), getbind(key, keym::ACTION_EDITING)); ICOMMAND(searchbinds, "s", (char *action), searchbinds(action, keym::ACTION_DEFAULT)); ICOMMAND(searchspecbinds, "s", (char *action), searchbinds(action, keym::ACTION_SPECTATOR)); ICOMMAND(searcheditbinds, "s", (char *action), searchbinds(action, keym::ACTION_EDITING)); void inputcommand(char *init, char *action = NULL, char *prompt = NULL) // turns input to the command line on or off { commandmillis = init ? totalmillis : -1; SDL_EnableUNICODE(commandmillis >= 0 ? 1 : 0); if(!editmode) keyrepeat(commandmillis >= 0); copystring(commandbuf, init ? init : ""); DELETEA(commandaction); DELETEA(commandprompt); commandpos = -1; if(action && action[0]) commandaction = newstring(action); if(prompt && prompt[0]) commandprompt = newstring(prompt); } ICOMMAND(saycommand, "C", (char *init), inputcommand(init)); COMMAND(inputcommand, "sss"); #if !defined(WIN32) && !defined(__APPLE__) #include #include #endif void pasteconsole() { #ifdef WIN32 if(!IsClipboardFormatAvailable(CF_TEXT)) return; if(!OpenClipboard(NULL)) return; char *cb = (char *)GlobalLock(GetClipboardData(CF_TEXT)); concatstring(commandbuf, cb); GlobalUnlock(cb); CloseClipboard(); #elif defined(__APPLE__) extern void mac_pasteconsole(char *commandbuf); mac_pasteconsole(commandbuf); #else SDL_SysWMinfo wminfo; SDL_VERSION(&wminfo.version); wminfo.subsystem = SDL_SYSWM_X11; if(!SDL_GetWMInfo(&wminfo)) return; int cbsize; char *cb = XFetchBytes(wminfo.info.x11.display, &cbsize); if(!cb || !cbsize) return; size_t commandlen = strlen(commandbuf); for(char *cbline = cb, *cbend; commandlen + 1 < sizeof(commandbuf) && cbline < &cb[cbsize]; cbline = cbend + 1) { cbend = (char *)memchr(cbline, '\0', &cb[cbsize] - cbline); if(!cbend) cbend = &cb[cbsize]; if(size_t(commandlen + cbend - cbline + 1) > sizeof(commandbuf)) cbend = cbline + sizeof(commandbuf) - commandlen - 1; memcpy(&commandbuf[commandlen], cbline, cbend - cbline); commandlen += cbend - cbline; commandbuf[commandlen] = '\n'; if(commandlen + 1 < sizeof(commandbuf) && cbend < &cb[cbsize]) ++commandlen; commandbuf[commandlen] = '\0'; } XFree(cb); #endif } struct hline { char *buf, *action, *prompt; hline() : buf(NULL), action(NULL), prompt(NULL) {} ~hline() { DELETEA(buf); DELETEA(action); DELETEA(prompt); } void restore() { copystring(commandbuf, buf); if(commandpos >= (int)strlen(commandbuf)) commandpos = -1; DELETEA(commandaction); DELETEA(commandprompt); if(action) commandaction = newstring(action); if(prompt) commandprompt = newstring(prompt); } bool shouldsave() { return strcmp(commandbuf, buf) || (commandaction ? !action || strcmp(commandaction, action) : action!=NULL) || (commandprompt ? !prompt || strcmp(commandprompt, prompt) : prompt!=NULL); } void save() { buf = newstring(commandbuf); if(commandaction) action = newstring(commandaction); if(commandprompt) prompt = newstring(commandprompt); } void run() { if(action) { alias("commandbuf", buf); execute(action); } else if(buf[0]=='/') execute(buf+1); else game::toserver(buf); } }; vector history; int histpos = 0; VARP(maxhistory, 0, 1000, 10000); void history_(int *n) { static bool inhistory = false; if(!inhistory && history.inrange(*n)) { inhistory = true; history[history.length()-*n-1]->run(); inhistory = false; } } COMMANDN(history, history_, "i"); struct releaseaction { keym *key; char *action; }; vector releaseactions; const char *addreleaseaction(char *s) { if(!keypressed) return NULL; releaseaction &ra = releaseactions.add(); ra.key = keypressed; ra.action = s; return keypressed->name; } void onrelease(const char *s) { addreleaseaction(newstring(s)); } COMMAND(onrelease, "s"); void execbind(keym &k, bool isdown) { loopv(releaseactions) { releaseaction &ra = releaseactions[i]; if(ra.key==&k) { if(!isdown) execute(ra.action); delete[] ra.action; releaseactions.remove(i--); } } if(isdown) { int state = keym::ACTION_DEFAULT; #ifndef NEWGUI if(!mainmenu) #else if(!UI::mainmenu) #endif { if(editmode) state = keym::ACTION_EDITING; else if(player->state==CS_SPECTATOR) state = keym::ACTION_SPECTATOR; } char *&action = k.actions[state][0] ? k.actions[state] : k.actions[keym::ACTION_DEFAULT]; keyaction = action; keypressed = &k; execute(keyaction); keypressed = NULL; if(keyaction!=action) delete[] keyaction; } k.pressed = isdown; } void consolekey(int code, bool isdown, int cooked) { #ifdef __APPLE__ #define MOD_KEYS (KMOD_LMETA|KMOD_RMETA) #else #define MOD_KEYS (KMOD_LCTRL|KMOD_RCTRL) #endif if(isdown) { switch(code) { case SDLK_RETURN: case SDLK_KP_ENTER: break; case SDLK_HOME: if(strlen(commandbuf)) commandpos = 0; break; case SDLK_END: commandpos = -1; break; case SDLK_DELETE: { int len = (int)strlen(commandbuf); if(commandpos<0) break; memmove(&commandbuf[commandpos], &commandbuf[commandpos+1], len - commandpos); resetcomplete(); if(commandpos>=len-1) commandpos = -1; break; } case SDLK_BACKSPACE: { int len = (int)strlen(commandbuf), i = commandpos>=0 ? commandpos : len; if(i<1) break; memmove(&commandbuf[i-1], &commandbuf[i], len - i + 1); resetcomplete(); if(commandpos>0) commandpos--; else if(!commandpos && len<=1) commandpos = -1; break; } case SDLK_LEFT: if(commandpos>0) commandpos--; else if(commandpos<0) commandpos = (int)strlen(commandbuf)-1; break; case SDLK_RIGHT: if(commandpos>=0 && ++commandpos>=(int)strlen(commandbuf)) commandpos = -1; break; case SDLK_UP: if(histpos > history.length()) histpos = history.length(); if(histpos > 0) history[--histpos]->restore(); break; case SDLK_DOWN: if(histpos + 1 < history.length()) history[++histpos]->restore(); break; case SDLK_TAB: if(!commandaction) { complete(commandbuf); if(commandpos>=0 && commandpos>=(int)strlen(commandbuf)) commandpos = -1; } break; case SDLK_v: if(SDL_GetModState()&MOD_KEYS) { pasteconsole(); return; } // fall through default: resetcomplete(); if(cooked) { size_t len = (int)strlen(commandbuf); if(len+1shouldsave()) { if(maxhistory && history.length() >= maxhistory) { loopi(history.length()-maxhistory+1) delete history[i]; history.remove(0, history.length()-maxhistory+1); } history.add(h = new hline)->save(); } else h = history.last(); } histpos = history.length(); inputcommand(NULL); if(h) h->run(); } else if(code==SDLK_ESCAPE) { histpos = history.length(); inputcommand(NULL); } } } #ifndef NEWGUI extern bool menukey(int code, bool isdown, int cooked); #endif void keypress(int code, bool isdown, int cooked) { keym *haskey = keyms.access(code); if(haskey && haskey->pressed) execbind(*haskey, isdown); // allow pressed keys to release #ifdef NEWGUI else if(!UI::keypress(code, isdown, cooked)) // 3D GUI mouse button intercept #else else if(!menukey(code, isdown, cooked)) // 3D GUI mouse button intercept #endif { if(commandmillis >= 0) consolekey(code, isdown, cooked); else if(haskey) execbind(*haskey, isdown); } } void clear_console() { keyms.clear(); } static inline bool sortbinds(keym *x, keym *y) { return strcmp(x->name, y->name) < 0; } void writebinds(stream *f) { static const char *cmds[3] = { "bind", "specbind", "editbind" }; vector binds; enumerate(keyms, keym, km, binds.add(&km)); binds.sort(sortbinds); loopj(3) { loopv(binds) { keym &km = *binds[i]; if(*km.actions[j]) f->printf("%s \"%s\" [%s]\n", cmds[j], km.name, km.actions[j]); } } } // tab-completion of all idents and base maps enum { FILES_DIR = 0, FILES_LIST }; struct fileskey { int type; const char *dir, *ext; fileskey() {} fileskey(int type, const char *dir, const char *ext) : type(type), dir(dir), ext(ext) {} }; struct filesval { int type; char *dir, *ext; vector files; int millis; filesval(int type, const char *dir, const char *ext) : type(type), dir(newstring(dir)), ext(ext && ext[0] ? newstring(ext) : NULL), millis(-1) {} ~filesval() { DELETEA(dir); DELETEA(ext); files.deletearrays(); } static bool comparefiles(const char *x, const char *y) { return strcmp(x, y) < 0; } void update() { if(type!=FILES_DIR || millis >= commandmillis) return; files.deletearrays(); listfiles(dir, ext, files); files.sort(comparefiles); loopv(files) if(i && !strcmp(files[i], files[i-1])) delete[] files.remove(i--); millis = totalmillis; } }; static inline bool htcmp(const fileskey &x, const fileskey &y) { return x.type==y.type && !strcmp(x.dir, y.dir) && (x.ext == y.ext || (x.ext && y.ext && !strcmp(x.ext, y.ext))); } static inline uint hthash(const fileskey &k) { return hthash(k.dir); } static hashtable completefiles; static hashtable completions; int completesize = 0; string lastcomplete; void resetcomplete() { completesize = 0; } void addcomplete(char *command, int type, char *dir, char *ext) { if(identflags&IDF_OVERRIDDEN) { conoutf(CON_ERROR, "cannot override complete %s", command); return; } if(!dir[0]) { filesval **hasfiles = completions.access(command); if(hasfiles) *hasfiles = NULL; return; } if(type==FILES_DIR) { int dirlen = (int)strlen(dir); while(dirlen > 0 && (dir[dirlen-1] == '/' || dir[dirlen-1] == '\\')) dir[--dirlen] = '\0'; if(ext) { if(strchr(ext, '*')) ext[0] = '\0'; if(!ext[0]) ext = NULL; } } fileskey key(type, dir, ext); filesval **val = completefiles.access(key); if(!val) { filesval *f = new filesval(type, dir, ext); if(type==FILES_LIST) explodelist(dir, f->files); val = &completefiles[fileskey(type, f->dir, f->ext)]; *val = f; } filesval **hasfiles = completions.access(command); if(hasfiles) *hasfiles = *val; else completions[newstring(command)] = *val; } void addfilecomplete(char *command, char *dir, char *ext) { addcomplete(command, FILES_DIR, dir, ext); } void addlistcomplete(char *command, char *list) { addcomplete(command, FILES_LIST, list, NULL); } COMMANDN(complete, addfilecomplete, "sss"); COMMANDN(listcomplete, addlistcomplete, "ss"); void complete(char *s) { if(*s!='/') { string t; copystring(t, s); copystring(s, "/"); concatstring(s, t); } if(!s[1]) return; if(!completesize) { completesize = (int)strlen(s)-1; lastcomplete[0] = '\0'; } filesval *f = NULL; if(completesize) { char *end = strchr(s, ' '); if(end) { string command; copystring(command, s+1, min(size_t(end-s), sizeof(command))); filesval **hasfiles = completions.access(command); if(hasfiles) f = *hasfiles; } } const char *nextcomplete = NULL; string prefix; copystring(prefix, "/"); if(f) // complete using filenames { int commandsize = strchr(s, ' ')+1-s; copystring(prefix, s, min(size_t(commandsize+1), sizeof(prefix))); f->update(); loopv(f->files) { if(strncmp(f->files[i], s+commandsize, completesize+1-commandsize)==0 && strcmp(f->files[i], lastcomplete) > 0 && (!nextcomplete || strcmp(f->files[i], nextcomplete) < 0)) nextcomplete = f->files[i]; } } else // complete using command names { enumerate(idents, ident, id, if(strncmp(id.name, s+1, completesize)==0 && strcmp(id.name, lastcomplete) > 0 && (!nextcomplete || strcmp(id.name, nextcomplete) < 0)) nextcomplete = id.name; ); } if(nextcomplete) { copystring(s, prefix); concatstring(s, nextcomplete); copystring(lastcomplete, nextcomplete); } else lastcomplete[0] = '\0'; } static inline bool sortcompletions(const char *x, const char *y) { return strcmp(x, y) < 0; } void writecompletions(stream *f) { vector cmds; enumeratekt(completions, char *, k, filesval *, v, { if(v) cmds.add(k); }); cmds.sort(sortcompletions); loopv(cmds) { char *k = cmds[i]; filesval *v = completions[k]; if(v->type==FILES_LIST) f->printf("listcomplete \"%s\" [%s]\n", k, v->dir); else f->printf("complete \"%s\" \"%s\" \"%s\"\n", k, v->dir, v->ext ? v->ext : "*"); } } ICOMMAND(getgame, "", (), result(game::gameident());); sandboxgamemaker-2.7.1+dfsg/src/engine/lightmap.cpp0000664000175000017500000027452411654260372022243 0ustar showardshoward#include "engine.h" #define MAXLIGHTMAPTASKS 4096 #define LIGHTMAPBUFSIZE (2*1024*1024) struct lightmapinfo; struct lightmaptask; struct lightmapworker { uchar *buf; int bufstart, bufused; lightmapinfo *firstlightmap, *lastlightmap, *curlightmaps; cube *c; cubeext *ext; uchar *colorbuf; bvec *raybuf; uchar *ambient, *blur; vec *colordata, *raydata; int type, bpp, w, h, orient, rotate; VSlot *vslot; Slot *slot; vector lights; ShadowRayCache *shadowraycache; BlendMapCache *blendmapcache; bool needspace, doneworking; SDL_cond *spacecond; SDL_Thread *thread; lightmapworker(); ~lightmapworker(); void reset(); bool setupthread(); void cleanupthread(); static int work(void *data); }; struct lightmapinfo { lightmapinfo *next; cube *c; uchar *colorbuf; bvec *raybuf; bool packed; int type, w, h, bpp, bufsize, surface; }; struct lightmaptask { ivec o; int size, usefaces, progress; cube *c; cubeext *ext; lightmapinfo *lightmaps; lightmapworker *worker; }; struct lightmapext { cube *c; cubeext *ext; }; static vector lightmapworkers; static vector lightmaptasks[2]; static vector lightmapexts; static int packidx = 0, allocidx = 0; static SDL_mutex *lightlock = NULL, *tasklock = NULL; static SDL_cond *fullcond = NULL, *emptycond = NULL; int lightmapping = 0; vector lightmaps; VARR(lightprecision, 1, 32, 1024); VARR(lighterror, 1, 8, 16); VARR(bumperror, 1, 3, 16); VARR(lightlod, 0, 0, 10); bvec ambientcolor(0x19, 0x19, 0x19), skylightcolor(0, 0, 0); HVARFR(ambient, 1, 0x191919, 0xFFFFFF, { //if(ambient <= 255) ambient |= (ambient<<8) | (ambient<<16); ambientcolor = bvec((ambient>>16)&0xFF, (ambient>>8)&0xFF, ambient&0xFF); }); HVARFR(skylight, 0, 0, 0xFFFFFF, { //if(skylight <= 255) skylight |= (skylight<<8) | (skylight<<16); skylightcolor = bvec((skylight>>16)&0xFF, (skylight>>8)&0xFF, skylight&0xFF); }); extern void setupsunlight(); bvec sunlightcolor(0, 0, 0); HVARFR(sunlight, 0, 0, 0xFFFFFF, { //if(sunlight <= 255) sunlight |= (sunlight<<8) | (sunlight<<16); sunlightcolor = bvec((sunlight>>16)&0xFF, (sunlight>>8)&0xFF, sunlight&0xFF); setupsunlight(); }); FVARFR(sunlightscale, 0, 1, 16, setupsunlight()); vec sunlightdir(0, 0, 1); extern void setsunlightdir(); VARFR(sunlightyaw, 0, 0, 360, setsunlightdir()); VARFR(sunlightpitch, -90, 90, 90, setsunlightdir()); void setsunlightdir() { sunlightdir = vec(sunlightyaw*RAD, sunlightpitch*RAD); loopk(3) if(fabs(sunlightdir[k]) < 1e-5f) sunlightdir[k] = 0; sunlightdir.normalize(); setupsunlight(); } entity sunlightent; void setupsunlight() { sunlightent.attr.setsize(0); sunlightent.type = ET_LIGHT; sunlightent.attr.add(0); //0 sunlightent.attr.add(sunlightcolor.x*sunlightscale); //1 sunlightent.attr.add(sunlightcolor.y*sunlightscale); //2 sunlightent.attr.add(sunlightcolor.z*sunlightscale); //3 float dist = min(min(sunlightdir.x ? 1/fabs(sunlightdir.x) : 1e16f, sunlightdir.y ? 1/fabs(sunlightdir.y) : 1e16f), sunlightdir.z ? 1/fabs(sunlightdir.z) : 1e16f); sunlightent.o = vec(sunlightdir).mul(dist*worldsize).add(vec(worldsize/2, worldsize/2, worldsize/2)); } VARR(skytexturelight, 0, 1, 1); static const surfaceinfo brightsurfaces[6] = { brightsurface, brightsurface, brightsurface, brightsurface, brightsurface, brightsurface }; void brightencube(cube &c) { if(!c.ext) newcubeext(c, 0, false); memcpy(c.ext->surfaces, brightsurfaces, sizeof(brightsurfaces)); } void setsurfaces(cube &c, const surfaceinfo *surfs, const vertinfo *verts, int numverts) { if(!c.ext || c.ext->maxverts < numverts) newcubeext(c, numverts, false); memcpy(c.ext->surfaces, surfs, sizeof(c.ext->surfaces)); memcpy(c.ext->verts(), verts, numverts*sizeof(vertinfo)); } void setsurface(cube &c, int orient, const surfaceinfo &src, const vertinfo *srcverts, int numsrcverts) { int dstoffset = 0; if(!c.ext) newcubeext(c, numsrcverts, true); else { int numbefore = 0, beforeoffset = 0; loopi(orient) { surfaceinfo &surf = c.ext->surfaces[i]; int numverts = surf.totalverts(); if(!numverts) continue; numbefore += numverts; beforeoffset = surf.verts + numverts; } int numafter = 0, afteroffset = c.ext->maxverts; for(int i = 5; i > orient; i--) { surfaceinfo &surf = c.ext->surfaces[i]; int numverts = surf.totalverts(); if(!numverts) continue; numafter += numverts; afteroffset = surf.verts; } if(afteroffset - beforeoffset >= numsrcverts) dstoffset = beforeoffset; else { cubeext *ext = c.ext; if(numbefore + numsrcverts + numafter > c.ext->maxverts) { ext = growcubeext(c.ext, numbefore + numsrcverts + numafter); memcpy(ext->surfaces, c.ext->surfaces, sizeof(ext->surfaces)); } int offset = 0; if(numbefore == beforeoffset) { if(numbefore && c.ext != ext) memcpy(ext->verts(), c.ext->verts(), numbefore*sizeof(vertinfo)); offset = numbefore; } else loopi(orient) { surfaceinfo &surf = ext->surfaces[i]; int numverts = surf.totalverts(); if(!numverts) continue; memmove(ext->verts() + offset, c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)); surf.verts = offset; offset += numverts; } dstoffset = offset; offset += numsrcverts; if(numafter && offset > afteroffset) { offset += numafter; for(int i = 5; i > orient; i--) { surfaceinfo &surf = ext->surfaces[i]; int numverts = surf.totalverts(); if(!numverts) continue; offset -= numverts; memmove(ext->verts() + offset, c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)); surf.verts = offset; } } if(c.ext != ext) setcubeext(c, ext); } } surfaceinfo &dst = c.ext->surfaces[orient]; dst = src; dst.verts = dstoffset; if(srcverts) memcpy(c.ext->verts() + dstoffset, srcverts, numsrcverts*sizeof(vertinfo)); } // quality parameters, set by the calclight arg VARNR(lmshadows, lmshadows_, 0, 2, 2); VARNR(lmaa, lmaa_, 0, 3, 3); VARNR(lerptjoints, lerptjoints_, 0, 1, 1); static int lmshadows = 2, lmaa = 3, lerptjoints = 1; static uint progress = 0, taskprogress = 0; static GLuint progresstex = 0; static int progresstexticks = 0, progresslightmap = -1; bool calclight_canceled = false; volatile bool check_calclight_progress = false; void check_calclight_canceled() { if(interceptkey(SDLK_ESCAPE)) { calclight_canceled = true; loopv(lightmapworkers) lightmapworkers[i]->doneworking = true; } if(!calclight_canceled) check_calclight_progress = false; } void show_calclight_progress() { float bar1 = float(progress) / float(allocnodes); defformatstring(text1)("%.2f%% using %d textures", bar1 * 100, lightmaps.length()); if(LM_PACKW <= hwtexsize && !progresstex) { glGenTextures(1, &progresstex); createtexture(progresstex, LM_PACKW, LM_PACKH, NULL, 3, 1, GL_RGB); } // only update once a sec (4 * 250 ms ticks) to not kill performance if(progresstex && !calclight_canceled && progresslightmap >= 0 && !(progresstexticks++ % 4)) { if(tasklock) SDL_LockMutex(tasklock); LightMap &lm = lightmaps[progresslightmap]; uchar *data = lm.data; int bpp = lm.bpp; if(tasklock) SDL_UnlockMutex(tasklock); glBindTexture(GL_TEXTURE_2D, progresstex); glPixelStorei(GL_UNPACK_ALIGNMENT, texalign(data, LM_PACKW, bpp)); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, LM_PACKW, LM_PACKH, bpp > 3 ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, data); } renderprogress(bar1, text1, progresstexticks ? progresstex : 0); } #define CHECK_PROGRESS_LOCKED(exit, before, after) CHECK_CALCLIGHT_PROGRESS_LOCKED(exit, show_calclight_progress, before, after) #define CHECK_PROGRESS(exit) CHECK_PROGRESS_LOCKED(exit, , ) bool PackNode::insert(ushort &tx, ushort &ty, ushort tw, ushort th) { if((available < tw && available < th) || w < tw || h < th) return false; if(child1) { bool inserted = child1->insert(tx, ty, tw, th) || child2->insert(tx, ty, tw, th); available = max(child1->available, child2->available); if(!available) clear(); return inserted; } if(w == tw && h == th) { available = 0; tx = x; ty = y; return true; } if(w - tw > h - th) { child1 = new PackNode(x, y, tw, h); child2 = new PackNode(x + tw, y, w - tw, h); } else { child1 = new PackNode(x, y, w, th); child2 = new PackNode(x, y + th, w, h - th); } bool inserted = child1->insert(tx, ty, tw, th); available = max(child1->available, child2->available); return inserted; } bool LightMap::insert(ushort &tx, ushort &ty, uchar *src, ushort tw, ushort th) { if((type&LM_TYPE) != LM_BUMPMAP1 && !packroot.insert(tx, ty, tw, th)) return false; copy(tx, ty, src, tw, th); return true; } void LightMap::copy(ushort tx, ushort ty, uchar *src, ushort tw, ushort th) { uchar *dst = data + bpp * tx + ty * bpp * LM_PACKW; loopi(th) { memcpy(dst, src, bpp * tw); dst += bpp * LM_PACKW; src += bpp * tw; } ++lightmaps; lumels += tw * th; } static void insertunlit(int i) { LightMap &l = lightmaps[i]; if((l.type&LM_TYPE) == LM_BUMPMAP1) { l.unlitx = l.unlity = -1; return; } ushort x, y; uchar unlit[4] = { ambientcolor[0], ambientcolor[1], ambientcolor[2], 255 }; if(l.insert(x, y, unlit, 1, 1)) { if((l.type&LM_TYPE) == LM_BUMPMAP0) { bvec front(128, 128, 255); ASSERT(lightmaps[i+1].insert(x, y, front.v, 1, 1)); } l.unlitx = x; l.unlity = y; } } struct layoutinfo { ushort x, y, lmid; uchar w, h; }; static void insertlightmap(lightmapinfo &li, layoutinfo &si) { loopv(lightmaps) { if(lightmaps[i].type == li.type && lightmaps[i].insert(si.x, si.y, li.colorbuf, si.w, si.h)) { si.lmid = i + LMID_RESERVED; if((li.type&LM_TYPE) == LM_BUMPMAP0) ASSERT(lightmaps[i+1].insert(si.x, si.y, (uchar *)li.raybuf, si.w, si.h)); return; } } progresslightmap = lightmaps.length(); si.lmid = lightmaps.length() + LMID_RESERVED; LightMap &l = lightmaps.add(); l.type = li.type; l.bpp = li.bpp; l.data = new uchar[li.bpp*LM_PACKW*LM_PACKH]; memset(l.data, 0, li.bpp*LM_PACKW*LM_PACKH); ASSERT(l.insert(si.x, si.y, li.colorbuf, si.w, si.h)); if((li.type&LM_TYPE) == LM_BUMPMAP0) { LightMap &r = lightmaps.add(); r.type = LM_BUMPMAP1 | (li.type&~LM_TYPE); r.bpp = 3; r.data = new uchar[3*LM_PACKW*LM_PACKH]; memset(r.data, 0, 3*LM_PACKW*LM_PACKH); ASSERT(r.insert(si.x, si.y, (uchar *)li.raybuf, si.w, si.h)); } } static void copylightmap(lightmapinfo &li, layoutinfo &si) { lightmaps[si.lmid-LMID_RESERVED].copy(si.x, si.y, li.colorbuf, si.w, si.h); if((li.type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(si.lmid+1-LMID_RESERVED)) lightmaps[si.lmid+1-LMID_RESERVED].copy(si.x, si.y, (uchar *)li.raybuf, si.w, si.h); } static inline bool htcmp(const lightmapinfo &k, const layoutinfo &v) { int kw = k.w, kh = k.h; if(kw != v.w || kh != v.h) return false; LightMap &vlm = lightmaps[v.lmid - LMID_RESERVED]; int ktype = k.type; if(ktype != vlm.type) return false; int kbpp = k.bpp; const uchar *kcolor = k.colorbuf, *vcolor = vlm.data + kbpp*(v.x + v.y*LM_PACKW); loopi(kh) { if(memcmp(kcolor, vcolor, kbpp*kw)) return false; kcolor += kbpp*kw; vcolor += kbpp*LM_PACKW; } if((ktype&LM_TYPE) != LM_BUMPMAP0) return true; const bvec *kdir = k.raybuf, *vdir = (const bvec *)lightmaps[v.lmid+1 - LMID_RESERVED].data; loopi(kh) { if(memcmp(kdir, vdir, kw*sizeof(bvec))) return false; kdir += kw; vdir += LM_PACKW; } return true; } static inline uint hthash(const lightmapinfo &k) { int kw = k.w, kh = k.h, kbpp = k.bpp; uint hash = kw + (kh<<8); const uchar *color = k.colorbuf; loopi(kw*kh) { hash ^= color[0] + (color[1] << 4) + (color[2] << 8); color += kbpp; } return hash; } static hashset compressed; VAR(lightcompress, 0, 3, 6); static bool packlightmap(lightmapinfo &l, layoutinfo &surface) { surface.w = l.w; surface.h = l.h; if((int)l.w <= lightcompress && (int)l.h <= lightcompress) { layoutinfo *val = compressed.access(l); if(!val) { insertlightmap(l, surface); compressed[l] = surface; } else { surface.x = val->x; surface.y = val->y; surface.lmid = val->lmid; return false; } } else insertlightmap(l, surface); return true; } static void updatelightmap(const layoutinfo &surface) { if(max(LM_PACKW, LM_PACKH) > hwtexsize) return; LightMap &lm = lightmaps[surface.lmid-LMID_RESERVED]; if(lm.tex < 0) { lm.offsetx = lm.offsety = 0; lm.tex = lightmaptexs.length(); LightMapTexture &tex = lightmaptexs.add(); tex.type = renderpath==R_FIXEDFUNCTION ? (lm.type&~LM_TYPE) | LM_DIFFUSE : lm.type; tex.w = LM_PACKW; tex.h = LM_PACKH; tex.unlitx = lm.unlitx; tex.unlity = lm.unlity; glGenTextures(1, &tex.id); createtexture(tex.id, tex.w, tex.h, NULL, 3, 1, tex.type&LM_ALPHA ? GL_RGBA : GL_RGB); if(renderpath!=R_FIXEDFUNCTION && (lm.type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(surface.lmid+1-LMID_RESERVED)) { LightMap &lm2 = lightmaps[surface.lmid+1-LMID_RESERVED]; lm2.offsetx = lm2.offsety = 0; lm2.tex = lightmaptexs.length(); LightMapTexture &tex2 = lightmaptexs.add(); tex2.type = (lm.type&~LM_TYPE) | LM_BUMPMAP0; tex2.w = LM_PACKW; tex2.h = LM_PACKH; tex2.unlitx = lm2.unlitx; tex2.unlity = lm2.unlity; glGenTextures(1, &tex2.id); createtexture(tex2.id, tex2.w, tex2.h, NULL, 3, 1, GL_RGB); } } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ROW_LENGTH, LM_PACKW); glBindTexture(GL_TEXTURE_2D, lightmaptexs[lm.tex].id); glTexSubImage2D(GL_TEXTURE_2D, 0, lm.offsetx + surface.x, lm.offsety + surface.y, surface.w, surface.h, lm.type&LM_ALPHA ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, &lm.data[(surface.y*LM_PACKW + surface.x)*lm.bpp]); if(renderpath!=R_FIXEDFUNCTION && (lm.type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(surface.lmid+1-LMID_RESERVED)) { LightMap &lm2 = lightmaps[surface.lmid+1-LMID_RESERVED]; glBindTexture(GL_TEXTURE_2D, lightmaptexs[lm2.tex].id); glTexSubImage2D(GL_TEXTURE_2D, 0, lm2.offsetx + surface.x, lm2.offsety + surface.y, surface.w, surface.h, GL_RGB, GL_UNSIGNED_BYTE, &lm2.data[(surface.y*LM_PACKW + surface.x)*3]); } glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); } static uint generatelumel(lightmapworker *w, const float tolerance, uint lightmask, const vector &lights, const vec &target, const vec &normal, vec &sample, int x, int y) { vec avgray(0, 0, 0); float r = 0, g = 0, b = 0; uint lightused = 0; loopv(lights) { if(lightmask&(1<type==ET_SPOTLIGHT) { vec spot(vec(light.attached->o).sub(light.o).normalize()); float maxatten = 1-cosf(max(1, min(90, int(light.attached->attr[0])))*RAD); float spotatten = 1-(1-ray.dot(spot))/maxatten; if(spotatten <= 0) continue; attenuation *= spotatten; } if(lmshadows && mag) { float dist = shadowray(w->shadowraycache, light.o, ray, mag - tolerance, RAY_SHADOW | (lmshadows > 1 ? RAY_ALPHAPOLY : 0)); if(dist < mag - tolerance) continue; } lightused |= 1<type&LM_TYPE) { case LM_BUMPMAP0: intensity = attenuation; avgray.add(ray.mul(-attenuation)); break; default: intensity = angle * attenuation; break; } r += intensity * float(light.attr[1]); g += intensity * float(light.attr[2]); b += intensity * float(light.attr[3]); } if(sunlight) { float angle = sunlightdir.dot(normal); if(angle > 0 && (!lmshadows || shadowray(w->shadowraycache, vec(sunlightdir).mul(tolerance).add(target), sunlightdir, 1e16f, RAY_SHADOW | (lmshadows > 1 ? RAY_ALPHAPOLY : 0) | (skytexturelight ? RAY_SKIPSKY : 0)) > 1e15f)) { float intensity; switch(w->type&LM_TYPE) { case LM_BUMPMAP0: intensity = 1; avgray.add(sunlightdir); break; default: intensity = angle; break; } r += intensity * (sunlightcolor.x*sunlightscale); g += intensity * (sunlightcolor.y*sunlightscale); b += intensity * (sunlightcolor.z*sunlightscale); } } switch(w->type&LM_TYPE) { case LM_BUMPMAP0: if(avgray.iszero()) break; // transform to tangent space extern vec orientation_tangent[6][3]; extern vec orientation_binormal[6][3]; vec S(orientation_tangent[w->rotate][dimension(w->orient)]), T(orientation_binormal[w->rotate][dimension(w->orient)]); normal.orthonormalize(S, T); avgray.normalize(); w->raydata[y*w->w+x].add(vec(S.dot(avgray)/S.magnitude(), T.dot(avgray)/T.magnitude(), normal.dot(avgray))); break; } sample.x = min(255.0f, max(r, float(ambientcolor[0]))); sample.y = min(255.0f, max(g, float(ambientcolor[1]))); sample.z = min(255.0f, max(b, float(ambientcolor[2]))); return lightused; } static bool lumelsample(const vec &sample, int aasample, int stride) { if(sample.x >= int(ambientcolor[0])+1 || sample.y >= int(ambientcolor[1])+1 || sample.z >= int(ambientcolor[2])+1) return true; #define NCHECK(n) \ if((n).x >= int(ambientcolor[0])+1 || (n).y >= int(ambientcolor[1])+1 || (n).z >= int(ambientcolor[2])+1) \ return true; const vec *n = &sample - stride - aasample; NCHECK(n[0]); NCHECK(n[aasample]); NCHECK(n[2*aasample]); n += stride; NCHECK(n[0]); NCHECK(n[2*aasample]); n += stride; NCHECK(n[0]); NCHECK(n[aasample]); NCHECK(n[2*aasample]); return false; } static void calcskylight(lightmapworker *w, const vec &o, const vec &normal, float tolerance, uchar *skylight, int flags = RAY_ALPHAPOLY, extentity *t = NULL) { static const vec rays[17] = { vec(cosf(21*RAD)*cosf(50*RAD), sinf(21*RAD)*cosf(50*RAD), sinf(50*RAD)), vec(cosf(111*RAD)*cosf(50*RAD), sinf(111*RAD)*cosf(50*RAD), sinf(50*RAD)), vec(cosf(201*RAD)*cosf(50*RAD), sinf(201*RAD)*cosf(50*RAD), sinf(50*RAD)), vec(cosf(291*RAD)*cosf(50*RAD), sinf(291*RAD)*cosf(50*RAD), sinf(50*RAD)), vec(cosf(66*RAD)*cosf(70*RAD), sinf(66*RAD)*cosf(70*RAD), sinf(70*RAD)), vec(cosf(156*RAD)*cosf(70*RAD), sinf(156*RAD)*cosf(70*RAD), sinf(70*RAD)), vec(cosf(246*RAD)*cosf(70*RAD), sinf(246*RAD)*cosf(70*RAD), sinf(70*RAD)), vec(cosf(336*RAD)*cosf(70*RAD), sinf(336*RAD)*cosf(70*RAD), sinf(70*RAD)), vec(0, 0, 1), vec(cosf(43*RAD)*cosf(60*RAD), sinf(43*RAD)*cosf(60*RAD), sinf(60*RAD)), vec(cosf(133*RAD)*cosf(60*RAD), sinf(133*RAD)*cosf(60*RAD), sinf(60*RAD)), vec(cosf(223*RAD)*cosf(60*RAD), sinf(223*RAD)*cosf(60*RAD), sinf(60*RAD)), vec(cosf(313*RAD)*cosf(60*RAD), sinf(313*RAD)*cosf(60*RAD), sinf(60*RAD)), vec(cosf(88*RAD)*cosf(80*RAD), sinf(88*RAD)*cosf(80*RAD), sinf(80*RAD)), vec(cosf(178*RAD)*cosf(80*RAD), sinf(178*RAD)*cosf(80*RAD), sinf(80*RAD)), vec(cosf(268*RAD)*cosf(80*RAD), sinf(268*RAD)*cosf(80*RAD), sinf(80*RAD)), vec(cosf(358*RAD)*cosf(80*RAD), sinf(358*RAD)*cosf(80*RAD), sinf(80*RAD)), }; flags |= RAY_SHADOW; if(skytexturelight) flags |= RAY_SKIPSKY; int hit = 0; if(w) loopi(17) { if(normal.dot(rays[i])>=0 && shadowray(w->shadowraycache, vec(rays[i]).mul(tolerance).add(o), rays[i], 1e16f, flags, t)>1e15f) hit++; } else loopi(17) { if(normal.dot(rays[i])>=0 && shadowray(vec(rays[i]).mul(tolerance).add(o), rays[i], 1e16f, flags, t)>1e15f) hit++; } loopk(3) skylight[k] = uchar(ambientcolor[k] + (max(skylightcolor[k], ambientcolor[k]) - ambientcolor[k])*hit/17.0f); } static inline bool hasskylight() { return skylightcolor[0]>ambientcolor[0] || skylightcolor[1]>ambientcolor[1] || skylightcolor[2]>ambientcolor[2]; } VARR(blurlms, 0, 0, 2); VARR(blurskylight, 0, 0, 2); static inline void generatealpha(lightmapworker *w, float tolerance, const vec &pos, uchar &alpha) { alpha = lookupblendmap(w->blendmapcache, pos); if(w->slot->layermask) { static const int sdim[] = { 1, 0, 0 }, tdim[] = { 2, 2, 1 }; int dim = dimension(w->orient); float k = 8.0f/w->vslot->scale, s = (pos[sdim[dim]] * k - w->vslot->xoffset) / w->slot->layermaskscale, t = (pos[tdim[dim]] * (dim <= 1 ? -k : k) - w->vslot->yoffset) / w->slot->layermaskscale; if((w->rotate&5)==1) swap(s, t); if(w->rotate>=2 && w->rotate<=4) s = -s; if((w->rotate>=1 && w->rotate<=2) || w->rotate==5) t = -t; const ImageData &mask = *w->slot->layermask; int mx = int(floor(s))%mask.w, my = int(floor(t))%mask.h; if(mx < 0) mx += mask.w; if(my < 0) my += mask.h; uchar maskval = mask.data[mask.bpp*(mx + 1) - 1 + mask.pitch*my]; switch(w->slot->layermaskmode) { case 2: alpha = min(alpha, maskval); break; case 3: alpha = max(alpha, maskval); break; case 4: alpha = min(alpha, uchar(0xFF - maskval)); break; case 5: alpha = max(alpha, uchar(0xFF - maskval)); break; default: alpha = maskval; break; } } } VAR(edgetolerance, 1, 4, 8); VAR(adaptivesample, 0, 2, 2); enum { NO_SURFACE = 0, SURFACE_AMBIENT_BOTTOM, SURFACE_AMBIENT_TOP, SURFACE_LIGHTMAP_BOTTOM, SURFACE_LIGHTMAP_TOP, SURFACE_LIGHTMAP_BLEND }; #define SURFACE_AMBIENT SURFACE_AMBIENT_BOTTOM #define SURFACE_LIGHTMAP SURFACE_LIGHTMAP_BOTTOM static bool generatelightmap(lightmapworker *w, float lpu, const lerpvert *lv, int numv, const vec &origin1, const vec &xstep1, const vec &ystep1, const vec &origin2, const vec &xstep2, const vec &ystep2, float side0, float sidestep) { static const float aacoords[8][2] = { {0.0f, 0.0f}, {-0.5f, -0.5f}, {0.0f, -0.5f}, {-0.5f, 0.0f}, {0.3f, -0.6f}, {0.6f, 0.3f}, {-0.3f, 0.6f}, {-0.6f, -0.3f}, }; float tolerance = 0.5 / lpu; uint lightmask = 0, lightused = 0; vec offsets1[8], offsets2[8]; loopi(8) { offsets1[i] = vec(xstep1).mul(aacoords[i][0]).add(vec(ystep1).mul(aacoords[i][1])); offsets2[i] = vec(xstep2).mul(aacoords[i][0]).add(vec(ystep2).mul(aacoords[i][1])); } if((w->type&LM_TYPE) == LM_BUMPMAP0) memset(w->raydata, 0, LM_MAXW*LM_MAXH*sizeof(vec)); int aasample = min(1 << lmaa, 4); int stride = aasample*(w->w+1); vec *sample = w->colordata; uchar *skylight = w->ambient; lerpbounds start, end; initlerpbounds(lv, numv, start, end); float sidex = side0; for(int y = 0; y < w->h; ++y, sidex += sidestep) { vec normal, nstep; lerpnormal(y, lv, numv, start, end, normal, nstep); for(int x = 0; x < w->w; ++x, normal.add(nstep), skylight += w->bpp) { vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(y)).add(origin2); lightused |= generatelumel(w, tolerance, 0, w->lights, u, vec(normal).normalize(), *sample, x, y); if(hasskylight()) { if((w->type&LM_TYPE)==LM_BUMPMAP0 || !adaptivesample || sample->xyz 1 ? RAY_ALPHAPOLY : 0); else loopk(3) skylight[k] = max(skylightcolor[k], ambientcolor[k]); } else loopk(3) skylight[k] = ambientcolor[k]; if(w->type&LM_ALPHA) generatealpha(w, tolerance, u, skylight[3]); sample += aasample; } sample += aasample; } if(adaptivesample > 1 && min(w->w, w->h) >= 2) lightmask = ~lightused; sample = w->colordata; initlerpbounds(lv, numv, start, end); sidex = side0; for(int y = 0; y < w->h; ++y, sidex += sidestep) { vec normal, nstep; lerpnormal(y, lv, numv, start, end, normal, nstep); for(int x = 0; x < w->w; ++x, normal.add(nstep)) { vec ¢er = *sample++; if(adaptivesample && x > 0 && x+1 < w->w && y > 0 && y+1 < w->h && !lumelsample(center, aasample, stride)) loopi(aasample-1) *sample++ = center; else { #define EDGE_TOLERANCE(i) \ ((!x && aacoords[i][0] < 0) \ || (x+1==w->w && aacoords[i][0] > 0) \ || (!y && aacoords[i][1] < 0) \ || (y+1==w->h && aacoords[i][1] > 0) \ ? edgetolerance : 1) vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(y)).add(origin2); const vec *offsets = x < sidex ? offsets1 : offsets2; vec n = vec(normal).normalize(); loopi(aasample-1) generatelumel(w, EDGE_TOLERANCE(i+1) * tolerance, lightmask, w->lights, vec(u).add(offsets[i+1]), n, *sample++, x, y); if(lmaa == 3) { loopi(4) { vec s; generatelumel(w, EDGE_TOLERANCE(i+4) * tolerance, lightmask, w->lights, vec(u).add(offsets[i+4]), n, s, x, y); center.add(s); } center.div(5); } } } if(aasample > 1) { vec u = w->w < sidex ? vec(xstep1).mul(w->w).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(w->w).add(vec(ystep2).mul(y)).add(origin2); const vec *offsets = w->w < sidex ? offsets1 : offsets2; vec n = vec(normal).normalize(); generatelumel(w, tolerance, lightmask, w->lights, vec(u).add(offsets[1]), n, sample[1], w->w-1, y); if(aasample > 2) generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[3]), n, sample[3], w->w-1, y); } sample += aasample; } if(aasample > 1) { vec normal, nstep; lerpnormal(w->h, lv, numv, start, end, normal, nstep); for(int x = 0; x <= w->w; ++x, normal.add(nstep)) { vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(w->h)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(w->h)).add(origin2); const vec *offsets = x < sidex ? offsets1 : offsets2; vec n = vec(normal).normalize(); generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[1]), n, sample[1], min(x, w->w-1), w->h-1); if(aasample > 2) generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[2]), n, sample[2], min(x, w->w-1), w->h-1); sample += aasample; } } return true; } static int finishlightmap(lightmapworker *w) { if(hasskylight() && blurskylight && (w->w>1 || w->h>1)) { blurtexture(blurskylight, w->bpp, w->w, w->h, w->blur, w->ambient); swap(w->blur, w->ambient); } vec *sample = w->colordata; int aasample = min(1 << lmaa, 4), stride = aasample*(w->w+1); float weight = 1.0f / (1.0f + 4.0f*lmaa), cweight = weight * (lmaa == 3 ? 5.0f : 1.0f); uchar *skylight = w->ambient; vec *ray = w->raydata; uchar *dstcolor = w->colorbuf; uchar mincolor[4] = { 255, 255, 255, 255 }, maxcolor[4] = { 0, 0, 0, 0 }; bvec *dstray = w->raybuf; bvec minray(255, 255, 255), maxray(0, 0, 0); loop(y, w->h) { loop(x, w->w) { vec l(0, 0, 0); const vec ¢er = *sample++; loopi(aasample-1) l.add(*sample++); if(aasample > 1) { l.add(sample[1]); if(aasample > 2) l.add(sample[3]); } vec *next = sample + stride - aasample; if(aasample > 1) { l.add(next[1]); if(aasample > 2) l.add(next[2]); l.add(next[aasample+1]); } int r = int(center.x*cweight + l.x*weight), g = int(center.y*cweight + l.y*weight), b = int(center.z*cweight + l.z*weight), ar = skylight[0], ag = skylight[1], ab = skylight[2]; dstcolor[0] = max(ar, r); dstcolor[1] = max(ag, g); dstcolor[2] = max(ab, b); loopk(3) { mincolor[k] = min(mincolor[k], dstcolor[k]); maxcolor[k] = max(maxcolor[k], dstcolor[k]); } if(w->type&LM_ALPHA) { dstcolor[3] = skylight[3]; mincolor[3] = min(mincolor[3], dstcolor[3]); maxcolor[3] = max(maxcolor[3], dstcolor[3]); } if((w->type&LM_TYPE) == LM_BUMPMAP0) { if(ray->iszero()) dstray[0] = bvec(128, 128, 255); else { // bias the normals towards the amount of ambient/skylight in the lumel // this is necessary to prevent the light values in shaders from dropping too far below the skylight (to the ambient) if N.L is small ray->normalize(); int l = max(r, max(g, b)), a = max(ar, max(ag, ab)); ray->mul(max(l-a, 0)); ray->z += a; dstray[0] = bvec(ray->normalize()); } loopk(3) { minray[k] = min(minray[k], dstray[0][k]); maxray[k] = max(maxray[k], dstray[0][k]); } ray++; dstray++; } dstcolor += w->bpp; skylight += w->bpp; } sample += aasample; } if(int(maxcolor[0]) - int(mincolor[0]) <= lighterror && int(maxcolor[1]) - int(mincolor[1]) <= lighterror && int(maxcolor[2]) - int(mincolor[2]) <= lighterror && mincolor[3] >= maxcolor[3]) { uchar color[3]; loopk(3) color[k] = (int(maxcolor[k]) + int(mincolor[k])) / 2; if(color[0] <= int(ambientcolor[0]) + lighterror && color[1] <= int(ambientcolor[1]) + lighterror && color[2] <= int(ambientcolor[2]) + lighterror && (maxcolor[3]==0 || mincolor[3]==255)) return mincolor[3]==255 ? SURFACE_AMBIENT_TOP : SURFACE_AMBIENT_BOTTOM; if((w->type&LM_TYPE) != LM_BUMPMAP0 || (int(maxray.x) - int(minray.x) <= bumperror && int(maxray.y) - int(minray.z) <= bumperror && int(maxray.z) - int(minray.z) <= bumperror)) { memcpy(w->colorbuf, color, 3); if(w->type&LM_ALPHA) w->colorbuf[3] = mincolor[3]; if((w->type&LM_TYPE) == LM_BUMPMAP0) { loopk(3) w->raybuf[0][k] = uchar((int(maxray[k])+int(minray[k]))/2); } w->lastlightmap->w = w->w = 1; w->lastlightmap->h = w->h = 1; } } if(blurlms && (w->w>1 || w->h>1)) { blurtexture(blurlms, w->bpp, w->w, w->h, w->blur, w->colorbuf); memcpy(w->colorbuf, w->blur, w->bpp*w->w*w->h); } if(mincolor[3]==255) return SURFACE_LIGHTMAP_TOP; else if(maxcolor[3]==0) return SURFACE_LIGHTMAP_BOTTOM; else return SURFACE_LIGHTMAP_BLEND; } static int previewlightmapalpha(lightmapworker *w, float lpu, const vec &origin1, const vec &xstep1, const vec &ystep1, const vec &origin2, const vec &xstep2, const vec &ystep2, float side0, float sidestep) { extern int fullbrightlevel; float tolerance = 0.5 / lpu; uchar *dst = w->colorbuf; uchar minalpha = 255, maxalpha = 0; float sidex = side0; for(int y = 0; y < w->h; ++y, sidex += sidestep) { for(int x = 0; x < w->w; ++x, dst += 4) { vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(y)).add(origin2); loopk(3) dst[k] = fullbrightlevel; generatealpha(w, tolerance, u, dst[3]); minalpha = min(minalpha, dst[3]); maxalpha = max(maxalpha, dst[3]); } } if(minalpha==255) return SURFACE_AMBIENT_TOP; if(maxalpha==0) return SURFACE_AMBIENT_BOTTOM; if(minalpha==maxalpha) w->w = w->h = 1; if((w->type&LM_TYPE) == LM_BUMPMAP0) loopi(w->w*w->h) w->raybuf[i] = bvec(128, 128, 255); return SURFACE_LIGHTMAP_BLEND; } static void clearsurfaces(cube *c) { loopi(8) { if(c[i].ext) { loopj(6) { surfaceinfo &surf = c[i].ext->surfaces[j]; if(!surf.used()) continue; surf.clear(); int numverts = surf.numverts&MAXFACEVERTS; if(numverts) { if(!(c[i].merged&(1<verts() + surf.verts; loopk(numverts) { vertinfo &v = verts[k]; v.u = 0; v.v = 0; v.norm = 0; } } } } if(c[i].children) clearsurfaces(c[i].children); } } #define LIGHTCACHESIZE 1024 static struct lightcacheentry { int x, y; vector lights; } lightcache[LIGHTCACHESIZE]; #define LIGHTCACHEHASH(x, y) (((((x)^(y))<<5) + (((x)^(y))>>5)) & (LIGHTCACHESIZE - 1)) VARF(lightcachesize, 4, 6, 12, clearlightcache()); void clearlightcache(int e) { if(e < 0 || !entities::getents()[e]->attr[0]) { for(lightcacheentry *lce = lightcache; lce < &lightcache[LIGHTCACHESIZE]; lce++) { lce->x = -1; lce->lights.setsize(0); } } else { const extentity &light = *entities::getents()[e]; int radius = light.attr[0]; for(int x = int(max(light.o.x-radius, 0.0f))>>lightcachesize, ex = int(min(light.o.x+radius, worldsize-1.0f))>>lightcachesize; x <= ex; x++) for(int y = int(max(light.o.y-radius, 0.0f))>>lightcachesize, ey = int(min(light.o.y+radius, worldsize-1.0f))>>lightcachesize; y <= ey; y++) { lightcacheentry &lce = lightcache[LIGHTCACHEHASH(x, y)]; if(lce.x != x || lce.y != y) continue; lce.x = -1; lce.lights.setsize(0); } } } const vector &checklightcache(int x, int y) { x >>= lightcachesize; y >>= lightcachesize; lightcacheentry &lce = lightcache[LIGHTCACHEHASH(x, y)]; if(lce.x == x && lce.y == y) return lce.lights; lce.lights.setsize(0); int csize = 1< &ents = entities::getents(); loopv(ents) { const extentity &light = *ents[i]; switch(light.type) { case ET_LIGHT: { int radius = light.attr[0]; if(radius > 0) { if(light.o.x + radius < cx || light.o.x - radius > cx + csize || light.o.y + radius < cy || light.o.y - radius > cy + csize) continue; } break; } default: continue; } lce.lights.add(i); } lce.x = x; lce.y = y; return lce.lights; } static inline void addlight(lightmapworker *w, const extentity &light, int cx, int cy, int cz, int size, const vec *v, const vec *n, int numv) { int radius = light.attr[0]; if(radius > 0) { if(light.o.x + radius < cx || light.o.x - radius > cx + size || light.o.y + radius < cy || light.o.y - radius > cy + size || light.o.z + radius < cz || light.o.z - radius > cz + size) return; } loopi(4) { vec p(light.o); p.sub(v[i]); float dist = p.dot(n[i]); if(dist >= 0 && (!radius || dist < radius)) { w->lights.add(&light); break; } } } static bool findlights(lightmapworker *w, int cx, int cy, int cz, int size, const vec *v, const vec *n, int numv, const Slot &slot, const VSlot &vslot) { w->lights.setsize(0); const vector &ents = entities::getents(); static volatile bool usinglightcache = false; if(size <= 1< &lights = checklightcache(cx, cy); loopv(lights) { const extentity &light = *ents[lights[i]]; switch(light.type) { case ET_LIGHT: addlight(w, light, cx, cy, cz, size, v, n, numv); break; } } if(lightlock) { usinglightcache = false; SDL_UnlockMutex(lightlock); } } else loopv(ents) { const extentity &light = *ents[i]; switch(light.type) { case ET_LIGHT: addlight(w, light, cx, cy, cz, size, v, n, numv); break; } } if(vslot.layer && (setblendmaporigin(w->blendmapcache, ivec(cx, cy, cz), size) || slot.layermask)) return true; return w->lights.length() || hasskylight() || sunlight; } static int packlightmaps(lightmapworker *w = NULL) { int numpacked = 0; for(; packidx < lightmaptasks[0].length(); packidx++, numpacked++) { lightmaptask &t = lightmaptasks[0][packidx]; if(!t.lightmaps) break; if(t.ext && t.c->ext != t.ext) { lightmapext &e = lightmapexts.add(); e.c = t.c; e.ext = t.ext; } progress = t.progress; lightmapinfo *l = t.lightmaps; if(l == (lightmapinfo *)-1) continue; int space = 0; for(; l && l->c == t.c; l = l->next) { l->packed = true; space += l->bufsize; if(l->surface < 0 || !t.ext) continue; surfaceinfo &surf = t.ext->surfaces[l->surface]; layoutinfo layout; packlightmap(*l, layout); int numverts = surf.numverts&MAXFACEVERTS; vertinfo *verts = t.ext->verts() + surf.verts; if(surf.numverts&LAYER_DUP) { if(l->type&LM_ALPHA) surf.lmid[0] = layout.lmid; else { surf.lmid[1] = layout.lmid; verts += numverts; } } else { surf.lmid[0] = surf.numverts&LAYER_TOP ? layout.lmid : LMID_AMBIENT; surf.lmid[1] = surf.numverts&LAYER_BOTTOM ? layout.lmid : LMID_AMBIENT; } ushort offsetx = layout.x*((USHRT_MAX+1)/LM_PACKW), offsety = layout.y*((USHRT_MAX+1)/LM_PACKH); loopk(numverts) { vertinfo &v = verts[k]; v.u += offsetx; v.v += offsety; } } if(t.worker == w) { w->bufused -= space; w->bufstart = (w->bufstart + space)%LIGHTMAPBUFSIZE; w->firstlightmap = l; if(!l) { w->lastlightmap = NULL; w->bufstart = w->bufused = 0; } } if(t.worker->needspace) SDL_CondSignal(t.worker->spacecond); } return numpacked; } static lightmapinfo *alloclightmap(lightmapworker *w) { int needspace1 = sizeof(lightmapinfo) + w->w*w->h*w->bpp, needspace2 = (w->type&LM_TYPE) == LM_BUMPMAP0 ? w->w*w->h*3 : 0, needspace = needspace1 + needspace2, bufend = (w->bufstart + w->bufused)%LIGHTMAPBUFSIZE, availspace = LIGHTMAPBUFSIZE - w->bufused, availspace1 = min(availspace, LIGHTMAPBUFSIZE - bufend), availspace2 = min(availspace, w->bufstart); if(availspace < needspace || (max(availspace1, availspace2) < needspace && (availspace1 < needspace1 || availspace2 < needspace2))) { if(tasklock) SDL_LockMutex(tasklock); while(!w->doneworking) { lightmapinfo *l = w->firstlightmap; for(; l && l->packed; l = l->next) { w->bufused -= l->bufsize; w->bufstart = (w->bufstart + l->bufsize)%LIGHTMAPBUFSIZE; } w->firstlightmap = l; if(!l) { w->lastlightmap = NULL; w->bufstart = w->bufused = 0; } bufend = (w->bufstart + w->bufused)%LIGHTMAPBUFSIZE; availspace = LIGHTMAPBUFSIZE - w->bufused; availspace1 = min(availspace, LIGHTMAPBUFSIZE - bufend); availspace2 = min(availspace, w->bufstart); if(availspace >= needspace && (max(availspace1, availspace2) >= needspace || (availspace1 >= needspace1 && availspace2 >= needspace2))) break; if(packlightmaps(w)) continue; if(!w->spacecond || !tasklock) break; w->needspace = true; SDL_CondWait(w->spacecond, tasklock); w->needspace = false; } if(tasklock) SDL_UnlockMutex(tasklock); } int usedspace = needspace; lightmapinfo *l = NULL; if(availspace1 >= needspace1) { l = (lightmapinfo *)&w->buf[bufend]; w->colorbuf = (uchar *)(l + 1); if((w->type&LM_TYPE) != LM_BUMPMAP0) w->raybuf = NULL; else if(availspace1 >= needspace) w->raybuf = (bvec *)&w->buf[bufend + needspace1]; else { w->raybuf = (bvec *)w->buf; usedspace += availspace1 - needspace1; } } else if(availspace2 >= needspace) { usedspace += availspace1; l = (lightmapinfo *)w->buf; w->colorbuf = (uchar *)(l + 1); w->raybuf = (w->type&LM_TYPE) == LM_BUMPMAP0 ? (bvec *)&w->buf[needspace1] : NULL; } else return NULL; w->bufused += usedspace; l->next = NULL; l->c = w->c; l->type = w->type; l->w = w->w; l->h = w->h; l->bpp = w->bpp; l->colorbuf = w->colorbuf; l->raybuf = w->raybuf; l->packed = false; l->bufsize = usedspace; l->surface = -1; if(!w->firstlightmap) w->firstlightmap = l; if(w->lastlightmap) w->lastlightmap->next = l; w->lastlightmap = l; if(!w->curlightmaps) w->curlightmaps = l; return l; } static void freelightmap(lightmapworker *w) { lightmapinfo *l = w->lastlightmap; if(!l || l->surface >= 0) return; if(w->firstlightmap == w->lastlightmap) { w->firstlightmap = w->lastlightmap = w->curlightmaps = NULL; w->bufstart = w->bufused = 0; } else { w->bufused -= l->bufsize - sizeof(lightmapinfo); l->bufsize = sizeof(lightmapinfo); l->packed = true; } if(w->curlightmaps == l) w->curlightmaps = NULL; } static int setupsurface(lightmapworker *w, plane planes[2], int numplanes, const vec *p, const vec *n, int numverts, vertinfo *litverts, bool preview = false) { vec u, v, t; vec2 c[MAXFACEVERTS]; u = vec(p[2]).sub(p[0]).normalize(); v.cross(planes[0], u); c[0] = vec2(0, 0); if(numplanes >= 2) t.cross(planes[1], u); else t = v; vec r1 = vec(p[1]).sub(p[0]); c[1] = vec2(r1.dot(u), min(r1.dot(v), 0.0f)); c[2] = vec2(vec(p[2]).sub(p[0]).dot(u), 0); for(int i = 3; i < numverts; i++) { vec r = vec(p[i]).sub(p[0]); c[i] = vec2(r.dot(u), max(r.dot(t), 0.0f)); } float carea = 1e16f; vec2 cx(0, 0), cy(0, 0), co(0, 0), cmin(0, 0), cmax(0, 0); loopi(numverts) { vec2 px = vec2(c[i+1 < numverts ? i+1 : 0]).sub(c[i]); float len = px.squaredlen(); if(!len) continue; px.mul(1/sqrtf(len)); vec2 py(-px.y, px.x), pmin(0, 0), pmax(0, 0); if(numplanes >= 2 && (i == 0 || i >= 3)) px.neg(); loopj(numverts) { vec2 rj = vec2(c[j]).sub(c[i]), pj(rj.dot(px), rj.dot(py)); pmin.x = min(pmin.x, pj.x); pmin.y = min(pmin.y, pj.y); pmax.x = max(pmax.x, pj.x); pmax.y = max(pmax.y, pj.y); } float area = (pmax.x-pmin.x)*(pmax.y-pmin.y); if(area < carea) { carea = area; cx = px; cy = py; co = c[i]; cmin = pmin; cmax = pmax; } } int scale = int(min(cmax.x - cmin.x, cmax.y - cmin.y)); float lpu = 16.0f / float(lightlod && scale < (1 << lightlod) ? max(lightprecision / 2, 1) : lightprecision); int lw = clamp(int(ceil((cmax.x - cmin.x + 1)*lpu)), LM_MINW, LM_MAXW), lh = clamp(int(ceil((cmax.y - cmin.y + 1)*lpu)), LM_MINH, LM_MAXH); w->w = lw; w->h = lh; if(!alloclightmap(w)) return NO_SURFACE; vec2 cscale = vec2(cmax).sub(cmin).div(vec2(lw-1, lh-1)), comin = vec2(cx).mul(cmin.x).add(vec2(cy).mul(cmin.y)).add(co); loopi(numverts) { vec2 ri = vec2(c[i]).sub(comin); c[i] = vec2(ri.dot(cx)/cscale.x, ri.dot(cy)/cscale.y); } vec xstep1 = vec(v).mul(cx.y).add(vec(u).mul(cx.x)).mul(cscale.x), ystep1 = vec(v).mul(cy.y).add(vec(u).mul(cy.x)).mul(cscale.y), origin1 = vec(v).mul(comin.y).add(vec(u).mul(comin.x)).add(p[0]), xstep2 = xstep1, ystep2 = ystep1, origin2 = origin1; float side0 = LM_MAXW + 1, sidestep = 0; if(numplanes >= 2) { xstep2 = vec(t).mul(cx.y).add(vec(u).mul(cx.x)).mul(cscale.x); ystep2 = vec(t).mul(cy.y).add(vec(u).mul(cy.x)).mul(cscale.y); origin2 = vec(t).mul(comin.y).add(vec(u).mul(comin.x)).add(p[0]); if(cx.y) { side0 = comin.y/-(cx.y*cscale.x); sidestep = cy.y*cscale.y/-(cx.y*cscale.x); } else if(cy.y) { side0 = ceil(comin.y/-(cy.y*cscale.y))*(LM_MAXW + 1); sidestep = -(LM_MAXW + 1); if(cy.y < 0) { side0 = (LM_MAXW + 1) - side0; sidestep = -sidestep; } } else side0 = comin.y <= 0 ? LM_MAXW + 1 : -1; } int surftype = NO_SURFACE; if(preview) { surftype = previewlightmapalpha(w, lpu, origin1, xstep1, ystep1, origin2, xstep2, ystep2, side0, sidestep); } else { lerpvert lv[MAXFACEVERTS]; int numv = numverts; calclerpverts(c, n, lv, numv); if(!generatelightmap(w, lpu, lv, numv, origin1, xstep1, ystep1, origin2, xstep2, ystep2, side0, sidestep)) return NO_SURFACE; surftype = finishlightmap(w); } if(surftypew) texscale.x *= float(w->w - 1) / (lw - 1); if(lh != w->h) texscale.y *= float(w->h - 1) / (lh - 1); loopk(numverts) { litverts[k].u = ushort(floor(clamp(c[k].x*texscale.x, 0.0f, float(USHRT_MAX)))); litverts[k].v = ushort(floor(clamp(c[k].y*texscale.y, 0.0f, float(USHRT_MAX)))); } return surftype; } static void removelmalpha(lightmapworker *w) { if(!(w->type&LM_ALPHA)) return; for(uchar *dst = w->colorbuf, *src = w->colorbuf, *end = &src[w->w*w->h*4]; src < end; dst += 3, src += 4) { dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; } w->type &= ~LM_ALPHA; w->bpp = 3; w->lastlightmap->type = w->type; w->lastlightmap->bpp = w->bpp; } static lightmapinfo *setupsurfaces(lightmapworker *w, lightmaptask &task) { cube &c = *task.c; const ivec &co = task.o; int size = task.size, usefacemask = task.usefaces; w->curlightmaps = NULL; w->c = &c; surfaceinfo surfaces[6]; vertinfo litverts[6*2*MAXFACEVERTS]; int numlitverts = 0; memset(surfaces, 0, sizeof(surfaces)); loopi(6) { int usefaces = usefacemask&0xF; usefacemask >>= 4; if(!usefaces) { if(!c.ext) continue; surfaceinfo &surf = surfaces[i]; surf = c.ext->surfaces[i]; int numverts = surf.totalverts(); if(numverts) { memcpy(&litverts[numlitverts], c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)); surf.verts = numlitverts; numlitverts += numverts; } continue; } VSlot &vslot = lookupvslot(c.texture[i], false), *layer = vslot.layer && !(c.material&MAT_ALPHA) ? &lookupvslot(vslot.layer, false) : NULL; Shader *shader = vslot.slot->shader; int shadertype = shader->type; if(layer) shadertype |= layer->slot->shader->type; surfaceinfo &surf = surfaces[i]; vertinfo *curlitverts = &litverts[numlitverts]; int numverts = c.ext ? c.ext->surfaces[i].numverts&MAXFACEVERTS : 0; ivec mo(co); int msz = size, convex = 0; if(numverts) { vertinfo *verts = c.ext->verts() + c.ext->surfaces[i].verts; loopj(numverts) curlitverts[j].set(verts[j].getxyz()); if(c.merged&(1<slot = vslot.slot; w->vslot = &vslot; w->type = shader->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE; if(layer) w->type |= LM_ALPHA; w->bpp = w->type&LM_ALPHA ? 4 : 3; w->orient = i; w->rotate = vslot.rotation; int surftype = setupsurface(w, planes, numplanes, pos, n, numverts, curlitverts); switch(surftype) { case SURFACE_LIGHTMAP_BOTTOM: if((shader->type^layer->slot->shader->type)&SHADER_NORMALSLMS || (shader->type&SHADER_NORMALSLMS && vslot.rotation!=layer->rotation)) { freelightmap(w); break; } // fall through case SURFACE_LIGHTMAP_BLEND: case SURFACE_LIGHTMAP_TOP: { if(!(surf.numverts&MAXFACEVERTS)) { surf.verts = numlitverts; surf.numverts |= numverts; numlitverts += numverts; } w->lastlightmap->surface = i; if(surftype==SURFACE_LIGHTMAP_BLEND) surf.numverts |= LAYER_BLEND; else { surf.numverts |= (surftype==SURFACE_LIGHTMAP_BOTTOM ? LAYER_BOTTOM : LAYER_TOP); if(w->type&LM_ALPHA) removelmalpha(w); } if(surftype!=SURFACE_LIGHTMAP_BLEND) continue; if((shader->type^layer->slot->shader->type)&SHADER_NORMALSLMS || (shader->type&SHADER_NORMALSLMS && vslot.rotation!=layer->rotation)) break; continue; } case SURFACE_AMBIENT_BOTTOM: freelightmap(w); surf.numverts |= layer ? LAYER_BOTTOM : LAYER_TOP; continue; case SURFACE_AMBIENT_TOP: freelightmap(w); surf.numverts |= LAYER_TOP; continue; default: freelightmap(w); continue; } w->slot = layer->slot; w->vslot = layer; w->type = layer->slot->shader->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE; w->bpp = 3; w->rotate = layer->rotation; vertinfo *blendverts = surf.numverts&MAXFACEVERTS ? &curlitverts[numverts] : curlitverts; switch(setupsurface(w, planes, numplanes, pos, n, numverts, blendverts)) { case SURFACE_LIGHTMAP_TOP: { if(!(surf.numverts&MAXFACEVERTS)) { surf.verts = numlitverts; surf.numverts |= numverts; numlitverts += numverts; } else if(!(surf.numverts&LAYER_DUP)) { surf.numverts |= LAYER_DUP; loopk(numverts) { vertinfo &src = curlitverts[k]; vertinfo &dst = blendverts[k]; dst.setxyz(src.getxyz()); dst.norm = src.norm; } numlitverts += numverts; } surf.numverts |= LAYER_BOTTOM; w->lastlightmap->surface = i; break; } case SURFACE_AMBIENT_TOP: { freelightmap(w); surf.numverts |= LAYER_BOTTOM; break; } default: freelightmap(w); break; } } loopk(6) { surfaceinfo &surf = surfaces[k]; if(surf.used()) { cubeext *ext = c.ext && c.ext->maxverts >= numlitverts ? c.ext : growcubeext(c.ext, numlitverts); memcpy(ext->surfaces, surfaces, sizeof(ext->surfaces)); memcpy(ext->verts(), litverts, numlitverts*sizeof(vertinfo)); task.ext = ext; break; } } return w->curlightmaps ? w->curlightmaps : (lightmapinfo *)-1; } int lightmapworker::work(void *data) { lightmapworker *w = (lightmapworker *)data; SDL_LockMutex(tasklock); while(!w->doneworking) { if(allocidx < lightmaptasks[0].length()) { lightmaptask &t = lightmaptasks[0][allocidx++]; t.worker = w; SDL_UnlockMutex(tasklock); lightmapinfo *l = setupsurfaces(w, t); SDL_LockMutex(tasklock); t.lightmaps = l; packlightmaps(w); } else { if(packidx >= lightmaptasks[0].length()) SDL_CondSignal(emptycond); SDL_CondWait(fullcond, tasklock); } } SDL_UnlockMutex(tasklock); return 0; } static bool processtasks(bool finish = false) { if(tasklock) SDL_LockMutex(tasklock); while(finish || lightmaptasks[1].length()) { if(packidx >= lightmaptasks[0].length()) { if(lightmaptasks[1].empty()) break; lightmaptasks[0].setsize(0); lightmaptasks[0].move(lightmaptasks[1]); packidx = allocidx = 0; if(fullcond) SDL_CondBroadcast(fullcond); } else if(lightmapping > 1) { SDL_CondWaitTimeout(emptycond, tasklock, 250); CHECK_PROGRESS_LOCKED({ SDL_UnlockMutex(tasklock); return false; }, SDL_UnlockMutex(tasklock), SDL_LockMutex(tasklock)); } else { while(allocidx < lightmaptasks[0].length()) { lightmaptask &t = lightmaptasks[0][allocidx++]; t.worker = lightmapworkers[0]; t.lightmaps = setupsurfaces(lightmapworkers[0], t); packlightmaps(lightmapworkers[0]); CHECK_PROGRESS(return false); } } } if(tasklock) SDL_UnlockMutex(tasklock); return true; } static void generatelightmaps(cube *c, int cx, int cy, int cz, int size) { CHECK_PROGRESS(return); taskprogress++; loopi(8) { ivec o(i, cx, cy, cz, size); if(c[i].children) generatelightmaps(c[i].children, o.x, o.y, o.z, size >> 1); else if(!isempty(c[i])) { if(c[i].ext) { loopj(6) { surfaceinfo &surf = c[i].ext->surfaces[j]; if(surf.lmid[0] >= LMID_RESERVED || surf.lmid[1] >= LMID_RESERVED) goto nextcube; surf.clear(); } } int usefacemask = 0; loopj(6) if(c[i].texture[j] != DEFAULT_SKY && (!(c[i].merged&(1<surfaces[j].numverts&MAXFACEVERTS))) { usefacemask |= visibletris(c[i], j, o.x, o.y, o.z, size)<<(4*j); } if(usefacemask) { lightmaptask &t = lightmaptasks[1].add(); t.o = o; t.size = size; t.usefaces = usefacemask; t.c = &c[i]; t.ext = NULL; t.lightmaps = NULL; t.progress = taskprogress; if(lightmaptasks[1].length() >= MAXLIGHTMAPTASKS && !processtasks()) return; } } nextcube:; } } static bool previewblends(lightmapworker *w, cube &c, const ivec &co, int size) { if(isempty(c) || c.material&MAT_ALPHA) return false; int usefacemask = 0; loopi(6) if(c.texture[i] != DEFAULT_SKY && lookupvslot(c.texture[i], false).layer) usefacemask |= visibletris(c, i, co.x, co.y, co.z, size)<<(4*i); if(!usefacemask) return false; if(!setblendmaporigin(w->blendmapcache, co, size)) { if(!c.ext) return false; bool blends = false; loopi(6) if(c.ext->surfaces[i].numverts&LAYER_BOTTOM) { c.ext->surfaces[i].brighten(); blends = true; } return blends; } w->firstlightmap = w->lastlightmap = w->curlightmaps = NULL; w->bufstart = w->bufused = 0; w->c = &c; surfaceinfo surfaces[6]; vertinfo litverts[6*2*MAXFACEVERTS]; int numlitverts = 0; memcpy(surfaces, c.ext ? c.ext->surfaces : brightsurfaces, sizeof(surfaces)); loopi(6) { int usefaces = usefacemask&0xF; usefacemask >>= 4; if(!usefaces) { surfaceinfo &surf = surfaces[i]; int numverts = surf.totalverts(); if(numverts) { memcpy(&litverts[numlitverts], c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)); surf.verts = numlitverts; numlitverts += numverts; } continue; } VSlot &vslot = lookupvslot(c.texture[i], false), &layer = lookupvslot(vslot.layer, false); Shader *shader = vslot.slot->shader; int shadertype = shader->type | layer.slot->shader->type; vertinfo *curlitverts = &litverts[numlitverts]; int numverts = 0; ivec v[4]; genfaceverts(c, i, v); int convex = flataxisface(c, i) ? 0 : faceconvexity(v), order = usefaces&4 || convex < 0 ? 1 : 0; ivec vo = ivec(co).mask(0xFFF).shl(3); curlitverts[numverts++].set(v[order].mul(size).add(vo)); if(usefaces&1) curlitverts[numverts++].set(v[order+1].mul(size).add(vo)); curlitverts[numverts++].set(v[order+2].mul(size).add(vo)); if(usefaces&2) curlitverts[numverts++].set(v[(order+3)&3].mul(size).add(vo)); vec pos[4], n[4], po = ivec(co).mask(~0xFFF).tovec(); loopj(numverts) pos[j] = curlitverts[j].getxyz().tovec().mul(1.0f/8).add(po); plane planes[2]; int numplanes = 0; planes[numplanes++].toplane(pos[0], pos[1], pos[2]); if(numverts < 4 || !convex) loopk(numverts) n[k] = planes[0]; else { planes[numplanes++].toplane(pos[0], pos[2], pos[3]); vec avg = vec(planes[0]).add(planes[1]).normalize(); n[0] = avg; n[1] = planes[0]; n[2] = avg; for(int k = 3; k < numverts; k++) n[k] = planes[1]; } surfaceinfo &surf = surfaces[i]; w->slot = vslot.slot; w->vslot = &vslot; w->type = shadertype&SHADER_NORMALSLMS ? LM_BUMPMAP0|LM_ALPHA : LM_DIFFUSE|LM_ALPHA; w->bpp = 4; w->orient = i; w->rotate = vslot.rotation; int surftype = setupsurface(w, planes, numplanes, pos, n, numverts, curlitverts, true); switch(surftype) { case SURFACE_AMBIENT_TOP: surf = brightsurface; continue; case SURFACE_AMBIENT_BOTTOM: surf = brightbottomsurface; continue; case SURFACE_LIGHTMAP_BLEND: { if(surf.numverts == (LAYER_BLEND|numverts) && surf.lmid[0] == surf.lmid[1] && (surf.numverts&MAXFACEVERTS) == numverts && !memcmp(curlitverts, c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)) && lightmaps.inrange(surf.lmid[0]-LMID_RESERVED) && lightmaps[surf.lmid[0]-LMID_RESERVED].type==w->type) { vertinfo *oldverts = c.ext->verts() + surf.verts; layoutinfo layout; layout.w = w->w; layout.h = w->h; layout.x = (oldverts[0].x - curlitverts[0].x)/((USHRT_MAX+1)/LM_PACKW); layout.y = (oldverts[0].y - curlitverts[0].y)/((USHRT_MAX+1)/LM_PACKH); if(LM_PACKW - layout.x >= w->w && LM_PACKH - layout.y >= w->h) { layout.lmid = surf.lmid[0]; copylightmap(*w->lastlightmap, layout); updatelightmap(layout); surf.verts = numlitverts; numlitverts += numverts; continue; } } surf.verts = numlitverts; surf.numverts = LAYER_BLEND|numverts; numlitverts += numverts; layoutinfo layout; if(packlightmap(*w->lastlightmap, layout)) updatelightmap(layout); surf.lmid[0] = surf.lmid[1] = layout.lmid; ushort offsetx = layout.x*((USHRT_MAX+1)/LM_PACKW), offsety = layout.y*((USHRT_MAX+1)/LM_PACKH); loopk(numverts) { vertinfo &v = curlitverts[k]; v.u += offsetx; v.v += offsety; } continue; } } } setsurfaces(c, surfaces, litverts, numlitverts); return true; } static bool previewblends(lightmapworker *w, cube *c, const ivec &co, int size, const ivec &bo, const ivec &bs) { bool changed = false; loopoctabox(co, size, bo, bs) { ivec o(i, co.x, co.y, co.z, size); cubeext *ext = c[i].ext; if(ext && ext->va && ext->va->hasmerges) { changed = true; destroyva(ext->va); ext->va = NULL; invalidatemerges(c[i], co, size, true); } if(c[i].children ? previewblends(w, c[i].children, o, size/2, bo, bs) : previewblends(w, c[i], o, size)) { changed = true; ext = c[i].ext; if(ext && ext->va) { destroyva(ext->va); ext->va = NULL; } } } return changed; } void previewblends(const ivec &bo, const ivec &bs) { loadlayermasks(); if(lightmapworkers.empty()) lightmapworkers.add(new lightmapworker); lightmapworkers[0]->reset(); if(previewblends(lightmapworkers[0], worldroot, ivec(0, 0, 0), worldsize/2, bo, bs)) commitchanges(true); } void cleanuplightmaps() { loopv(lightmaps) { LightMap &lm = lightmaps[i]; lm.tex = lm.offsetx = lm.offsety = -1; } loopv(lightmaptexs) glDeleteTextures(1, &lightmaptexs[i].id); lightmaptexs.shrink(0); if(progresstex) { glDeleteTextures(1, &progresstex); progresstex = 0; } } void resetlightmaps(bool fullclean) { cleanuplightmaps(); lightmaps.shrink(0); compressed.clear(); clearlightcache(); if(fullclean) while(lightmapworkers.length()) delete lightmapworkers.pop(); } lightmapworker::lightmapworker() { buf = new uchar[LIGHTMAPBUFSIZE]; bufstart = bufused = 0; firstlightmap = lastlightmap = curlightmaps = NULL; ambient = new uchar[4*LM_MAXW*LM_MAXH]; blur = new uchar[4*LM_MAXW*LM_MAXH]; colordata = new vec[4*(LM_MAXW+1)*(LM_MAXH+1)]; raydata = new vec[LM_MAXW*LM_MAXH]; shadowraycache = newshadowraycache(); blendmapcache = newblendmapcache(); needspace = doneworking = false; spacecond = NULL; thread = NULL; } lightmapworker::~lightmapworker() { cleanupthread(); delete[] buf; delete[] ambient; delete[] blur; delete[] colordata; delete[] raydata; freeshadowraycache(shadowraycache); freeblendmapcache(blendmapcache); } void lightmapworker::cleanupthread() { if(spacecond) { SDL_DestroyCond(spacecond); spacecond = NULL; } thread = NULL; } void lightmapworker::reset() { bufstart = bufused = 0; firstlightmap = lastlightmap = curlightmaps = NULL; needspace = doneworking = false; resetshadowraycache(shadowraycache); } bool lightmapworker::setupthread() { if(!spacecond) spacecond = SDL_CreateCond(); if(!spacecond) return false; thread = SDL_CreateThread(work, this); return thread!=NULL; } static Uint32 calclighttimer(Uint32 interval, void *param) { check_calclight_progress = true; return interval; } bool setlightmapquality(int quality) { switch(quality) { case 1: lmshadows = 2; lmaa = 3; lerptjoints = 1; break; case 0: lmshadows = lmshadows_; lmaa = lmaa_; lerptjoints = lerptjoints_; break; case -1: lmshadows = 1; lmaa = 0; lerptjoints = 0; break; default: return false; } return true; } VARP(lightthreads, 1, 1, 16); #define ALLOCLOCK(name, init) { if(lightmapping > 1) name = init(); if(!name) lightmapping = 1; } #define FREELOCK(name, destroy) { if(name) { destroy(name); name = NULL; } } static void cleanuplocks() { FREELOCK(lightlock, SDL_DestroyMutex); FREELOCK(tasklock, SDL_DestroyMutex); FREELOCK(fullcond, SDL_DestroyCond); FREELOCK(emptycond, SDL_DestroyCond); } static void setupthreads() { loopi(2) lightmaptasks[i].setsize(0); lightmapexts.setsize(0); packidx = allocidx = 0; lightmapping = lightthreads; if(lightmapping > 1) { ALLOCLOCK(lightlock, SDL_CreateMutex); ALLOCLOCK(tasklock, SDL_CreateMutex); ALLOCLOCK(fullcond, SDL_CreateCond); ALLOCLOCK(emptycond, SDL_CreateCond); } while(lightmapworkers.length() < lightmapping) lightmapworkers.add(new lightmapworker); loopi(lightmapping) { lightmapworker *w = lightmapworkers[i]; w->reset(); if(lightmapping <= 1 || w->setupthread()) continue; w->cleanupthread(); lightmapping = i >= 1 ? max(i, 2) : 1; break; } if(lightmapping <= 1) cleanuplocks(); } static void cleanupthreads() { processtasks(true); if(lightmapping > 1) { SDL_LockMutex(tasklock); loopv(lightmapworkers) lightmapworkers[i]->doneworking = true; SDL_CondBroadcast(fullcond); loopv(lightmapworkers) { lightmapworker *w = lightmapworkers[i]; if(w->needspace && w->spacecond) SDL_CondSignal(w->spacecond); } SDL_UnlockMutex(tasklock); loopv(lightmapworkers) { lightmapworker *w = lightmapworkers[i]; if(w->thread) SDL_WaitThread(w->thread, NULL); } } loopv(lightmapexts) { lightmapext &e = lightmapexts[i]; setcubeext(*e.c, e.ext); } loopv(lightmapworkers) lightmapworkers[i]->cleanupthread(); cleanuplocks(); lightmapping = 0; } void calclight(int *quality) { if(!setlightmapquality(*quality)) { conoutf(CON_ERROR, "valid range for calclight quality is -1..1"); return; } extern string mname; defformatstring(capt)("Sandbox %s: %s - Calculating Lightmaps...", version, mname); SDL_WM_SetCaption(capt, NULL); renderbackground("computing lightmaps... (esc to abort)"); mpremip(true); optimizeblendmap(); loadlayermasks(); if(lightthreads > 1) preloadusedmapmodels(false, true); resetlightmaps(false); clearsurfaces(worldroot); taskprogress = progress = 0; progresstexticks = 0; progresslightmap = -1; calclight_canceled = false; check_calclight_progress = false; SDL_TimerID timer = SDL_AddTimer(250, calclighttimer, NULL); Uint32 start = SDL_GetTicks(); calcnormals(lerptjoints > 0); show_calclight_progress(); setupthreads(); generatelightmaps(worldroot, 0, 0, 0, worldsize >> 1); cleanupthreads(); clearnormals(); Uint32 end = SDL_GetTicks(); if(timer) SDL_RemoveTimer(timer); uint total = 0, lumels = 0; loopv(lightmaps) { insertunlit(i); if(!editmode) lightmaps[i].finalize(); total += lightmaps[i].lightmaps; lumels += lightmaps[i].lumels; } if(!editmode) compressed.clear(); initlights(); renderbackground("lighting done..."); allchanged(); if(calclight_canceled) conoutf("calclight aborted"); else conoutf("generated %d lightmaps using %.2f%% of %d textures (%.1f seconds)", total, lightmaps.length() ? lumels * 100.0 / (lightmaps.length() * LM_PACKW * LM_PACKH) : 0, lightmaps.length(), (end - start) / 1000.0f); game::setwindowcaption(); } COMMAND(calclight, "i"); VAR(patchnormals, 0, 0, 1); void patchlight(int *quality) { if(noedit(true)) return; if(!setlightmapquality(*quality)) { conoutf(CON_ERROR, "valid range for patchlight quality is -1..1"); return; } extern string mname; defformatstring(capt)("Sandbox %s: %s - Patching Lightmaps...", version, mname); SDL_WM_SetCaption(capt, NULL); renderbackground("patching lightmaps... (esc to abort)"); loadlayermasks(); if(lightthreads > 1) preloadusedmapmodels(false, true); cleanuplightmaps(); taskprogress = progress = 0; progresstexticks = 0; progresslightmap = -1; int total = 0, lumels = 0; loopv(lightmaps) { if((lightmaps[i].type&LM_TYPE) != LM_BUMPMAP1) progresslightmap = i; total -= lightmaps[i].lightmaps; lumels -= lightmaps[i].lumels; } calclight_canceled = false; check_calclight_progress = false; SDL_TimerID timer = SDL_AddTimer(250, calclighttimer, NULL); if(patchnormals) renderprogress(0, "computing normals..."); Uint32 start = SDL_GetTicks(); if(patchnormals) calcnormals(lerptjoints > 0); show_calclight_progress(); setupthreads(); generatelightmaps(worldroot, 0, 0, 0, worldsize >> 1); cleanupthreads(); if(patchnormals) clearnormals(); Uint32 end = SDL_GetTicks(); if(timer) SDL_RemoveTimer(timer); loopv(lightmaps) { total += lightmaps[i].lightmaps; lumels += lightmaps[i].lumels; } initlights(); renderbackground("lighting done..."); allchanged(); if(calclight_canceled) conoutf("patchlight aborted"); else conoutf("patched %d lightmaps using %.2f%% of %d textures (%.1f seconds)", total, lightmaps.length() ? lumels * 100 / (lightmaps.length() * LM_PACKW * LM_PACKH) : 0, lightmaps.length(), (end - start) / 1000.0f); game::setwindowcaption(); } COMMAND(patchlight, "i"); void clearlightmaps() { if(noedit(true)) return; renderprogress(0, "clearing lightmaps..."); resetlightmaps(false); clearsurfaces(worldroot); initlights(); allchanged(); } COMMAND(clearlightmaps, ""); void setfullbrightlevel(int fullbrightlevel) { if(lightmaptexs.length() > LMID_BRIGHT) { uchar bright[3] = { fullbrightlevel, fullbrightlevel, fullbrightlevel }; createtexture(lightmaptexs[LMID_BRIGHT].id, 1, 1, bright, 0, 1); } initlights(); } VARF(fullbright, 0, 0, 1, if(lightmaptexs.length()) initlights()); VARF(fullbrightlevel, 0, 128, 255, setfullbrightlevel(fullbrightlevel)); vector lightmaptexs; static void rotatenormals(LightMap &lmlv, int x, int y, int w, int h, int rotate) { bool flipx = rotate>=2 && rotate<=4, flipy = (rotate>=1 && rotate<=2) || rotate==5, swapxy = (rotate&5)==1; uchar *lv = lmlv.data + 3*(y*LM_PACKW + x); int stride = 3*(LM_PACKW-w); loopi(h) { loopj(w) { if(flipx) lv[0] = 255 - lv[0]; if(flipy) lv[1] = 255 - lv[1]; if(swapxy) swap(lv[0], lv[1]); lv += 3; } lv += stride; } } static void rotatenormals(cube *c) { loopi(8) { cube &ch = c[i]; if(ch.children) { rotatenormals(ch.children); continue; } else if(!ch.ext) continue; loopj(6) if(lightmaps.inrange(ch.ext->surfaces[j].lmid[0]+1-LMID_RESERVED)) { VSlot &vslot = lookupvslot(ch.texture[j], false); if(!vslot.rotation) continue; surfaceinfo &surface = ch.ext->surfaces[j]; int numverts = surface.numverts&MAXFACEVERTS; if(!numverts) continue; LightMap &lmlv = lightmaps[surface.lmid[0]+1-LMID_RESERVED]; if((lmlv.type&LM_TYPE)!=LM_BUMPMAP1) continue; ushort x1 = USHRT_MAX, y1 = USHRT_MAX, x2 = 0, y2 = 0; vertinfo *verts = ch.ext->verts() + surface.verts; loopk(numverts) { vertinfo &v = verts[k]; x1 = min(x1, v.u); y1 = min(y1, v.u); x2 = max(x2, v.u); y2 = max(y2, v.v); } if(x1 > x2 || y1 > y2) continue; x1 /= (USHRT_MAX+1)/LM_PACKW; y1 /= (USHRT_MAX+1)/LM_PACKH; x2 /= (USHRT_MAX+1)/LM_PACKW; y2 /= (USHRT_MAX+1)/LM_PACKH; rotatenormals(lmlv, x1, y1, x2-x1, y1-y1, vslot.rotation < 4 ? 4-vslot.rotation : vslot.rotation); } } } void fixlightmapnormals() { rotatenormals(worldroot); } void fixrotatedlightmaps(cube &c, const ivec &co, int size) { if(c.children) { loopi(8) fixrotatedlightmaps(c.children[i], ivec(i, co.x, co.y, co.z, size>>1), size>>1); return; } if(!c.ext) return; loopi(6) { if(c.merged&(1<surfaces[i]; int numverts = surf.numverts&MAXFACEVERTS; if(numverts!=4 || (surf.lmid[0] < LMID_RESERVED && surf.lmid[1] < LMID_RESERVED)) continue; vertinfo *verts = c.ext->verts() + surf.verts; int vis = visibletris(c, i, co.x, co.y, co.z, size); if(!vis || vis==3) continue; if((verts[0].u != verts[1].u || verts[0].v != verts[1].v) && (verts[0].u != verts[3].u || verts[0].v != verts[3].v) && (verts[2].u != verts[1].u || verts[2].v != verts[1].v) && (verts[2].u != verts[3].u || verts[2].v != verts[3].v)) continue; if(vis&4) { vertinfo tmp = verts[0]; verts[0].x = verts[1].x; verts[0].y = verts[1].y; verts[0].z = verts[1].z; verts[1].x = verts[2].x; verts[1].y = verts[2].y; verts[1].z = verts[2].z; verts[2].x = verts[3].x; verts[2].y = verts[3].y; verts[2].z = verts[3].z; verts[3].x = tmp.x; verts[3].y = tmp.y; verts[3].z = tmp.z; if(surf.numverts&LAYER_DUP) loopk(4) { vertinfo &v = verts[k], &b = verts[k+4]; b.x = v.x; b.y = v.y; b.z = v.z; } } surf.numverts = (surf.numverts & ~MAXFACEVERTS) | 3; if(vis&2) { verts[1] = verts[2]; verts[2] = verts[3]; if(surf.numverts&LAYER_DUP) { verts[3] = verts[4]; verts[4] = verts[6]; verts[5] = verts[7]; } } else if(surf.numverts&LAYER_DUP) { verts[3] = verts[4]; verts[4] = verts[5]; verts[5] = verts[6]; } } } void fixrotatedlightmaps() { loopi(8) fixrotatedlightmaps(worldroot[i], ivec(i, 0, 0, 0, worldsize>>1), worldsize>>1); } static void convertlightmap(LightMap &lmc, LightMap &lmlv, uchar *dst, size_t stride) { const uchar *c = lmc.data; const bvec *lv = (const bvec *)lmlv.data; loopi(LM_PACKH) { uchar *dstrow = dst; loopj(LM_PACKW) { int z = int(lv->z)*2 - 255, r = (int(c[0]) * z) / 255, g = (int(c[1]) * z) / 255, b = (int(c[2]) * z) / 255; dstrow[0] = max(r, int(ambientcolor[0])); dstrow[1] = max(g, int(ambientcolor[1])); dstrow[2] = max(b, int(ambientcolor[2])); if(lmc.bpp==4) dstrow[3] = c[3]; c += lmc.bpp; lv++; dstrow += lmc.bpp; } dst += stride; } } static void copylightmap(LightMap &lm, uchar *dst, size_t stride) { const uchar *c = lm.data; loopi(LM_PACKH) { memcpy(dst, c, lm.bpp*LM_PACKW); c += lm.bpp*LM_PACKW; dst += stride; } } VARF(convertlms, 0, 1, 1, { cleanuplightmaps(); initlights(); allchanged(); }); void genreservedlightmaptexs() { while(lightmaptexs.length() < LMID_RESERVED) { LightMapTexture &tex = lightmaptexs.add(); tex.type = renderpath != R_FIXEDFUNCTION && lightmaptexs.length()&1 ? LM_DIFFUSE : LM_BUMPMAP1; glGenTextures(1, &tex.id); } uchar unlit[3] = { ambientcolor[0], ambientcolor[1], ambientcolor[2] }; createtexture(lightmaptexs[LMID_AMBIENT].id, 1, 1, unlit, 0, 1); bvec front(128, 128, 255); createtexture(lightmaptexs[LMID_AMBIENT1].id, 1, 1, &front, 0, 1); uchar bright[3] = { fullbrightlevel, fullbrightlevel, fullbrightlevel }; createtexture(lightmaptexs[LMID_BRIGHT].id, 1, 1, bright, 0, 1); createtexture(lightmaptexs[LMID_BRIGHT1].id, 1, 1, &front, 0, 1); uchar dark[3] = { 0, 0, 0 }; createtexture(lightmaptexs[LMID_DARK].id, 1, 1, dark, 0, 1); createtexture(lightmaptexs[LMID_DARK1].id, 1, 1, &front, 0, 1); } static void findunlit(int i) { LightMap &lm = lightmaps[i]; if(lm.unlitx>=0) return; else if((lm.type&LM_TYPE)==LM_BUMPMAP0) { if(i+1>=lightmaps.length() || (lightmaps[i+1].type&LM_TYPE)!=LM_BUMPMAP1) return; } else if((lm.type&LM_TYPE)!=LM_DIFFUSE) return; uchar *data = lm.data; loop(y, 2) loop(x, LM_PACKW) { if(!data[0] && !data[1] && !data[2]) { memcpy(data, ambientcolor.v, 3); if((lm.type&LM_TYPE)==LM_BUMPMAP0) ((bvec *)lightmaps[i+1].data)[y*LM_PACKW + x] = bvec(128, 128, 255); lm.unlitx = x; lm.unlity = y; return; } if(data[0]==ambientcolor[0] && data[1]==ambientcolor[1] && data[2]==ambientcolor[2]) { if((lm.type&LM_TYPE)!=LM_BUMPMAP0 || ((bvec *)lightmaps[i+1].data)[y*LM_PACKW + x] == bvec(128, 128, 255)) { lm.unlitx = x; lm.unlity = y; return; } } data += lm.bpp; } } VARF(roundlightmaptex, 0, 4, 16, { cleanuplightmaps(); initlights(); allchanged(); }); VARF(batchlightmaps, 0, 4, 256, { cleanuplightmaps(); initlights(); allchanged(); }); void genlightmaptexs(int flagmask, int flagval) { if(lightmaptexs.length() < LMID_RESERVED) genreservedlightmaptexs(); int remaining[3] = { 0, 0, 0 }, total = 0; loopv(lightmaps) { LightMap &lm = lightmaps[i]; if(lm.tex >= 0 || (lm.type&flagmask)!=flagval) continue; int type = lm.type&LM_TYPE; remaining[type]++; total++; if(lm.unlitx < 0) findunlit(i); } if(renderpath==R_FIXEDFUNCTION) { remaining[LM_DIFFUSE] += remaining[LM_BUMPMAP0]; remaining[LM_BUMPMAP0] = remaining[LM_BUMPMAP1] = 0; } int sizelimit = (maxtexsize ? min(maxtexsize, hwtexsize) : hwtexsize)/max(LM_PACKW, LM_PACKH); sizelimit = min(batchlightmaps, sizelimit*sizelimit); while(total) { int type = LM_DIFFUSE; LightMap *firstlm = NULL; loopv(lightmaps) { LightMap &lm = lightmaps[i]; if(lm.tex >= 0 || (lm.type&flagmask) != flagval) continue; if(renderpath != R_FIXEDFUNCTION) type = lm.type&LM_TYPE; else if((lm.type&LM_TYPE) == LM_BUMPMAP1) continue; firstlm = &lm; break; } if(!firstlm) break; int used = 0, uselimit = min(remaining[type], sizelimit); do used++; while((1<type; tex.w = LM_PACKW<<((used+1)/2); tex.h = LM_PACKH<<(used/2); int bpp = firstlm->bpp; uchar *data = used || (renderpath == R_FIXEDFUNCTION && (firstlm->type&LM_TYPE) == LM_BUMPMAP0 && convertlms) ? new uchar[bpp*tex.w*tex.h] : NULL; int offsetx = 0, offsety = 0; loopv(lightmaps) { LightMap &lm = lightmaps[i]; if(lm.tex >= 0 || (lm.type&flagmask) != flagval || (renderpath==R_FIXEDFUNCTION ? (lm.type&LM_TYPE) == LM_BUMPMAP1 : (lm.type&LM_TYPE) != type)) continue; lm.tex = lightmaptexs.length()-1; lm.offsetx = offsetx; lm.offsety = offsety; if(tex.unlitx < 0 && lm.unlitx >= 0) { tex.unlitx = offsetx + lm.unlitx; tex.unlity = offsety + lm.unlity; } if(data) { if(renderpath == R_FIXEDFUNCTION && (lm.type&LM_TYPE) == LM_BUMPMAP0 && convertlms) convertlightmap(lm, lightmaps[i+1], &data[bpp*(offsety*tex.w + offsetx)], bpp*tex.w); else copylightmap(lm, &data[bpp*(offsety*tex.w + offsetx)], bpp*tex.w); } offsetx += LM_PACKW; if(offsetx >= tex.w) { offsetx = 0; offsety += LM_PACKH; } if(offsety >= tex.h) break; } glGenTextures(1, &tex.id); createtexture(tex.id, tex.w, tex.h, data ? data : firstlm->data, 3, 1, bpp==4 ? GL_RGBA : GL_RGB); if(data) delete[] data; } } bool brightengeom = false; void clearlights() { clearlightcache(); const vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; e.light.color = vec(1, 1, 1); e.light.dir = vec(0, 0, 1); } if(nolights) return; genlightmaptexs(LM_ALPHA, 0); genlightmaptexs(LM_ALPHA, LM_ALPHA); brightengeom = true; } void lightent(extentity &e, float height) { if(e.type==ET_LIGHT) return; float ambient = 0.0f; if(e.type==ET_MAPMODEL) { model *m = loadmodel(NULL, e.attr[1]); if(m) height = m->above()*0.75f; } else if(e.type>=ET_GAMESPECIFIC) ambient = 0.4f; vec target(e.o.x, e.o.y, e.o.z + height); lightreaching(target, e.light.color, e.light.dir, false, &e, ambient); } void updateentlighting() { const vector &ents = entities::getents(); loopv(ents) lightent(*ents[i]); } void initlights() { if(nolights || fullbright || lightmaps.empty()) { clearlights(); return; } clearlightcache(); updateentlighting(); genlightmaptexs(LM_ALPHA, 0); genlightmaptexs(LM_ALPHA, LM_ALPHA); brightengeom = false; } static inline void fastskylight(const vec &o, float tolerance, uchar *skylight, int flags = RAY_ALPHAPOLY, extentity *t = NULL, bool fast = false) { flags |= RAY_SHADOW; if(skytexturelight) flags |= RAY_SKIPSKY; if(fast) { static const vec ray(0, 0, 1); if(shadowray(vec(ray).mul(tolerance).add(o), ray, 1e16f, flags, t)>1e15f) memcpy(skylight, skylightcolor.v, 3); else memcpy(skylight, ambientcolor.v, 3); } else { static const vec rays[5] = { vec(cosf(66*RAD)*cosf(65*RAD), sinf(66*RAD)*cosf(65*RAD), sinf(65*RAD)), vec(cosf(156*RAD)*cosf(65*RAD), sinf(156*RAD)*cosf(65*RAD), sinf(65*RAD)), vec(cosf(246*RAD)*cosf(65*RAD), sinf(246*RAD)*cosf(65*RAD), sinf(65*RAD)), vec(cosf(336*RAD)*cosf(65*RAD), sinf(336*RAD)*cosf(65*RAD), sinf(65*RAD)), vec(0, 0, 1), }; int hit = 0; loopi(5) if(shadowray(vec(rays[i]).mul(tolerance).add(o), rays[i], 1e16f, flags, t)>1e15f) hit++; loopk(3) skylight[k] = uchar(ambientcolor[k] + (max(skylightcolor[k], ambientcolor[k]) - ambientcolor[k])*hit/5.0f); } } void lightreaching(const vec &target, vec &color, vec &dir, bool fast, extentity *t, float ambient) { if(nolights || fullbright || lightmaps.empty()) { color = vec(1, 1, 1); dir = vec(0, 0, 1); return; } color = dir = vec(0, 0, 0); const vector &ents = entities::getents(); const vector &lights = checklightcache(int(target.x), int(target.y)); loopv(lights) { extentity &e = *ents[lights[i]]; if(e.type != ET_LIGHT) continue; vec ray(target); ray.sub(e.o); float mag = ray.magnitude(); if(e.attr[0] && mag >= float(e.attr[0])) continue; ray.div(mag); if(shadowray(e.o, ray, mag, RAY_SHADOW | RAY_POLY, t) < mag) continue; float intensity = 1; if(e.attr[0]) intensity -= mag / float(e.attr[0]); if(e.attached && e.attached->type==ET_SPOTLIGHT) { vec spot(vec(e.attached->o).sub(e.o).normalize()); float maxatten = 1-cosf(max(1, min(90, int(e.attached->attr[0])))*RAD); float spotatten = 1-(1-ray.dot(spot))/maxatten; if(spotatten<=0) continue; intensity *= spotatten; } //if(target==player->o) //{ // conoutf(CON_DEBUG, "%d - %f %f", i, intensity, mag); //} color.add(vec(e.attr[1], e.attr[2], e.attr[3]).mul(intensity/255)); intensity *= e.attr[1]*e.attr[2]*e.attr[3]; if(fabs(mag)<1e-3) dir.add(vec(0, 0, 1)); else dir.add(vec(e.o).sub(target).mul(intensity/mag)); } if(sunlight && shadowray(target, sunlightdir, 1e16f, RAY_SHADOW | RAY_POLY | (skytexturelight ? RAY_SKIPSKY : 0), t) > 1e15f) { color.add(vec(sunlightcolor.x, sunlightcolor.y, sunlightcolor.z).mul(sunlightscale/255)); dir.add(sunlightdir); } if(hasskylight()) { uchar skylight[3]; if(t) calcskylight(NULL, target, vec(0, 0, 0), 0.5f, skylight, RAY_POLY, t); else fastskylight(target, 0.5f, skylight, RAY_POLY, t, fast); loopk(3) color[k] = min(1.5f, max(max(skylight[k]/255.0f, ambient), color[k])); } else loopk(3) color[k] = min(1.5f, max(max(ambientcolor[k]/255.0f, ambient), color[k])); if(dir.iszero()) dir = vec(0, 0, 1); else dir.normalize(); } entity *brightestlight(const vec &target, const vec &dir) { if(sunlight && sunlightdir.dot(dir) > 0 && shadowray(target, sunlightdir, 1e16f, RAY_SHADOW | RAY_POLY | (skytexturelight ? RAY_SKIPSKY : 0)) > 1e15f) return &sunlightent; const vector &ents = entities::getents(); const vector &lights = checklightcache(int(target.x), int(target.y)); extentity *brightest = NULL; float bintensity = 0; loopv(lights) { extentity &e = *ents[lights[i]]; if(e.type != ET_LIGHT || vec(e.o).sub(target).dot(dir)<0) continue; vec ray(target); ray.sub(e.o); float mag = ray.magnitude(); if(e.attr[0] && mag >= float(e.attr[0])) continue; ray.div(mag); if(shadowray(e.o, ray, mag, RAY_SHADOW | RAY_POLY) < mag) continue; float intensity = 1; if(e.attr[0]) intensity -= mag / float(e.attr[0]); if(e.attached && e.attached->type==ET_SPOTLIGHT) { vec spot(vec(e.attached->o).sub(e.o).normalize()); float maxatten = 1-cosf(max(1, min(90, int(e.attached->attr[0])))*RAD); float spotatten = 1-(1-ray.dot(spot))/maxatten; if(spotatten<=0) continue; intensity *= spotatten; } if(!brightest || intensity > bintensity) { brightest = &e; bintensity = intensity; } } return brightest; } void dumplms() { loopv(lightmaps) { ImageData temp(LM_PACKW, LM_PACKH, lightmaps[i].bpp, lightmaps[i].data); const char *map = game::getclientmap(), *name = strrchr(map, '/'); defformatstring(buf)("lightmap_%s_%d.png", name ? name+1 : map, i); savepng(buf, temp, true); } } COMMAND(dumplms, ""); sandboxgamemaker-2.7.1+dfsg/src/engine/smd.h0000664000175000017500000004431211514736556020663 0ustar showardshowardstruct smd; struct smdbone { string name; int parent; smdbone() : parent(-1) { name[0] = '\0'; } }; struct smd : skelmodel, skelloader { smd(const char *name) : skelmodel(name) {} static const char *formatname() { return "smd"; } int type() const { return MDL_SMD; } struct smdmesh : skelmesh { }; struct smdmeshgroup : skelmeshgroup { smdmeshgroup() { } bool skipcomment(char *&curbuf) { while(*curbuf && isspace(*curbuf)) curbuf++; switch(*curbuf) { case '#': case ';': case '\r': case '\n': case '\0': return true; case '/': if(curbuf[1] == '/') return true; break; } return false; } void skipsection(stream *f, char *buf, size_t bufsize) { while(f->getline(buf, bufsize)) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(!strncmp(curbuf, "end", 3)) break; } } void readname(char *&curbuf, char *name, size_t namesize) { char *curname = name; while(*curbuf && isspace(*curbuf)) curbuf++; bool allowspace = false; if(*curbuf == '"') { curbuf++; allowspace = true; } while(*curbuf) { char c = *curbuf++; if(c == '"') break; if(isspace(c) && !allowspace) break; if(curname < &name[namesize-1]) *curname++ = c; } *curname = '\0'; } void readnodes(stream *f, char *buf, size_t bufsize, vector &bones) { while(f->getline(buf, bufsize)) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(!strncmp(curbuf, "end", 3)) break; int id = strtol(curbuf, &curbuf, 10); string name; readname(curbuf, name, sizeof(name)); int parent = strtol(curbuf, &curbuf, 10); if(id < 0 || id > 255 || parent > 255 || !name[0]) continue; while(!bones.inrange(id)) bones.add(); smdbone &bone = bones[id]; copystring(bone.name, name); bone.parent = parent; } } void readmaterial(char *&curbuf, char *name, size_t namesize) { char *curname = name; while(*curbuf && isspace(*curbuf)) curbuf++; while(*curbuf) { char c = *curbuf++; if(isspace(c)) break; if(c == '.') { while(*curbuf && !isspace(*curbuf)) curbuf++; break; } if(curname < &name[namesize-1]) *curname++ = c; } *curname = '\0'; } struct smdmeshdata { smdmesh *mesh; vector verts; vector tris; void finalize() { if(verts.empty() || tris.empty()) return; vert *mverts = new vert[mesh->numverts + verts.length()]; if(mesh->numverts) { memcpy(mverts, mesh->verts, mesh->numverts*sizeof(vert)); delete[] mesh->verts; } memcpy(&mverts[mesh->numverts], verts.getbuf(), verts.length()*sizeof(vert)); mesh->numverts += verts.length(); mesh->verts = mverts; tri *mtris = new tri[mesh->numtris + tris.length()]; if(mesh->numtris) { memcpy(mtris, mesh->tris, mesh->numtris*sizeof(tri)); delete[] mesh->tris; } memcpy(&mtris[mesh->numtris], tris.getbuf(), tris.length()*sizeof(tri)); mesh->numtris += tris.length(); mesh->tris = mtris; } }; struct smdvertkey : vert { smdmeshdata *mesh; smdvertkey(smdmeshdata *mesh) : mesh(mesh) {} }; void readtriangles(stream *f, char *buf, size_t bufsize) { smdmeshdata *curmesh = NULL; hashtable materials(1<<6); hashset verts(1<<12); while(f->getline(buf, bufsize)) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(!strncmp(curbuf, "end", 3)) break; string material; readmaterial(curbuf, material, sizeof(material)); if(!curmesh || strcmp(curmesh->mesh->name, material)) { curmesh = materials.access(material); if(!curmesh) { smdmesh *m = new smdmesh; m->group = this; m->name = newstring(material); meshes.add(m); curmesh = &materials[m->name]; curmesh->mesh = m; } } tri curtri; loopi(3) { char *curbuf; do { if(!f->getline(buf, bufsize)) goto endsection; curbuf = buf; } while(skipcomment(curbuf)); smdvertkey key(curmesh); int parent = -1, numlinks = 0, len = 0; if(sscanf(curbuf, " %d %f %f %f %f %f %f %f %f %d%n", &parent, &key.pos.x, &key.pos.y, &key.pos.z, &key.norm.x, &key.norm.y, &key.norm.z, &key.u, &key.v, &numlinks, &len) < 9) goto endsection; curbuf += len; key.pos.y = -key.pos.y; key.norm.y = -key.norm.y; key.v = 1 - key.v; blendcombo c; int sorted = 0; float pweight = 0, tweight = 0; for(; numlinks > 0; numlinks--) { int bone = -1, len = 0; float weight = 0; if(sscanf(curbuf, " %d %f%n", &bone, &weight, &len) < 2) break; curbuf += len; tweight += weight; if(bone == parent) pweight += weight; else sorted = c.addweight(sorted, weight, bone); } if(tweight < 1) pweight += 1 - tweight; if(pweight > 0) sorted = c.addweight(sorted, pweight, parent); c.finalize(sorted); key.blend = curmesh->mesh->addblendcombo(c); int index = verts.access(key, curmesh->verts.length()); if(index == curmesh->verts.length()) curmesh->verts.add(key); curtri.vert[2-i] = index; } curmesh->tris.add(curtri); } endsection: enumerate(materials, smdmeshdata, data, data.finalize()); } void readskeleton(stream *f, char *buf, size_t bufsize) { int frame = -1; while(f->getline(buf, bufsize)) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(sscanf(curbuf, " time %d", &frame) == 1) continue; else if(!strncmp(curbuf, "end", 3)) break; else if(frame != 0) continue; int bone; vec pos, rot; if(sscanf(curbuf, " %d %f %f %f %f %f %f", &bone, &pos.x, &pos.y, &pos.z, &rot.x, &rot.y, &rot.z) != 7) continue; if(bone < 0 || bone >= skel->numbones) continue; rot.x = -rot.x; rot.z = -rot.z; float cx = cosf(rot.x/2), sx = sinf(rot.x/2), cy = cosf(rot.y/2), sy = sinf(rot.y/2), cz = cosf(rot.z/2), sz = sinf(rot.z/2); pos.y = -pos.y; dualquat dq(quat(sx*cy*cz - cx*sy*sz, cx*sy*cz + sx*cy*sz, cx*cy*sz - sx*sy*cz, cx*cy*cz + sx*sy*sz), pos); boneinfo &b = skel->bones[bone]; if(b.parent < 0) b.base = dq; else b.base.mul(skel->bones[b.parent].base, dq); (b.invbase = b.base).invert(); } } bool loadmesh(const char *filename) { stream *f = openfile(filename, "r"); if(!f) return false; char buf[512]; int version = -1; while(f->getline(buf, sizeof(buf))) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(sscanf(curbuf, " version %d", &version) == 1) { if(version != 1) { delete f; return false; } } else if(!strncmp(curbuf, "nodes", 5)) { if(skel->numbones > 0) { skipsection(f, buf, sizeof(buf)); continue; } vector bones; readnodes(f, buf, sizeof(buf), bones); if(bones.empty()) continue; skel->numbones = bones.length(); skel->bones = new boneinfo[skel->numbones]; loopv(bones) { boneinfo &dst = skel->bones[i]; smdbone &src = bones[i]; dst.name = newstring(src.name); dst.parent = src.parent; } skel->linkchildren(); } else if(!strncmp(curbuf, "triangles", 9)) readtriangles(f, buf, sizeof(buf)); else if(!strncmp(curbuf, "skeleton", 8)) { if(skel->shared > 1) skipsection(f, buf, sizeof(buf)); else readskeleton(f, buf, sizeof(buf)); } else if(!strncmp(curbuf, "vertexanimation", 15)) skipsection(f, buf, sizeof(buf)); } sortblendcombos(); delete f; return true; } int readframes(stream *f, char *buf, size_t bufsize, vector &animbones) { int frame = -1, numframes = 0, lastbone = skel->numbones; while(f->getline(buf, bufsize)) { char *curbuf = buf; if(skipcomment(curbuf)) continue; int nextframe = -1; if(sscanf(curbuf, " time %d", &nextframe) == 1) { for(; lastbone < skel->numbones; lastbone++) animbones[frame*skel->numbones + lastbone] = animbones[lastbone]; if(nextframe >= numframes) { databuf framebones = animbones.reserve(skel->numbones * (nextframe + 1 - numframes)); loopi(nextframe - numframes) framebones.put(animbones.getbuf(), skel->numbones); animbones.addbuf(framebones); animbones.advance(skel->numbones); numframes = nextframe + 1; } frame = nextframe; lastbone = 0; continue; } else if(!strncmp(curbuf, "end", 3)) break; int bone; vec pos, rot; if(sscanf(curbuf, " %d %f %f %f %f %f %f", &bone, &pos.x, &pos.y, &pos.z, &rot.x, &rot.y, &rot.z) != 7) continue; if(bone < 0 || bone >= skel->numbones) continue; for(; lastbone < bone; lastbone++) animbones[frame*skel->numbones + lastbone] = animbones[lastbone]; lastbone++; float cx = cosf(rot.x/2), sx = sinf(rot.x/2), cy = cosf(rot.y/2), sy = sinf(rot.y/2), cz = cosf(rot.z/2), sz = sinf(rot.z/2); pos.y = -pos.y; dualquat dq(quat(-(sx*cy*cz - cx*sy*sz), cx*sy*cz + sx*cy*sz, -(cx*cy*sz - sx*sy*cz), cx*cy*cz + sx*sy*sz), pos); if(adjustments.inrange(bone)) adjustments[bone].adjust(dq); dq.mul(skel->bones[bone].invbase); dualquat &dst = animbones[frame*skel->numbones + bone]; if(skel->bones[bone].parent < 0) dst = dq; else dst.mul(skel->bones[skel->bones[bone].parent].base, dq); dst.fixantipodal(skel->numframes > 0 ? skel->framebones[bone] : animbones[bone]); } for(; lastbone < skel->numbones; lastbone++) animbones[frame*skel->numbones + lastbone] = animbones[lastbone]; return numframes; } skelanimspec *loadanim(const char *filename) { skelanimspec *sa = skel->findskelanim(filename); if(sa || skel->numbones <= 0) return sa; stream *f = openfile(filename, "r"); if(!f) return NULL; char buf[512]; int version = -1; vector animbones; while(f->getline(buf, sizeof(buf))) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(sscanf(curbuf, " version %d", &version) == 1) { if(version != 1) { delete f; return NULL; } } else if(!strncmp(curbuf, "nodes", 5)) { vector bones; readnodes(f, buf, sizeof(buf), bones); if(bones.length() != skel->numbones) { delete f; return NULL; } } else if(!strncmp(curbuf, "triangles", 9)) skipsection(f, buf, sizeof(buf)); else if(!strncmp(curbuf, "skeleton", 8)) readframes(f, buf, sizeof(buf), animbones); else if(!strncmp(curbuf, "vertexanimation", 15)) skipsection(f, buf, sizeof(buf)); } int numframes = animbones.length() / skel->numbones; dualquat *framebones = new dualquat[(skel->numframes+numframes)*skel->numbones]; if(skel->framebones) { memcpy(framebones, skel->framebones, skel->numframes*skel->numbones*sizeof(dualquat)); delete[] skel->framebones; } memcpy(&framebones[skel->numframes*skel->numbones], animbones.getbuf(), numframes*skel->numbones*sizeof(dualquat)); skel->framebones = framebones; sa = &skel->addskelanim(filename); sa->frame = skel->numframes; sa->range = numframes; skel->numframes += numframes; delete f; return sa; } bool load(const char *meshfile) { name = newstring(meshfile); if(!loadmesh(meshfile)) return false; return true; } }; meshgroup *loadmeshes(char *name, va_list args) { smdmeshgroup *group = new smdmeshgroup; group->shareskeleton(va_arg(args, char *)); if(!group->load(name)) { delete group; return NULL; } return group; } bool loaddefaultparts() { skelpart &mdl = *new skelpart; parts.add(&mdl); mdl.model = this; mdl.index = 0; mdl.pitchscale = mdl.pitchoffset = mdl.pitchmin = mdl.pitchmax = 0; adjustments.setsize(0); const char *fname = loadname + strlen(loadname); do --fname; while(fname >= loadname && *fname!='/' && *fname!='\\'); fname++; defformatstring(meshname)("packages/models/%s/%s.smd", loadname, fname); mdl.meshes = sharemeshes(path(meshname), NULL); if(!mdl.meshes) return false; mdl.initanimparts(); mdl.initskins(); return true; } bool load() { if(loaded) return true; formatstring(dir)("packages/models/%s", loadname); defformatstring(cfgname)("packages/models/%s/smd.cfg", loadname); loading = this; identflags &= ~IDF_PERSIST; if(execfile(cfgname, false) && parts.length()) // configured smd, will call the smd* commands below { identflags |= IDF_PERSIST; loading = NULL; loopv(parts) if(!parts[i]->meshes) return false; } else // smd without configuration, try default tris and skin { identflags |= IDF_PERSIST; if(!loaddefaultparts()) { loading = NULL; return false; } loading = NULL; } scale /= 4; parts[0]->translate = translate; loopv(parts) { skelpart *p = (skelpart *)parts[i]; p->endanimparts(); p->meshes->shared++; } preloadshaders(); return loaded = true; } }; static inline uint hthash(const smd::smdmeshgroup::smdvertkey &k) { return hthash(k.pos); } static inline bool htcmp(const smd::smdmeshgroup::smdvertkey &k, int index) { if(!k.mesh->verts.inrange(index)) return false; const smd::vert &v = k.mesh->verts[index]; return k.pos == v.pos && k.norm == v.norm && k.u == v.u && k.v == v.v && k.blend == v.blend; } skelcommands smdcommands; sandboxgamemaker-2.7.1+dfsg/src/engine/serverbrowser.cpp0000664000175000017500000004671311655776734023364 0ustar showardshoward// serverbrowser.cpp: eihrul's concurrent resolver, and server browser window management #include "engine.h" #include "SDL_thread.h" struct resolverthread { SDL_Thread *thread; const char *query; int starttime; }; struct resolverresult { const char *query; ENetAddress address; }; vector resolverthreads; vector resolverqueries; vector resolverresults; SDL_mutex *resolvermutex; SDL_cond *querycond, *resultcond; #define RESOLVERTHREADS 2 #define RESOLVERLIMIT 3000 int resolverloop(void * data) { resolverthread *rt = (resolverthread *)data; SDL_LockMutex(resolvermutex); SDL_Thread *thread = rt->thread; SDL_UnlockMutex(resolvermutex); if(!thread || SDL_GetThreadID(thread) != SDL_ThreadID()) return 0; while(thread == rt->thread) { SDL_LockMutex(resolvermutex); while(resolverqueries.empty()) SDL_CondWait(querycond, resolvermutex); rt->query = resolverqueries.pop(); rt->starttime = totalmillis; SDL_UnlockMutex(resolvermutex); ENetAddress address = { ENET_HOST_ANY, ENET_PORT_ANY }; enet_address_set_host(&address, rt->query); SDL_LockMutex(resolvermutex); if(rt->query && thread == rt->thread) { resolverresult &rr = resolverresults.add(); rr.query = rt->query; rr.address = address; rt->query = NULL; rt->starttime = 0; SDL_CondSignal(resultcond); } SDL_UnlockMutex(resolvermutex); } return 0; } void resolverinit() { resolvermutex = SDL_CreateMutex(); querycond = SDL_CreateCond(); resultcond = SDL_CreateCond(); SDL_LockMutex(resolvermutex); loopi(RESOLVERTHREADS) { resolverthread &rt = resolverthreads.add(); rt.query = NULL; rt.starttime = 0; rt.thread = SDL_CreateThread(resolverloop, &rt); } SDL_UnlockMutex(resolvermutex); } void resolverstop(resolverthread &rt) { SDL_LockMutex(resolvermutex); if(rt.query) { #ifndef __APPLE__ SDL_KillThread(rt.thread); #endif rt.thread = SDL_CreateThread(resolverloop, &rt); } rt.query = NULL; rt.starttime = 0; SDL_UnlockMutex(resolvermutex); } void resolverclear() { if(resolverthreads.empty()) return; SDL_LockMutex(resolvermutex); resolverqueries.shrink(0); resolverresults.shrink(0); loopv(resolverthreads) { resolverthread &rt = resolverthreads[i]; resolverstop(rt); } SDL_UnlockMutex(resolvermutex); } void resolverquery(const char *name) { if(resolverthreads.empty()) resolverinit(); SDL_LockMutex(resolvermutex); resolverqueries.add(name); SDL_CondSignal(querycond); SDL_UnlockMutex(resolvermutex); } bool resolvercheck(const char **name, ENetAddress *address) { bool resolved = false; SDL_LockMutex(resolvermutex); if(!resolverresults.empty()) { resolverresult &rr = resolverresults.pop(); *name = rr.query; address->host = rr.address.host; resolved = true; } else loopv(resolverthreads) { resolverthread &rt = resolverthreads[i]; if(rt.query && totalmillis - rt.starttime > RESOLVERLIMIT) { resolverstop(rt); *name = rt.query; resolved = true; } } SDL_UnlockMutex(resolvermutex); return resolved; } bool resolverwait(const char *name, ENetAddress *address) { if(resolverthreads.empty()) resolverinit(); defformatstring(text)("resolving %s... (esc to abort)", name); renderprogress(0, text); SDL_LockMutex(resolvermutex); resolverqueries.add(name); SDL_CondSignal(querycond); int starttime = SDL_GetTicks(), timeout = 0; bool resolved = false; for(;;) { SDL_CondWaitTimeout(resultcond, resolvermutex, 250); loopv(resolverresults) if(resolverresults[i].query == name) { address->host = resolverresults[i].address.host; resolverresults.remove(i); resolved = true; break; } if(resolved) break; timeout = SDL_GetTicks() - starttime; renderprogress(min(float(timeout)/RESOLVERLIMIT, 1.0f), text); if(interceptkey(SDLK_ESCAPE)) timeout = RESOLVERLIMIT + 1; if(timeout > RESOLVERLIMIT) break; } if(!resolved && timeout > RESOLVERLIMIT) { loopv(resolverthreads) { resolverthread &rt = resolverthreads[i]; if(rt.query == name) { resolverstop(rt); break; } } } SDL_UnlockMutex(resolvermutex); return resolved; } SDL_Thread *connthread = NULL; SDL_mutex *connmutex = NULL; SDL_cond *conncond = NULL; struct connectdata { ENetSocket sock; ENetAddress address; int result; }; // do this in a thread to prevent timeouts // could set timeouts on sockets, but this is more reliable and gives more control int connectthread(void *data) { SDL_LockMutex(connmutex); if(!connthread || SDL_GetThreadID(connthread) != SDL_ThreadID()) { SDL_UnlockMutex(connmutex); return 0; } connectdata cd = *(connectdata *)data; SDL_UnlockMutex(connmutex); int result = enet_socket_connect(cd.sock, &cd.address); SDL_LockMutex(connmutex); if(!connthread || SDL_GetThreadID(connthread) != SDL_ThreadID()) { enet_socket_destroy(cd.sock); SDL_UnlockMutex(connmutex); return 0; } ((connectdata *)data)->result = result; SDL_CondSignal(conncond); SDL_UnlockMutex(connmutex); return 0; } #define CONNLIMIT 20000 int connectwithtimeout(ENetSocket sock, const char *hostname, const ENetAddress &address) { defformatstring(text)("connecting to %s... (esc to abort)", hostname); renderprogress(0, text); if(!connmutex) connmutex = SDL_CreateMutex(); if(!conncond) conncond = SDL_CreateCond(); SDL_LockMutex(connmutex); connectdata cd = { sock, address, -1 }; connthread = SDL_CreateThread(connectthread, &cd); int starttime = SDL_GetTicks(), timeout = 0; for(;;) { if(!SDL_CondWaitTimeout(conncond, connmutex, 250)) { if(cd.result<0) enet_socket_destroy(sock); break; } timeout = SDL_GetTicks() - starttime; renderprogress(min(float(timeout)/CONNLIMIT, 1.0f), text); if(interceptkey(SDLK_ESCAPE)) timeout = CONNLIMIT + 1; if(timeout > CONNLIMIT) break; } /* thread will actually timeout eventually if its still trying to connect * so just leave it (and let it destroy socket) instead of causing problems on some platforms by killing it */ connthread = NULL; SDL_UnlockMutex(connmutex); return cd.result; } enum { UNRESOLVED = 0, RESOLVING, RESOLVED }; struct serverinfo { enum { WAITING = INT_MAX, MAXPINGS = 3 }; string name, map, sdesc; int port, numplayers, resolved, ping, lastping, nextping; int pings[MAXPINGS]; vector attr; ENetAddress address; bool keep; const char *password; serverinfo() : port(-1), numplayers(0), resolved(UNRESOLVED), keep(false), password(NULL) { name[0] = map[0] = sdesc[0] = '\0'; clearpings(); } ~serverinfo() { DELETEA(password); } void clearpings() { ping = WAITING; loopk(MAXPINGS) pings[k] = WAITING; nextping = 0; lastping = -1; } void cleanup() { clearpings(); attr.setsize(0); numplayers = 0; } void reset() { lastping = -1; } void checkdecay(int decay) { if(lastping >= 0 && totalmillis - lastping >= decay) cleanup(); if(lastping < 0) lastping = totalmillis; } void calcping() { int numpings = 0, totalpings = 0; loopk(MAXPINGS) if(pings[k] != WAITING) { totalpings += pings[k]; numpings++; } ping = numpings ? totalpings/numpings : WAITING; } void addping(int rtt, int millis) { if(millis >= lastping) lastping = -1; pings[nextping] = rtt; nextping = (nextping+1)%MAXPINGS; calcping(); } static bool compare(serverinfo *a, serverinfo *b) { bool ac = server::servercompatible(a->name, a->sdesc, a->map, a->ping, a->attr, a->numplayers), bc = server::servercompatible(b->name, b->sdesc, b->map, b->ping, b->attr, b->numplayers); if(ac > bc) return true; if(bc > ac) return false; if(a->keep > b->keep) return true; if(a->keep < b->keep) return false; if(a->numplayers < b->numplayers) return false; if(a->numplayers > b->numplayers) return true; if(a->ping > b->ping) return false; if(a->ping < b->ping) return true; int cmp = strcmp(a->name, b->name); if(cmp != 0) return cmp < 0; if(a->port < b->port) return true; if(a->port > b->port) return false; return false; } }; vector servers; ENetSocket pingsock = ENET_SOCKET_NULL; int lastinfo = 0; static serverinfo *newserver(const char *name, int port, uint ip = ENET_HOST_ANY) { serverinfo *si = new serverinfo; si->address.host = ip; si->address.port = server::serverinfoport(port); if(ip!=ENET_HOST_ANY) si->resolved = RESOLVED; si->port = port; if(name) copystring(si->name, name); else if(ip==ENET_HOST_ANY || enet_address_get_host_ip(&si->address, si->name, sizeof(si->name)) < 0) { delete si; return NULL; } servers.add(si); return si; } void addserver(const char *name, int port, const char *password, bool keep) { if(port <= 0) port = server::serverport(); loopv(servers) { serverinfo *s = servers[i]; if(strcmp(s->name, name) || s->port != port) continue; if(password && (!s->password || strcmp(s->password, password))) { DELETEA(s->password); s->password = newstring(password); } if(keep && !s->keep) s->keep = true; return; } serverinfo *s = newserver(name, port); if(!s) return; if(password) s->password = newstring(password); s->keep = keep; } VARP(searchlan, 0, 1, 1); VARP(servpingrate, 1000, 5000, 60000); VARP(servpingdecay, 1000, 15000, 60000); VARP(maxservpings, 0, 10, 1000); void pingservers() { if(pingsock == ENET_SOCKET_NULL) { pingsock = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM); if(pingsock == ENET_SOCKET_NULL) { lastinfo = totalmillis; return; } enet_socket_set_option(pingsock, ENET_SOCKOPT_NONBLOCK, 1); enet_socket_set_option(pingsock, ENET_SOCKOPT_BROADCAST, 1); } ENetBuffer buf; uchar ping[MAXTRANS]; ucharbuf p(ping, sizeof(ping)); putint(p, totalmillis); static int lastping = 0; if(lastping >= servers.length()) lastping = 0; loopi(maxservpings ? min(servers.length(), maxservpings) : servers.length()) { serverinfo &si = *servers[lastping]; if(++lastping >= servers.length()) lastping = 0; if(si.address.host == ENET_HOST_ANY) continue; buf.data = ping; buf.dataLength = p.length(); enet_socket_send(pingsock, &si.address, &buf, 1); si.checkdecay(servpingdecay); } if(searchlan) { ENetAddress address; address.host = ENET_HOST_BROADCAST; address.port = server::laninfoport(); buf.data = ping; buf.dataLength = p.length(); enet_socket_send(pingsock, &address, &buf, 1); } lastinfo = totalmillis; } void checkresolver() { int resolving = 0; loopv(servers) { serverinfo &si = *servers[i]; if(si.resolved == RESOLVED) continue; if(si.address.host == ENET_HOST_ANY) { if(si.resolved == UNRESOLVED) { si.resolved = RESOLVING; resolverquery(si.name); } resolving++; } } if(!resolving) return; const char *name = NULL; for(;;) { ENetAddress addr = { ENET_HOST_ANY, ENET_PORT_ANY }; if(!resolvercheck(&name, &addr)) break; loopv(servers) { serverinfo &si = *servers[i]; if(name == si.name) { si.resolved = RESOLVED; si.address.host = addr.host; break; } } } } static int lastreset = 0; void checkpings() { if(pingsock==ENET_SOCKET_NULL) return; enet_uint32 events = ENET_SOCKET_WAIT_RECEIVE; ENetBuffer buf; ENetAddress addr; uchar ping[MAXTRANS]; char text[MAXTRANS]; buf.data = ping; buf.dataLength = sizeof(ping); while(enet_socket_wait(pingsock, &events, 0) >= 0 && events) { int len = enet_socket_receive(pingsock, &addr, &buf, 1); if(len <= 0) return; serverinfo *si = NULL; loopv(servers) if(addr.host == servers[i]->address.host && addr.port == servers[i]->address.port) { si = servers[i]; break; } if(!si && searchlan) si = newserver(NULL, server::serverport(addr.port), addr.host); if(!si) continue; ucharbuf p(ping, len); int millis = getint(p), rtt = clamp(totalmillis - millis, 0, min(servpingdecay, totalmillis)); if(millis >= lastreset && rtt < servpingdecay) si->addping(rtt, millis); si->numplayers = getint(p); int numattr = getint(p); si->attr.shrink(0); loopj(numattr) si->attr.add(getint(p)); getstring(text, p); filtertext(si->map, text, false); getstring(text, p); filtertext(si->sdesc, text); } } void refreshservers() { static int lastrefresh = 0; if(lastrefresh==totalmillis) return; if(totalmillis - lastrefresh > 1000) { loopv(servers) servers[i]->reset(); lastreset = totalmillis; } lastrefresh = totalmillis; checkresolver(); checkpings(); if(totalmillis - lastinfo >= servpingrate/(maxservpings ? max(1, (servers.length() + maxservpings - 1) / maxservpings) : 1)) pingservers(); servers.sort(serverinfo::compare); } #ifndef NEWGUI char *showservers(g3d_gui *cgui) { refreshservers(); serverinfo *sc = NULL; for(int start = 0; start < servers.length();) { if(start > 0) cgui->tab(); int end = servers.length(); cgui->pushlist(); loopi(10) { if(!game::serverinfostartcolumn(cgui, i)) break; for(int j = start; j < end; j++) { if(!i && cgui->shouldtab()) { end = j; break; } serverinfo &si = *servers[j]; const char *sdesc = si.sdesc; if(si.address.host == ENET_HOST_ANY) sdesc = "[unknown host]"; else if(si.ping == serverinfo::WAITING) sdesc = "[waiting for response]"; if(game::serverinfoentry(cgui, i, si.name, si.port, sdesc, si.map, sdesc == si.sdesc ? si.ping : -1, si.attr, si.numplayers)) sc = &si; } game::serverinfoendcolumn(cgui, i); } cgui->poplist(); start = end; } if(!sc) return NULL; string command; if(sc->password) formatstring(command)("connect %s %d \"%s\"", sc->name, sc->port, sc->password); else formatstring(command)("connect %s %d", sc->name, sc->port); return newstring(command); } #endif void clearservers(bool full = false) { resolverclear(); if(full) servers.deletecontents(); else loopvrev(servers) if(!servers[i]->keep) delete servers.remove(i); } #define RETRIEVELIMIT 20000 void retrieveservers(vector &data) { ENetSocket sock = connectmaster(); if(sock == ENET_SOCKET_NULL) return; extern char *mastername; defformatstring(text)("retrieving servers from %s... (esc to abort)", mastername); renderprogress(0, text); int starttime = SDL_GetTicks(), timeout = 0; const char *req = "list\n"; int reqlen = strlen(req); ENetBuffer buf; while(reqlen > 0) { enet_uint32 events = ENET_SOCKET_WAIT_SEND; if(enet_socket_wait(sock, &events, 250) >= 0 && events) { buf.data = (void *)req; buf.dataLength = reqlen; int sent = enet_socket_send(sock, NULL, &buf, 1); if(sent < 0) break; req += sent; reqlen -= sent; if(reqlen <= 0) break; } timeout = SDL_GetTicks() - starttime; renderprogress(min(float(timeout)/RETRIEVELIMIT, 1.0f), text); if(interceptkey(SDLK_ESCAPE)) timeout = RETRIEVELIMIT + 1; if(timeout > RETRIEVELIMIT) break; } if(reqlen <= 0) for(;;) { enet_uint32 events = ENET_SOCKET_WAIT_RECEIVE; if(enet_socket_wait(sock, &events, 250) >= 0 && events) { if(data.length() >= data.capacity()) data.reserve(4096); buf.data = data.getbuf() + data.length(); buf.dataLength = data.capacity() - data.length(); int recv = enet_socket_receive(sock, NULL, &buf, 1); if(recv <= 0) break; data.advance(recv); } timeout = SDL_GetTicks() - starttime; renderprogress(min(float(timeout)/RETRIEVELIMIT, 1.0f), text); if(interceptkey(SDLK_ESCAPE)) timeout = RETRIEVELIMIT + 1; if(timeout > RETRIEVELIMIT) break; } if(data.length()) data.add('\0'); enet_socket_destroy(sock); } void updatefrommaster() { vector data; retrieveservers(data); if(data.empty()) conoutf("master server not replying"); else { clearservers(); execute(data.getbuf()); } refreshservers(); } ICOMMAND(addserver, "sis", (const char *name, int *port, const char *password), addserver(name, *port, password[0] ? password : NULL)); ICOMMAND(keepserver, "sis", (const char *name, int *port, const char *password), addserver(name, *port, password[0] ? password : NULL, true)); ICOMMAND(clearservers, "i", (int *full), clearservers(*full!=0)); COMMAND(updatefrommaster, ""); void writeservercfg() { if(!game::savedservers()) return; stream *f = openutf8file(path(game::savedservers(), true), "wb"); if(!f) return; int kept = 0; loopv(servers) { serverinfo *s = servers[i]; if(s->keep) { if(!kept) f->printf("// servers that should never be cleared from the server list\n\n"); if(s->password) f->printf("keepserver %s %d \"%s\"\n", s->name, s->port, s->password); else f->printf("keepserver %s %d\n", s->name, s->port); kept++; } } if(kept) f->printf("\n"); f->printf("// servers connected to are added here automatically\n\n"); loopv(servers) { serverinfo *s = servers[i]; if(!s->keep) { if(s->password) f->printf("addserver %s %d \"%s\"\n", s->name, s->port, s->password); else f->printf("addserver %s %d\n", s->name, s->port); } } delete f; } sandboxgamemaker-2.7.1+dfsg/src/engine/vertmodel.h0000664000175000017500000006031711527772736022110 0ustar showardshowardstruct vertmodel : animmodel { struct vert { vec pos, norm; }; struct vvertff { vec pos; float u, v; }; struct vvert : vvertff { vec norm; }; struct vvertbump : vvert { vec tangent; float bitangent; }; struct tcvert { float u, v; }; struct bumpvert { vec tangent; float bitangent; }; struct tri { ushort vert[3]; }; struct vbocacheentry { uchar *vdata; GLuint vbuf; animstate as; int millis; vbocacheentry() : vdata(NULL), vbuf(0) { as.cur.fr1 = as.prev.fr1 = -1; } }; struct vertmesh : mesh { vert *verts; tcvert *tcverts; bumpvert *bumpverts; tri *tris; int numverts, numtris; int voffset, eoffset, elen; ushort minvert, maxvert; vertmesh() : verts(0), tcverts(0), bumpverts(0), tris(0) { } virtual ~vertmesh() { DELETEA(verts); DELETEA(tcverts); DELETEA(bumpverts); DELETEA(tris); } void smoothnorms(float limit = 0, bool areaweight = true) { if(((vertmeshgroup *)group)->numframes != 1) { buildnorms(areaweight); return; } mesh::smoothnorms(verts, numverts, tris, numtris, limit, areaweight); } void buildnorms(bool areaweight = true) { loopk(((vertmeshgroup *)group)->numframes) mesh::buildnorms(&verts[k*numverts], numverts, tris, numtris, areaweight); } void calctangents(bool areaweight = true) { if(bumpverts) return; bumpverts = new bumpvert[((vertmeshgroup *)group)->numframes*numverts]; loopk(((vertmeshgroup *)group)->numframes) mesh::calctangents(&bumpverts[k*numverts], &verts[k*numverts], tcverts, numverts, tris, numtris, areaweight); } void calcbb(int frame, vec &bbmin, vec &bbmax, const matrix3x4 &m) { vert *fverts = &verts[frame*numverts]; loopj(numverts) { vec v = m.transform(fverts[j].pos); loopi(3) { bbmin[i] = min(bbmin[i], v[i]); bbmax[i] = max(bbmax[i], v[i]); } } } void gentris(int frame, Texture *tex, vector *out, const matrix3x4 &m) { vert *fverts = &verts[frame*numverts]; loopj(numtris) { BIH::tri &t = out[noclip ? 1 : 0].add(); t.tex = tex; t.a = m.transform(fverts[tris[j].vert[0]].pos); t.b = m.transform(fverts[tris[j].vert[1]].pos); t.c = m.transform(fverts[tris[j].vert[2]].pos); tcvert &av = tcverts[tris[j].vert[0]], &bv = tcverts[tris[j].vert[1]], &cv = tcverts[tris[j].vert[2]]; t.tc[0] = av.u; t.tc[1] = av.v; t.tc[2] = bv.u; t.tc[3] = bv.v; t.tc[4] = cv.u; t.tc[5] = cv.v; } } static inline bool comparevert(vvertff &w, int j, tcvert &tc, vert &v) { return tc.u==w.u && tc.v==w.v && v.pos==w.pos; } static inline bool comparevert(vvert &w, int j, tcvert &tc, vert &v) { return tc.u==w.u && tc.v==w.v && v.pos==w.pos && v.norm==w.norm; } inline bool comparevert(vvertbump &w, int j, tcvert &tc, vert &v) { return tc.u==w.u && tc.v==w.v && v.pos==w.pos && v.norm==w.norm && (!bumpverts || (bumpverts[j].tangent==w.tangent && bumpverts[j].bitangent==w.bitangent)); } static inline void assignvert(vvertff &vv, int j, tcvert &tc, vert &v) { vv.pos = v.pos; vv.u = tc.u; vv.v = tc.v; } static inline void assignvert(vvert &vv, int j, tcvert &tc, vert &v) { vv.pos = v.pos; vv.norm = v.norm; vv.u = tc.u; vv.v = tc.v; } inline void assignvert(vvertbump &vv, int j, tcvert &tc, vert &v) { vv.pos = v.pos; vv.norm = v.norm; vv.u = tc.u; vv.v = tc.v; if(bumpverts) { vv.tangent = bumpverts[j].tangent; vv.bitangent = bumpverts[j].bitangent; } } template int genvbo(vector &idxs, int offset, vector &vverts, int *htdata, int htlen) { voffset = offset; eoffset = idxs.length(); minvert = 0xFFFF; loopi(numtris) { tri &t = tris[i]; loopj(3) { int index = t.vert[j]; tcvert &tc = tcverts[index]; vert &v = verts[index]; int htidx = hthash(v.pos)&(htlen-1); loopk(htlen) { int &vidx = htdata[(htidx+k)&(htlen-1)]; if(vidx < 0) { vidx = idxs.add(ushort(vverts.length())); assignvert(vverts.add(), index, tc, v); break; } else if(comparevert(vverts[vidx], index, tc, v)) { minvert = min(minvert, idxs.add(ushort(vidx))); break; } } } } minvert = min(minvert, ushort(voffset)); maxvert = max(minvert, ushort(vverts.length()-1)); elen = idxs.length()-eoffset; return vverts.length()-voffset; } int genvbo(vector &idxs, int offset) { voffset = offset; eoffset = idxs.length(); loopi(numtris) { tri &t = tris[i]; loopj(3) idxs.add(voffset+t.vert[j]); } minvert = voffset; maxvert = voffset + numverts-1; elen = idxs.length()-eoffset; return numverts; } void filltc(uchar *vdata, size_t stride) { vdata = (uchar *)&((vvertff *)&vdata[voffset*stride])->u; loopi(numverts) { *(tcvert *)vdata = tcverts[i]; vdata += stride; } } void interpverts(const animstate &as, bool norms, bool tangents, void * RESTRICT vdata, skin &s) { const vert * RESTRICT vert1 = &verts[as.cur.fr1 * numverts], * RESTRICT vert2 = &verts[as.cur.fr2 * numverts], * RESTRICT pvert1 = as.interp<1 ? &verts[as.prev.fr1 * numverts] : NULL, * RESTRICT pvert2 = as.interp<1 ? &verts[as.prev.fr2 * numverts] : NULL; #define ipvert(attrib) v.attrib.lerp(vert1[i].attrib, vert2[i].attrib, as.cur.t) #define ipbvert(attrib) v.attrib.lerp(bvert1[i].attrib, bvert2[i].attrib, as.cur.t) #define ipvertp(attrib) v.attrib.lerp(pvert1[i].attrib, pvert2[i].attrib, as.prev.t).lerp(vec().lerp(vert1[i].attrib, vert2[i].attrib, as.cur.t), as.interp) #define ipbvertp(attrib) v.attrib.lerp(bpvert1[i].attrib, bpvert2[i].attrib, as.prev.t).lerp(vec().lerp(bvert1[i].attrib, bvert2[i].attrib, as.cur.t), as.interp) #define iploop(type, body) \ loopi(numverts) \ { \ type &v = ((type * RESTRICT)vdata)[i]; \ body; \ } if(tangents) { const bumpvert * RESTRICT bvert1 = &bumpverts[as.cur.fr1 * numverts], * RESTRICT bvert2 = &bumpverts[as.cur.fr2 * numverts], * RESTRICT bpvert1 = as.interp<1 ? &bumpverts[as.prev.fr1 * numverts] : NULL, * RESTRICT bpvert2 = as.interp<1 ? &bumpverts[as.prev.fr2 * numverts] : NULL; if(as.interp<1) iploop(vvertbump, { ipvertp(pos); ipvertp(norm); ipbvertp(tangent); v.bitangent = bvert1[i].bitangent; }) else iploop(vvertbump, { ipvert(pos); ipvert(norm); ipbvert(tangent); v.bitangent = bvert1[i].bitangent; }) } else if(norms) { if(as.interp<1) iploop(vvert, { ipvertp(pos); ipvertp(norm); }) else iploop(vvert, { ipvert(pos); ipvert(norm); }) } else if(as.interp<1) iploop(vvertff, ipvertp(pos)) else iploop(vvertff, ipvert(pos)) #undef iploop #undef ipvert #undef ipbvert #undef ipvertp #undef ipbvertp } void render(const animstate *as, skin &s, vbocacheentry &vc) { if(!(as->cur.anim&ANIM_NOSKIN)) { if(s.multitextured()) { if(!enablemtc || lastmtcbuf!=lastvbuf) { glClientActiveTexture_(GL_TEXTURE1_ARB); if(!enablemtc) glEnableClientState(GL_TEXTURE_COORD_ARRAY); if(lastmtcbuf!=lastvbuf) { vvertff *vverts = hasVBO ? 0 : (vvertff *)vc.vdata; glTexCoordPointer(2, GL_FLOAT, ((vertmeshgroup *)group)->vertsize, &vverts->u); } glClientActiveTexture_(GL_TEXTURE0_ARB); lastmtcbuf = lastvbuf; enablemtc = true; } } else if(enablemtc) disablemtc(); if(s.tangents()) { if(!enabletangents || lastxbuf!=lastvbuf) { if(!enabletangents) glEnableVertexAttribArray_(1); if(lastxbuf!=lastvbuf) { vvertbump *vverts = hasVBO ? 0 : (vvertbump *)vc.vdata; glVertexAttribPointer_(1, 4, GL_FLOAT, GL_FALSE, ((vertmeshgroup *)group)->vertsize, &vverts->tangent.x); } lastxbuf = lastvbuf; enabletangents = true; } } else if(enabletangents) disabletangents(); if(renderpath==R_FIXEDFUNCTION && (s.scrollu || s.scrollv)) { glMatrixMode(GL_TEXTURE); glPushMatrix(); glTranslatef(s.scrollu*lastmillis/1000.0f, s.scrollv*lastmillis/1000.0f, 0); if(s.multitextured()) { glActiveTexture_(GL_TEXTURE1_ARB); glPushMatrix(); glTranslatef(s.scrollu*lastmillis/1000.0f, s.scrollv*lastmillis/1000.0f, 0); } } } if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, minvert, maxvert, elen, GL_UNSIGNED_SHORT, &((vertmeshgroup *)group)->edata[eoffset]); else glDrawElements(GL_TRIANGLES, elen, GL_UNSIGNED_SHORT, &((vertmeshgroup *)group)->edata[eoffset]); glde++; xtravertsva += numverts; if(renderpath==R_FIXEDFUNCTION && !(as->cur.anim&ANIM_NOSKIN) && (s.scrollu || s.scrollv)) { if(s.multitextured()) { glPopMatrix(); glActiveTexture_(GL_TEXTURE0_ARB); } glPopMatrix(); glMatrixMode(GL_MODELVIEW); } return; } }; struct tag { char *name; matrix3x4 transform; tag() : name(NULL) {} ~tag() { DELETEA(name); } }; struct vertmeshgroup : meshgroup { int numframes; tag *tags; int numtags; static const int MAXVBOCACHE = 16; vbocacheentry vbocache[MAXVBOCACHE]; ushort *edata; GLuint ebuf; bool vnorms, vtangents; int vlen, vertsize; uchar *vdata; vertmeshgroup() : numframes(0), tags(NULL), numtags(0), edata(NULL), ebuf(0), vdata(NULL) { } virtual ~vertmeshgroup() { DELETEA(tags); if(ebuf) glDeleteBuffers_(1, &ebuf); loopi(MAXVBOCACHE) { DELETEA(vbocache[i].vdata); if(vbocache[i].vbuf) glDeleteBuffers_(1, &vbocache[i].vbuf); } DELETEA(vdata); } int findtag(const char *name) { loopi(numtags) if(!strcmp(tags[i].name, name)) return i; return -1; } int totalframes() const { return numframes; } void concattagtransform(part *p, int frame, int i, const matrix3x4 &m, matrix3x4 &n) { n.mul(m, tags[frame*numtags + i].transform); n.translate(m.transformnormal(p->translate).mul(p->model->scale)); } void calctagmatrix(part *p, int i, const animstate &as, glmatrixf &matrix) { const matrix3x4 &tag1 = tags[as.cur.fr1*numtags + i].transform, &tag2 = tags[as.cur.fr2*numtags + i].transform; matrix3x4 tag; tag.lerp(tag1, tag2, as.cur.t); if(as.interp<1) { const matrix3x4 &tag1p = tags[as.prev.fr1*numtags + i].transform, &tag2p = tags[as.prev.fr2*numtags + i].transform; matrix3x4 tagp; tagp.lerp(tag1p, tag2p, as.prev.t); tag.lerp(tagp, tag, as.interp); } matrix = glmatrixf(tag); matrix[12] = (matrix[12] + p->translate.x) * p->model->scale; matrix[13] = (matrix[13] + p->translate.y) * p->model->scale; matrix[14] = (matrix[14] + p->translate.z) * p->model->scale; } void genvbo(bool norms, bool tangents, vbocacheentry &vc) { if(hasVBO) { if(!vc.vbuf) glGenBuffers_(1, &vc.vbuf); if(ebuf) return; } else if(edata) { #define ALLOCVDATA(vdata) \ do \ { \ DELETEA(vdata); \ vdata = new uchar[vlen*vertsize]; \ loopv(meshes) ((vertmesh *)meshes[i])->filltc(vdata, vertsize); \ } while(0) if(!vc.vdata) ALLOCVDATA(vc.vdata); return; } vector idxs; vnorms = norms; vtangents = tangents; vertsize = tangents ? sizeof(vvertbump) : (norms ? sizeof(vvert) : sizeof(vvertff)); vlen = 0; if(numframes>1) { loopv(meshes) vlen += ((vertmesh *)meshes[i])->genvbo(idxs, vlen); DELETEA(vdata); if(hasVBO) ALLOCVDATA(vdata); else ALLOCVDATA(vc.vdata); } else { if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc.vbuf); #define GENVBO(type) \ do \ { \ vector vverts; \ loopv(meshes) vlen += ((vertmesh *)meshes[i])->genvbo(idxs, vlen, vverts, htdata, htlen); \ if(hasVBO) glBufferData_(GL_ARRAY_BUFFER_ARB, vverts.length()*sizeof(type), vverts.getbuf(), GL_STATIC_DRAW_ARB); \ else \ { \ DELETEA(vc.vdata); \ vc.vdata = new uchar[vverts.length()*sizeof(type)]; \ memcpy(vc.vdata, vverts.getbuf(), vverts.length()*sizeof(type)); \ } \ } while(0) int numverts = 0, htlen = 128; loopv(meshes) numverts += ((vertmesh *)meshes[i])->numverts; while(htlen < numverts) htlen *= 2; if(numverts*4 > htlen*3) htlen *= 2; int *htdata = new int[htlen]; memset(htdata, -1, htlen*sizeof(int)); if(tangents) GENVBO(vvertbump); else if(norms) GENVBO(vvert); else GENVBO(vvertff); delete[] htdata; if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); } if(hasVBO) { glGenBuffers_(1, &ebuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, ebuf); glBufferData_(GL_ELEMENT_ARRAY_BUFFER_ARB, idxs.length()*sizeof(ushort), idxs.getbuf(), GL_STATIC_DRAW_ARB); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } else { edata = new ushort[idxs.length()]; memcpy(edata, idxs.getbuf(), idxs.length()*sizeof(ushort)); } #undef GENVBO #undef ALLOCVDATA } void bindvbo(const animstate *as, vbocacheentry &vc) { vvert *vverts = hasVBO ? 0 : (vvert *)vc.vdata; if(hasVBO && lastebuf!=ebuf) { glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, ebuf); lastebuf = ebuf; } if(lastvbuf != (hasVBO ? (void *)(size_t)vc.vbuf : vc.vdata)) { if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc.vbuf); if(!lastvbuf) glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, vertsize, &vverts->pos); lastvbuf = hasVBO ? (void *)(size_t)vc.vbuf : vc.vdata; } if(as->cur.anim&ANIM_NOSKIN) { if(enabletc) disabletc(); if(enablenormals) disablenormals(); } else { if(vnorms || vtangents) { if(!enablenormals) { glEnableClientState(GL_NORMAL_ARRAY); enablenormals = true; } if(lastnbuf!=lastvbuf) { glNormalPointer(GL_FLOAT, vertsize, &vverts->norm); lastnbuf = lastvbuf; } } else if(enablenormals) disablenormals(); if(!enabletc) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); enabletc = true; } if(lasttcbuf!=lastvbuf) { glTexCoordPointer(2, GL_FLOAT, vertsize, &vverts->u); lasttcbuf = lastnbuf; } } if(enablebones) disablebones(); } void cleanup() { loopi(MAXVBOCACHE) { vbocacheentry &c = vbocache[i]; if(c.vbuf) { glDeleteBuffers_(1, &c.vbuf); c.vbuf = 0; } DELETEA(c.vdata); c.as.cur.fr1 = -1; } if(hasVBO) { if(ebuf) { glDeleteBuffers_(1, &ebuf); ebuf = 0; } } else DELETEA(vdata); } void render(const animstate *as, float pitch, const vec &axis, const vec &forward, dynent *d, part *p) { if(as->cur.anim&ANIM_NORENDER) { loopv(p->links) calctagmatrix(p, p->links[i].tag, *as, p->links[i].matrix); return; } bool norms = false, tangents = false; loopv(p->skins) { if(p->skins[i].normals()) norms = true; if(p->skins[i].tangents()) tangents = true; } if(norms!=vnorms || tangents!=vtangents) { cleanup(); disablevbo(); } vbocacheentry *vc = NULL; if(numframes<=1) vc = vbocache; else { loopi(MAXVBOCACHE) { vbocacheentry &c = vbocache[i]; if(hasVBO ? !c.vbuf : !c.vdata) continue; if(c.as==*as) { vc = &c; break; } } if(!vc) loopi(MAXVBOCACHE) { vc = &vbocache[i]; if((hasVBO ? !vc->vbuf : !vc->vdata) || vc->millis < lastmillis) break; } } if(hasVBO ? !vc->vbuf : !vc->vdata) genvbo(norms, tangents, *vc); if(numframes>1) { if(vc->as!=*as) { vc->as = *as; vc->millis = lastmillis; loopv(meshes) { vertmesh &m = *(vertmesh *)meshes[i]; m.interpverts(*as, norms, tangents, (hasVBO ? vdata : vc->vdata) + m.voffset*vertsize, p->skins[i]); } if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc->vbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, vlen*vertsize, vdata, GL_STREAM_DRAW_ARB); } } vc->millis = lastmillis; } bindvbo(as, *vc); loopv(meshes) { vertmesh *m = (vertmesh *)meshes[i]; p->skins[i].bind(m, as); m->render(as, p->skins[i], *vc); } loopv(p->links) calctagmatrix(p, p->links[i].tag, *as, p->links[i].matrix); } }; vertmodel(const char *name) : animmodel(name) { } }; template struct vertloader : modelloader { }; template struct vertcommands : modelcommands { typedef struct MDL::part part; typedef struct MDL::skin skin; static void loadpart(char *model, float *smooth) { if(!MDL::loading) { conoutf("not loading an %s", MDL::formatname()); return; } defformatstring(filename)("%s/%s", MDL::dir, model); part &mdl = *new part; MDL::loading->parts.add(&mdl); mdl.model = MDL::loading; mdl.index = MDL::loading->parts.length()-1; if(mdl.index) mdl.pitchscale = mdl.pitchoffset = mdl.pitchmin = mdl.pitchmax = 0; mdl.meshes = MDL::loading->sharemeshes(path(filename), double(*smooth > 0 ? cos(clamp(*smooth, 0.0f, 180.0f)*RAD) : 2)); if(!mdl.meshes) conoutf("could not load %s", filename); else mdl.initskins(); } static void setpitch(float *pitchscale, float *pitchoffset, float *pitchmin, float *pitchmax) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } part &mdl = *MDL::loading->parts.last(); mdl.pitchscale = *pitchscale; mdl.pitchoffset = *pitchoffset; if(*pitchmin || *pitchmax) { mdl.pitchmin = *pitchmin; mdl.pitchmax = *pitchmax; } else { mdl.pitchmin = -360*fabs(mdl.pitchscale) + mdl.pitchoffset; mdl.pitchmax = 360*fabs(mdl.pitchscale) + mdl.pitchoffset; } } static void setanim(char *anim, int *frame, int *range, float *speed, int *priority) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } vector anims; findanims(anim, anims); if(anims.empty()) conoutf("could not find animation %s", anim); else loopv(anims) { MDL::loading->parts.last()->setanim(0, anims[i], *frame, *range, *speed, *priority); } } vertcommands() { if(MDL::multiparted()) modelcommand(loadpart, "load", "sf"); modelcommand(setpitch, "pitch", "ffff"); if(MDL::animated()) modelcommand(setanim, "anim", "siiff"); } }; sandboxgamemaker-2.7.1+dfsg/src/engine/bih.h0000664000175000017500000000235111544613352020626 0ustar showardshowardstruct BIHNode { short split[2]; ushort child[2]; int axis() const { return child[0]>>14; } int childindex(int which) const { return child[which]&0x3FFF; } bool isleaf(int which) const { return (child[1]&(1<<(14+which)))!=0; } }; struct BIH { struct tri : triangle { float tc[6]; Texture *tex; }; int maxdepth; int numnodes; BIHNode *nodes; int numtris; tri *tris, *noclip; vec bbmin, bbmax; float radius; BIH(vector *t); ~BIH() { DELETEA(nodes); DELETEA(tris); } static bool triintersect(tri &t, const vec &o, const vec &ray, float maxdist, float &dist, int mode, tri *noclip); void build(vector &buildnodes, ushort *indices, int numindices, const vec &vmin, const vec &vmax, int depth = 1); bool traverse(const vec &o, const vec &ray, float maxdist, float &dist, int mode); bool traverse(const vec &o, const vec &ray, const vec &invray, float maxdist, float &dist, int mode, BIHNode *curnode, float tmin, float tmax); void preload(); }; extern bool mmintersect(const extentity &e, const vec &o, const vec &ray, float maxdist, int mode, float &dist); sandboxgamemaker-2.7.1+dfsg/src/engine/physics.cpp0000664000175000017500000021530611655776734022130 0ustar showardshoward// physics.cpp: no physics books were hurt nor consulted in the construction of this code. // All physics computations and constants were invented on the fly and simply tweaked until // they "felt right", and have no basis in reality. Collision detection is simplistic but // very robust (uses discrete steps at fixed fps). #include "engine.h" #include "mpr.h" const int MAXCLIPPLANES = 1024; static clipplanes clipcache[MAXCLIPPLANES]; static int clipcacheversion = 0; static inline clipplanes &getclipplanes(cube &c, const ivec &o, int size) { clipplanes &p = clipcache[int(&c - worldroot)&(MAXCLIPPLANES-1)]; if(p.owner != &c || p.version != clipcacheversion) { p.owner = &c; p.version = clipcacheversion; genclipplanes(c, o.x, o.y, o.z, size, p); } return p; } void resetclipplanes() { if(!clipcacheversion++) memset(clipcache, 0, sizeof(clipcache)); } ///////////////////////// ray - cube collision /////////////////////////////////////////////// static inline bool pointinbox(const vec &v, const vec &bo, const vec &br) { return v.x <= bo.x+br.x && v.x >= bo.x-br.x && v.y <= bo.y+br.y && v.y >= bo.y-br.y && v.z <= bo.z+br.z && v.z >= bo.z-br.z; } bool pointincube(const clipplanes &p, const vec &v) { if(!pointinbox(v, p.o, p.r)) return false; loopi(p.size) if(p.p[i].dist(v)>1e-3f) return false; return true; } #define INTERSECTPLANES(setentry, exit) \ float enterdist = -1e16f, exitdist = 1e16f; \ loopi(p.size) \ { \ float pdist = p.p[i].dist(v), facing = ray.dot(p.p[i]); \ if(facing < 0) \ { \ pdist /= -facing; \ if(pdist > enterdist) \ { \ if(pdist > exitdist) exit; \ enterdist = pdist; \ setentry; \ } \ } \ else if(facing > 0) \ { \ pdist /= -facing; \ if(pdist < exitdist) \ { \ if(pdist < enterdist) exit; \ exitdist = pdist; \ } \ } \ else if(pdist > 0) exit; \ } #define INTERSECTBOX(setentry, exit) \ loop(i, 3) \ { \ if(ray[i]) \ { \ float prad = fabs(p.r[i] * invray[i]), pdist = (p.o[i] - v[i]) * invray[i], pmin = pdist - prad, pmax = pdist + prad; \ if(pmin > enterdist) \ { \ if(pmin > exitdist) exit; \ enterdist = pmin; \ setentry; \ } \ if(pmax < exitdist) \ { \ if(pmax < enterdist) exit; \ exitdist = pmax; \ } \ } \ else if(v[i] < p.o[i]-p.r[i] || v[i] > p.o[i]+p.r[i]) exit; \ } vec hitsurface; static inline bool raycubeintersect(clipplanes &p, const cube &c, const vec &v, const vec &ray, const vec &invray, float &dist) { int entry = -1, bbentry = -1; INTERSECTPLANES(entry = i, return false); INTERSECTBOX(bbentry = i, return false); if(exitdist < 0) return false; dist = max(enterdist+0.1f, 0.0f); if(bbentry>=0) { hitsurface = vec(0, 0, 0); hitsurface[bbentry] = ray[bbentry]>0 ? -1 : 1; } else hitsurface = p.p[entry]; return true; } extern void entselectionbox(const entity &e, vec &eo, vec &es); extern int entselradius; float hitentdist; int hitent, hitorient; static float disttoent(octaentities *oc, octaentities *last, const vec &o, const vec &ray, float radius, int mode, extentity *t) { vec eo, es; int orient; float dist = 1e16f, f = 0.0f; if(oc == last) return dist; const vector &ents = entities::getents(); #define entintersect(mask, type, func) {\ if((mode&(mask))==(mask)) \ { \ loopv(oc->type) \ if(!last || last->type.find(oc->type[i])<0) \ { \ extentity &e = *ents[oc->type[i]]; \ if(!e.inoctanode || &e==t) continue; \ func; \ if(f0) \ { \ hitentdist = dist = f; \ hitent = oc->type[i]; \ hitorient = orient; \ } \ } \ } \ } entintersect(RAY_POLY, mapmodels, orient = 0; // FIXME, not set if(!mmintersect(e, o, ray, radius, mode, f)) continue; ); entintersect(RAY_ENTS, other, entselectionbox(e, eo, es); if(!rayrectintersect(eo, es, o, ray, f, orient)) continue; ); entintersect(RAY_ENTS, mapmodels, entselectionbox(e, eo, es); if(!rayrectintersect(eo, es, o, ray, f, orient)) continue; ); return dist; } static float disttooutsideent(const vec &o, const vec &ray, float radius, int mode, extentity *t) { vec eo, es; int orient; float dist = 1e16f, f = 0.0f; const vector &ents = entities::getents(); loopv(outsideents) { extentity &e = *ents[outsideents[i]]; if(!e.inoctanode || &e == t) continue; entselectionbox(e, eo, es); if(!rayrectintersect(eo, es, o, ray, f, orient)) continue; if(f0) { hitentdist = dist = f; hitent = outsideents[i]; hitorient = orient; } } return dist; } // optimized shadow version static float shadowent(octaentities *oc, octaentities *last, const vec &o, const vec &ray, float radius, int mode, extentity *t) { float dist = 1e16f, f = 0.0f; if(oc == last) return dist; const vector &ents = entities::getents(); loopv(oc->mapmodels) if(!last || last->mapmodels.find(oc->mapmodels[i])<0) { extentity &e = *ents[oc->mapmodels[i]]; if(!e.inoctanode || &e==t) continue; if(!mmintersect(e, o, ray, radius, mode, f)) continue; if(f>0 && f0 ? 1 : 0, invray.y>0 ? 1 : 0, invray.z>0 ? 1 : 0); \ #define CHECKINSIDEWORLD \ if(!insideworld(o)) \ { \ float disttoworld = 0, exitworld = 1e16f; \ loopi(3) \ { \ float c = v[i]; \ if(c<0 || c>=worldsize) \ { \ float d = ((invray[i]>0?0:worldsize)-c)*invray[i]; \ if(d<0) return (radius>0?radius:-1); \ disttoworld = max(disttoworld, 0.1f + d); \ } \ float e = ((invray[i]>0?worldsize:0)-c)*invray[i]; \ exitworld = min(exitworld, e); \ } \ if(disttoworld > exitworld) return (radius>0?radius:-1); \ v.add(vec(ray).mul(disttoworld)); \ dist += disttoworld; \ } #define DOWNOCTREE(disttoent, earlyexit) \ cube *lc = levels[lshift]; \ for(;;) \ { \ lshift--; \ lc += octastep(x, y, z, lshift); \ if(lc->ext && lc->ext->ents && dent > 1e15f) \ { \ dent = disttoent(lc->ext->ents, oclast, o, ray, radius, mode, t); \ if(dent < 1e15f earlyexit) return min(dent, dist); \ oclast = lc->ext->ents; \ } \ if(lc->children==NULL) break; \ lc = lc->children; \ levels[lshift] = lc; \ } #define FINDCLOSEST(xclosest, yclosest, zclosest) \ float dx = (lo.x+(lsizemask.x<= uint(worldsize)) exitworld; \ diff >>= lshift; \ if(!diff) exitworld; \ do \ { \ lshift++; \ diff >>= 1; \ } while(diff); float raycube(const vec &o, const vec &ray, float radius, int mode, int size, extentity *t) { if(ray.iszero()) return 0; INITRAYCUBE; CHECKINSIDEWORLD; int closest = -1, x = int(v.x), y = int(v.y), z = int(v.z); for(;;) { DOWNOCTREE(disttoent, && (mode&RAY_SHADOW)); int lsize = 1<0 || !(mode&RAY_SKIPFIRST)) && (((mode&RAY_CLIPMAT) && isclipped(c.material&MATF_VOLUME)) || ((mode&RAY_EDITMAT) && c.material != MAT_AIR) || (!(mode&RAY_PASS) && lsize==size && !isempty(c)) || isentirelysolid(c) || dent < dist)) { if(closest >= 0) { hitsurface = vec(0, 0, 0); hitsurface[closest] = ray[closest]>0 ? -1 : 1; } return min(dent, dist); } ivec lo(x&(~0<0 || !(mode&RAY_SKIPFIRST))) return min(dent, dist+f); } FINDCLOSEST(closest = 0, closest = 1, closest = 2); if(radius>0 && dist>=radius) return min(dent, dist); UPOCTREE(return min(dent, radius>0 ? radius : dist)); } } // optimized version for lightmap shadowing... every cycle here counts!!! float shadowray(const vec &o, const vec &ray, float radius, int mode, extentity *t) { INITRAYCUBE; CHECKINSIDEWORLD; int side = O_BOTTOM, x = int(v.x), y = int(v.y), z = int(v.z); for(;;) { DOWNOCTREE(shadowent, ); cube &c = *lc; ivec lo(x&(~0<= 0) return c.texture[side]==DEFAULT_SKY && mode&RAY_SKIPSKY ? radius : dist+max(enterdist+0.1f, 0.0f); } nextcube: FINDCLOSEST(side = O_RIGHT - lsizemask.x, side = O_FRONT - lsizemask.y, side = O_TOP - lsizemask.z); if(dist>=radius) return dist; UPOCTREE(return radius); } } // thread safe version struct ShadowRayCache { clipplanes clipcache[MAXCLIPPLANES]; int version; ShadowRayCache() : version(0) {} }; ShadowRayCache *newshadowraycache() { return new ShadowRayCache; } void freeshadowraycache(ShadowRayCache *&cache) { delete cache; cache = NULL; } void resetshadowraycache(ShadowRayCache *cache) { if(!cache->version++) memset(cache->clipcache, 0, sizeof(cache->clipcache)); } float shadowray(ShadowRayCache *cache, const vec &o, const vec &ray, float radius, int mode, extentity *t) { INITRAYCUBE; CHECKINSIDEWORLD; int side = O_BOTTOM, x = int(v.x), y = int(v.y), z = int(v.z); for(;;) { DOWNOCTREE(shadowent, ); cube &c = *lc; ivec lo(x&(~0<clipcache[int(&c - worldroot)&(MAXCLIPPLANES-1)]; if(p.owner != &c || p.version != cache->version) { p.owner = &c; p.version = cache->version; genclipplanes(c, lo.x, lo.y, lo.z, 1<= 0) return c.texture[side]==DEFAULT_SKY && mode&RAY_SKIPSKY ? radius : dist+max(enterdist+0.1f, 0.0f); } nextcube: FINDCLOSEST(side = O_RIGHT - lsizemask.x, side = O_FRONT - lsizemask.y, side = O_TOP - lsizemask.z); if(dist>=radius) return dist; UPOCTREE(return radius); } } float rayent(const vec &o, const vec &ray, float radius, int mode, int size, int &orient, int &ent) { hitent = -1; hitentdist = radius; float dist = raycube(o, ray, radius, mode, size); if((mode&RAY_ENTS) == RAY_ENTS) { float dent = disttooutsideent(o, ray, dist < 0 ? 1e16f : dist, mode, NULL); if(dent < 1e15f && (dist < 0 || dent < dist)) dist = dent; } orient = hitorient; ent = hitentdist == dist ? hitent : -1; return dist; } float raycubepos(const vec &o, const vec &ray, vec &hitpos, float radius, int mode, int size) { hitpos = ray; float dist = raycube(o, ray, radius, mode, size); if(radius>0 && dist>=radius) dist = radius; hitpos.mul(dist).add(o); return dist; } bool raycubelos(const vec &o, const vec &dest, vec &hitpos) { vec ray(dest); ray.sub(o); float mag = ray.magnitude(); ray.mul(1/mag); float distance = raycubepos(o, ray, hitpos, mag, RAY_CLIPMAT|RAY_POLY); return distance >= mag; } float rayfloor(const vec &o, vec &floor, int mode, float radius) { if(o.z<=0) return -1; hitsurface = vec(0, 0, 1); float dist = raycube(o, vec(0, 0, -1), radius, mode); if(dist<0 || (radius>0 && dist>=radius)) return dist; floor = hitsurface; return dist; } ///////////////////////// entity collision /////////////////////////////////////////////// // info about collisions bool inside; // whether an internal collision happened physent *hitplayer; // whether the collection hit a player vec wall; // just the normal vectors. const float STAIRHEIGHT = 4.1f; const float FLOORZ = 0.867f; const float SLOPEZ = 0.5f; const float WALLZ = 0.2f; FVARR(movespeed, 10, 100, 1000); FVARR(jumpvel, 10, 200, 5000); FVARR(gravity, 10, 200, 1000); bool ellipserectcollide(physent *d, const vec &dir, const vec &o, const vec ¢er, float yaw, float xr, float yr, float hi, float lo) { float below = (o.z+center.z-lo) - (d->o.z+d->aboveeye), above = (d->o.z-d->eyeheight) - (o.z+center.z+hi); if(below>=0 || above>=0) return true; vec yo(d->o); yo.sub(o); yo.rotate_around_z(-yaw*RAD); yo.sub(center); float dx = clamp(yo.x, -xr, xr) - yo.x, dy = clamp(yo.y, -yr, yr) - yo.y, dist = sqrtf(dx*dx + dy*dy) - d->radius; if(dist < 0) { int sx = yo.x <= -xr ? -1 : (yo.x >= xr ? 1 : 0), sy = yo.y <= -yr ? -1 : (yo.y >= yr ? 1 : 0); if(dist > (yo.z < 0 ? below : above) && (sx || sy)) { vec ydir(dir); ydir.rotate_around_z(-yaw*RAD); if(sx*yo.x - xr > sy*yo.y - yr) { if(dir.iszero() || sx*ydir.x < -1e-6f) { wall = vec(sx, 0, 0); wall.rotate_around_z(yaw*RAD); return false; } } else if(dir.iszero() || sy*ydir.y < -1e-6f) { wall = vec(0, sy, 0); wall.rotate_around_z(yaw*RAD); return false; } } if(yo.z < 0) { if(dir.iszero() || (dir.z > 0 && (d->type>=ENT_INANIMATE || below >= d->zmargin-(d->eyeheight+d->aboveeye)/4.0f))) { wall = vec(0, 0, -1); return false; } } else if(dir.iszero() || (dir.z < 0 && (d->type>=ENT_INANIMATE || above >= d->zmargin-(d->eyeheight+d->aboveeye)/3.0f))) { wall = vec(0, 0, 1); return false; } inside = true; } return true; } bool ellipsecollide(physent *d, const vec &dir, const vec &o, const vec ¢er, float yaw, float xr, float yr, float hi, float lo) { float below = (o.z+center.z-lo) - (d->o.z+d->aboveeye), above = (d->o.z-d->eyeheight) - (o.z+center.z+hi); if(below>=0 || above>=0) return true; vec yo(center); yo.rotate_around_z(yaw*RAD); yo.add(o); float x = yo.x - d->o.x, y = yo.y - d->o.y; float angle = atan2f(y, x), dangle = angle-(d->yaw+90)*RAD, eangle = angle-(yaw+90)*RAD; float dx = d->xradius*cosf(dangle), dy = d->yradius*sinf(dangle); float ex = xr*cosf(eangle), ey = yr*sinf(eangle); float dist = sqrtf(x*x + y*y) - sqrtf(dx*dx + dy*dy) - sqrtf(ex*ex + ey*ey); if(dist < 0) { if(dist > (d->o.z < yo.z ? below : above) && (dir.iszero() || x*dir.x + y*dir.y > 0)) { wall = vec(-x, -y, 0); if(!wall.iszero()) wall.normalize(); return false; } if(d->o.z < yo.z) { if(dir.iszero() || (dir.z > 0 && (d->type>=ENT_INANIMATE || below >= d->zmargin-(d->eyeheight+d->aboveeye)/4.0f))) { wall = vec(0, 0, -1); return false; } } else if(dir.iszero() || (dir.z < 0 && (d->type>=ENT_INANIMATE || above >= d->zmargin-(d->eyeheight+d->aboveeye)/3.0f))) { wall = vec(0, 0, 1); return false; } inside = true; } return true; } bool rectcollide(physent *d, const vec &dir, const vec &o, float xr, float yr, float hi, float lo, uchar visible = 0xFF) { vec s(d->o); s.sub(o); float dxr = d->collidetype==COLLIDE_AABB ? d->xradius : d->radius, dyr = d->collidetype==COLLIDE_AABB ? d->yradius : d->radius; xr += dxr; yr += dyr; float zr = s.z>0 ? d->eyeheight+hi : d->aboveeye+lo; float ax = fabs(s.x)-xr; float ay = fabs(s.y)-yr; float az = fabs(s.z)-zr; if(ax>0 || ay>0 || az>0) return true; wall.x = wall.y = wall.z = 0; #define TRYCOLLIDE(dim, ON, OP, N, P) \ { \ if(s.dim<0) { if(visible&(1<0 && (d->type>=ENT_INANIMATE || (N))))) { wall.dim = -1; return false; } } \ else if(visible&(1<type>=ENT_INANIMATE || (P))))) { wall.dim = 1; return false; } \ } if(ax>ay && ax>az) TRYCOLLIDE(x, O_LEFT, O_RIGHT, ax > -dxr, ax > -dxr); if(ay>az) TRYCOLLIDE(y, O_BACK, O_FRONT, ay > -dyr, ay > -dyr); TRYCOLLIDE(z, O_BOTTOM, O_TOP, az >= d->zmargin-(d->eyeheight+d->aboveeye)/4.0f, az >= d->zmargin-(d->eyeheight+d->aboveeye)/3.0f); inside = true; return true; } #define DYNENTCACHESIZE 1024 static uint dynentframe = 0; static struct dynentcacheentry { int x, y; uint frame; vector dynents; } dynentcache[DYNENTCACHESIZE]; void cleardynentcache() { dynentframe++; if(!dynentframe || dynentframe == 1) loopi(DYNENTCACHESIZE) dynentcache[i].frame = 0; if(!dynentframe) dynentframe = 1; } VARF(dynentsize, 4, 7, 12, cleardynentcache()); #define DYNENTHASH(x, y) (((((x)^(y))<<5) + (((x)^(y))>>5)) & (DYNENTCACHESIZE - 1)) const vector &checkdynentcache(int x, int y) { dynentcacheentry &dec = dynentcache[DYNENTHASH(x, y)]; if(dec.x == x && dec.y == y && dec.frame == dynentframe) return dec.dynents; dec.x = x; dec.y = y; dec.frame = dynentframe; dec.dynents.shrink(0); int numdyns = game::numdynents(), dsize = 1<state != CS_ALIVE || d->o.x+d->radius <= dx || d->o.x-d->radius >= dx+dsize || d->o.y+d->radius <= dy || d->o.y-d->radius >= dy+dsize) continue; dec.dynents.add(d); } return dec.dynents; } #define loopdynentcache(curx, cury, o, radius) \ for(int curx = max(int(o.x-radius), 0)>>dynentsize, endx = min(int(o.x+radius), worldsize-1)>>dynentsize; curx <= endx; curx++) \ for(int cury = max(int(o.y-radius), 0)>>dynentsize, endy = min(int(o.y+radius), worldsize-1)>>dynentsize; cury <= endy; cury++) void updatedynentcache(physent *d) { loopdynentcache(x, y, d->o, d->radius) { dynentcacheentry &dec = dynentcache[DYNENTHASH(x, y)]; if(dec.x != x || dec.y != y || dec.frame != dynentframe || dec.dynents.find(d) >= 0) continue; dec.dynents.add(d); } } bool overlapsdynent(const vec &o, float radius) { loopdynentcache(x, y, o, radius) { const vector &dynents = checkdynentcache(x, y); loopv(dynents) { physent *d = dynents[i]; if(o.dist(d->o)-d->radius < radius) return true; } } return false; } template static inline bool plcollide(physent *d, const vec &dir, physent *o) { E entvol(d); O obvol(o); vec cp; if(mpr::collide(entvol, obvol, NULL, NULL, &cp)) { vec wn = vec(cp).sub(obvol.center()); wall = obvol.contactface(wn, dir.iszero() ? vec(wn).neg() : dir); if(!wall.iszero()) return false; inside = true; } return true; } bool plcollide(physent *d, const vec &dir) // collide with player or monster { if(d->type==ENT_CAMERA || d->state!=CS_ALIVE) return true; loopdynentcache(x, y, d->o, d->radius) { const vector &dynents = checkdynentcache(x, y); loopv(dynents) { physent *o = dynents[i]; if(o==d || d->o.reject(o->o, d->radius+o->radius)) continue; switch(d->collidetype) { case COLLIDE_ELLIPSE: if(o->collidetype == COLLIDE_ELLIPSE) { if(ellipsecollide(d, dir, o->o, vec(0, 0, 0), o->yaw, o->xradius, o->yradius, o->aboveeye, o->eyeheight)) continue; } else if(ellipserectcollide(d, dir, o->o, vec(0, 0, 0), o->yaw, o->xradius, o->yradius, o->aboveeye, o->eyeheight)) continue; break; case COLLIDE_OBB: if(o->collidetype == COLLIDE_ELLIPSE) { if(plcollide(d, dir, o)) continue; } else if(plcollide(d, dir, o)) continue; break; case COLLIDE_AABB: default: if(rectcollide(d, dir, o->o, o->collidetype == COLLIDE_AABB ? o->xradius : o->radius, o->collidetype == COLLIDE_AABB ? o->yradius : o->radius, o->aboveeye, o->eyeheight)) continue; break; } hitplayer = o; game::dynentcollide(d, o, wall); return false; } } return true; } void rotatebb(vec ¢er, vec &radius, int yaw) { if(yaw < 0) yaw = 360 + yaw%360; else if(yaw >= 360) yaw %= 360; const vec2 &rot = sincos360[yaw]; vec2 oldcenter(center), oldradius(radius); center.x = oldcenter.x*rot.x - oldcenter.y*rot.y; center.y = oldcenter.y*rot.x + oldcenter.x*rot.y; radius.x = fabs(oldradius.x*rot.x) + fabs(oldradius.y*rot.y); radius.y = fabs(oldradius.y*rot.x) + fabs(oldradius.x*rot.y); } template static inline bool mmcollide(physent *d, const vec &dir, const extentity &e, const vec ¢er, const vec &radius, float yaw) { E entvol(d); M mdlvol(e.o, center, radius, yaw); vec cp; if(mpr::collide(entvol, mdlvol, NULL, NULL, &cp)) { vec wn = vec(cp).sub(mdlvol.center()); wall = mdlvol.contactface(wn, dir.iszero() ? vec(wn).neg() : dir); if(!wall.iszero()) return false; inside = true; } return true; } bool mmcollide(physent *d, const vec &dir, octaentities &oc) // collide with a mapmodel { const vector &ents = entities::getents(); loopv(oc.mapmodels) { extentity &e = *ents[oc.mapmodels[i]]; if(e.flags&extentity::F_NOCOLLIDE) continue; model *m = loadmodel(NULL, e.attr[1]); if(!m || !m->collide) continue; vec center, radius; m->collisionbox(0, center, radius); float yaw = e.attr[0]; switch(d->collidetype) { case COLLIDE_ELLIPSE: if(m->ellipsecollide) { //if(!mmcollide(d, dir, e, center, radius, yaw)) return false; if(!ellipsecollide(d, dir, e.o, center, yaw, radius.x, radius.y, radius.z, radius.z)) return false; } //else if(!mmcollide(d, dir, e, center, radius, yaw)) return false; else if(!ellipserectcollide(d, dir, e.o, center, yaw, radius.x, radius.y, radius.z, radius.z)) return false; break; case COLLIDE_OBB: if(m->ellipsecollide) { if(!mmcollide(d, dir, e, center, radius, yaw)) return false; } else if(!mmcollide(d, dir, e, center, radius, yaw)) return false; break; case COLLIDE_AABB: default: rotatebb(center, radius, e.attr[0]); if(!rectcollide(d, dir, center.add(e.o), radius.x, radius.y, radius.z, radius.z)) return false; break; } } return true; } template static bool fuzzycollidesolid(physent *d, const vec &dir, float cutoff, cube &c, const ivec &co, int size) // collide with solid cube geometry { int crad = size/2; if(fabs(d->o.x - co.x - crad) > d->radius + crad || fabs(d->o.y - co.y - crad) > d->radius + crad || d->o.z + d->aboveeye < co.z || d->o.z - d->eyeheight > co.z + size) return true; E entvol(d); wall = vec(0, 0, 0); float bestdist = -1e10f; int visible = isentirelysolid(c) ? c.collide : 0xFF; loopi(6) if(visible&(1< 0) return true; if(dist <= bestdist) continue; if(!dir.iszero()) { if(w.dot(dir) >= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } wall = w; bestdist = dist; } if(wall.iszero()) { inside = true; return true; } return false; } template static inline bool clampcollide(const clipplanes &p, const E &entvol, const plane &w, const vec &pw) { if(w.x && (w.y || w.z) && fabs(pw.x - p.o.x) > p.r.x) { vec c = entvol.center(); float fv = pw.x < p.o.x ? p.o.x-p.r.x : p.o.x+p.r.x, fdist = (w.x*fv + w.y*c.y + w.z*c.z + w.offset) / (w.y*w.y + w.z*w.z); vec fdir(fv - c.x, -w.y*fdist, -w.z*fdist); if(entvol.supportpoint(fdir).squaredist(c) < fdir.squaredlen()) return true; } if(w.y && (w.x || w.z) && fabs(pw.y - p.o.y) > p.r.y) { vec c = entvol.center(); float fv = pw.y < p.o.y ? p.o.y-p.r.y : p.o.y+p.r.y, fdist = (w.x*c.x + w.y*fv + w.z*c.z + w.offset) / (w.x*w.x + w.z*w.z); vec fdir(-w.x*fdist, fv - c.y, -w.z*fdist); if(entvol.supportpoint(fdir).squaredist(c) < fdir.squaredlen()) return true; } if(w.z && (w.x || w.y) && fabs(pw.z - p.o.z) > p.r.z) { vec c = entvol.center(); float fv = pw.z < p.o.z ? p.o.z-p.r.z : p.o.z+p.r.z, fdist = (w.x*c.x + w.y*c.y + w.z*fv + w.offset) / (w.x*w.x + w.y*w.y); vec fdir(-w.x*fdist, -w.y*fdist, fv - c.z); if(entvol.supportpoint(fdir).squaredist(c) < fdir.squaredlen()) return true; } return false; } template static bool fuzzycollideplanes(physent *d, const vec &dir, float cutoff, cube &c, const ivec &co, int size) // collide with deformed cube geometry { clipplanes &p = getclipplanes(c, co, size); if(fabs(d->o.x - p.o.x) > p.r.x + d->radius || fabs(d->o.y - p.o.y) > p.r.y + d->radius || d->o.z + d->aboveeye < p.o.z - p.r.z || d->o.z - d->eyeheight > p.o.z + p.r.z) return true; E entvol(d); wall = vec(0, 0, 0); float bestdist = -1e10f; loopi(6) if(p.visible&(1<= 0) return true; if(dist <= bestdist) continue; if(!dir.iszero()) { if(w.dot(dir) >= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } wall = w; bestdist = dist; } int bestplane = -1; loopi(p.size) { plane &w = p.p[i]; vec pw = entvol.supportpoint(vec(w).neg()); float dist = w.dist(pw); if(dist >= 0) return true; if(dist <= bestdist) continue; bestplane = -1; bestdist = dist; if(!dir.iszero()) { if(w.dot(dir) >= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } if(clampcollide(p, entvol, w, pw)) continue; bestplane = i; } if(bestplane >= 0) wall = p.p[bestplane]; else if(wall.iszero()) { inside = true; return true; } return false; } template static bool cubecollidesolid(physent *d, const vec &dir, float cutoff, cube &c, const ivec &co, int size) // collide with solid cube geometry { int crad = size/2; if(fabs(d->o.x - co.x - crad) > d->radius + crad || fabs(d->o.y - co.y - crad) > d->radius + crad || d->o.z + d->aboveeye < co.z || d->o.z - d->eyeheight > co.z + size) return true; E entvol(d); bool collided = mpr::collide(mpr::SolidCube(co, size), entvol); if(!collided) return true; wall = vec(0, 0, 0); float bestdist = -1e10f; int visible = isentirelysolid(c) ? c.collide : 0xFF; loopi(6) if(visible&(1<= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } wall = w; bestdist = dist; } if(wall.iszero()) { inside = true; return true; } return false; } template static bool cubecollideplanes(physent *d, const vec &dir, float cutoff, cube &c, const ivec &co, int size) // collide with deformed cube geometry { clipplanes &p = getclipplanes(c, co, size); if(fabs(d->o.x - p.o.x) > p.r.x + d->radius || fabs(d->o.y - p.o.y) > p.r.y + d->radius || d->o.z + d->aboveeye < p.o.z - p.r.z || d->o.z - d->eyeheight > p.o.z + p.r.z) return true; E entvol(d); bool collided = mpr::collide(mpr::CubePlanes(p), entvol); if(!collided) return true; wall = vec(0, 0, 0); float bestdist = -1e10f; loopi(6) if(p.visible&(1<= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } wall = w; bestdist = dist; } int bestplane = -1; loopi(p.size) { plane &w = p.p[i]; vec pw = entvol.supportpoint(vec(w).neg()); float dist = w.dist(pw); if(dist <= bestdist) continue; bestplane = -1; bestdist = dist; if(!dir.iszero()) { if(w.dot(dir) >= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } if(clampcollide(p, entvol, w, pw)) continue; bestplane = i; } if(bestplane >= 0) wall = p.p[bestplane]; else if(wall.iszero()) { inside = true; return true; } return false; } static inline bool cubecollide(physent *d, const vec &dir, float cutoff, cube &c, const ivec &co, int size, bool solid) { switch(d->collidetype) { case COLLIDE_AABB: if(isentirelysolid(c) || solid) { if(cutoff <= 0) { int crad = size/2; return rectcollide(d, dir, vec(co.x + crad, co.y + crad, co.z), crad, crad, size, 0, isentirelysolid(c) ? c.collide : 0xFF); } #if 0 else return cubecollidesolid(d, dir, cutoff, c, co, size); #else else return fuzzycollidesolid(d, dir, cutoff, c, co, size); #endif } else { #if 0 if(cutoff <= 0) { clipplanes &p = getclipplanes(c, co, size); if(!p.size) return rectcollide(d, dir, p.o, p.r.x, p.r.y, p.r.z, p.r.z, p.visible); } return cubecollideplanes(d, dir, cutoff, c, co, size); #else return fuzzycollideplanes(d, dir, cutoff, c, co, size); #endif } case COLLIDE_OBB: if(isentirelysolid(c) || solid) return cubecollidesolid(d, dir, cutoff, c, co, size); else return cubecollideplanes(d, dir, cutoff, c, co, size); case COLLIDE_ELLIPSE: default: if(d->type < ENT_CAMERA) { if(isentirelysolid(c) || solid) return fuzzycollidesolid(d, dir, cutoff, c, co, size); else return fuzzycollideplanes(d, dir, cutoff, c, co, size); } else if(isentirelysolid(c) || solid) return cubecollidesolid(d, dir, cutoff, c, co, size); else return cubecollideplanes(d, dir, cutoff, c, co, size); } } static inline bool octacollide(physent *d, const vec &dir, float cutoff, const ivec &bo, const ivec &bs, cube *c, const ivec &cor, int size) // collide with octants { loopoctabox(cor, size, bo, bs) { if(c[i].ext && c[i].ext->ents) if(!mmcollide(d, dir, *c[i].ext->ents)) return false; ivec o(i, cor.x, cor.y, cor.z, size); if(c[i].children) { if(!octacollide(d, dir, cutoff, bo, bs, c[i].children, o, size>>1)) return false; } else { bool solid = false; switch(c[i].material&MATF_CLIP) { case MAT_NOCLIP: continue; case MAT_GAMECLIP: if(d->type==ENT_AI) solid = true; break; case MAT_CLIP: if(isclipped(c[i].material&MATF_VOLUME) || d->type= uint(worldsize)) return octacollide(d, dir, cutoff, bo, bs, worldroot, ivec(0, 0, 0), worldsize>>1); cube *c = &worldroot[octastep(bo.x, bo.y, bo.z, scale)]; if(c->ext && c->ext->ents && !mmcollide(d, dir, *c->ext->ents)) return false; scale--; while(c->children && !(diff&(1<children[octastep(bo.x, bo.y, bo.z, scale)]; if(c->ext && c->ext->ents && !mmcollide(d, dir, *c->ext->ents)) return false; scale--; } if(c->children) return octacollide(d, dir, cutoff, bo, bs, c->children, ivec(bo).mask(~((2<material&MATF_CLIP) { case MAT_NOCLIP: return true; case MAT_GAMECLIP: if(d->type==ENT_AI) solid = true; break; case MAT_CLIP: if(isclipped(c->material&MATF_VOLUME) || d->typeo.x-d->radius), int(d->o.y-d->radius), int(d->o.z-d->eyeheight)), bs(int(d->radius*2), int(d->radius*2), int(d->eyeheight+d->aboveeye)); bs.add(2); // guard space for rounding errors if(!octacollide(d, dir, cutoff, bo, bs)) return false;//, worldroot, ivec(0, 0, 0), worldsize>>1)) return false; // collide with world return !playercol || plcollide(d, dir); } void recalcdir(physent *d, const vec &oldvel, vec &dir) { float speed = oldvel.magnitude(); if(speed > 1e-6f) { float step = dir.magnitude(); dir = d->vel; dir.add(d->falling); dir.mul(step/speed); } } void slideagainst(physent *d, vec &dir, const vec &obstacle, bool foundfloor, bool slidecollide) { vec wall(obstacle); if(foundfloor ? wall.z > 0 : slidecollide) { wall.z = 0; if(!wall.iszero()) wall.normalize(); } vec oldvel(d->vel); oldvel.add(d->falling); d->vel.project(wall); d->falling.project(wall); recalcdir(d, oldvel, dir); } void switchfloor(physent *d, vec &dir, const vec &floor) { if(floor.z >= FLOORZ) d->falling = vec(0, 0, 0); vec oldvel(d->vel); oldvel.add(d->falling); if(dir.dot(floor) >= 0) { if(d->physstate < PHYS_SLIDE || fabs(dir.dot(d->floor)) > 0.01f*dir.magnitude()) return; d->vel.projectxy(floor, 0.0f); } else d->vel.projectxy(floor); d->falling.project(floor); recalcdir(d, oldvel, dir); } bool trystepup(physent *d, vec &dir, const vec &obstacle, float maxstep, const vec &floor) { vec old(d->o), stairdir = (obstacle.z >= 0 && obstacle.z < SLOPEZ ? vec(-obstacle.x, -obstacle.y, 0) : vec(dir.x, dir.y, 0)).rescale(1); bool cansmooth = true; /* check if there is space atop the stair to move to */ if(d->physstate != PHYS_STEP_UP) { vec checkdir = stairdir; checkdir.mul(0.1f); checkdir.z += maxstep + 0.1f; d->o.add(checkdir); if(!collide(d)) { d->o = old; if(collide(d, vec(0, 0, -1), SLOPEZ)) return false; cansmooth = false; } } if(cansmooth) { vec checkdir = stairdir; checkdir.z += 1; checkdir.mul(maxstep); d->o = old; d->o.add(checkdir); int scale = 2; if(!collide(d, checkdir)) { if(collide(d, vec(0, 0, -1), SLOPEZ)) { d->o = old; return false; } d->o.add(checkdir); if(!collide(d, vec(0, 0, -1), SLOPEZ)) scale = 1; } if(scale != 1) { d->o = old; d->o.sub(checkdir.mul(vec(2, 2, 1))); if(collide(d, vec(0, 0, -1), SLOPEZ)) scale = 1; } d->o = old; vec smoothdir(dir.x, dir.y, 0); float magxy = smoothdir.magnitude(); if(magxy > 1e-9f) { if(magxy > scale*dir.z) { smoothdir.mul(1/magxy); smoothdir.z = 1.0f/scale; smoothdir.mul(dir.magnitude()/smoothdir.magnitude()); } else smoothdir.z = dir.z; d->o.add(smoothdir); d->o.z += maxstep + 0.1f; if(collide(d, smoothdir)) { d->o.z -= maxstep + 0.1f; if(d->physstate == PHYS_FALL || d->floor != floor) { d->timeinair = 0; d->floor = floor; switchfloor(d, dir, d->floor); } d->physstate = PHYS_STEP_UP; return true; } } } /* try stepping up */ d->o = old; d->o.z += dir.magnitude(); if(collide(d, vec(0, 0, 1))) { if(d->physstate == PHYS_FALL || d->floor != floor) { d->timeinair = 0; d->floor = floor; switchfloor(d, dir, d->floor); } if(cansmooth) d->physstate = PHYS_STEP_UP; return true; } d->o = old; return false; } bool trystepdown(physent *d, vec &dir, float step, float xy, float z, bool init = false) { vec stepdir(dir.x, dir.y, 0); stepdir.z = -stepdir.magnitude2()*z/xy; if(!stepdir.z) return false; stepdir.normalize(); vec old(d->o); d->o.add(vec(stepdir).mul(STAIRHEIGHT/fabs(stepdir.z))).z -= STAIRHEIGHT; d->zmargin = -STAIRHEIGHT; if(!collide(d, vec(0, 0, -1), SLOPEZ)) { d->o = old; d->o.add(vec(stepdir).mul(step)); d->zmargin = 0; if(collide(d, vec(0, 0, -1))) { vec stepfloor(stepdir); stepfloor.mul(-stepfloor.z).z += 1; stepfloor.normalize(); if(d->physstate >= PHYS_SLOPE && d->floor != stepfloor) { // prevent alternating step-down/step-up states if player would keep bumping into the same floor vec stepped(d->o); d->o.z -= 0.5f; d->zmargin = -0.5f; if(!collide(d, stepdir) && wall == d->floor) { d->o = old; if(!init) { d->o.x += dir.x; d->o.y += dir.y; if(dir.z <= 0 || !collide(d, dir)) d->o.z += dir.z; } d->zmargin = 0; d->physstate = PHYS_STEP_DOWN; d->timeinair = 0; return true; } d->o = init ? old : stepped; d->zmargin = 0; } else if(init) d->o = old; switchfloor(d, dir, stepfloor); d->floor = stepfloor; d->physstate = PHYS_STEP_DOWN; d->timeinair = 0; return true; } } d->o = old; d->zmargin = 0; return false; } bool trystepdown(physent *d, vec &dir, bool init = false) { if(!game::allowmove(d) || (!d->move && !d->strafe)) return false; vec old(d->o); d->o.z -= STAIRHEIGHT; d->zmargin = -STAIRHEIGHT; if(collide(d, vec(0, 0, -1), SLOPEZ)) { d->o = old; d->zmargin = 0; return false; } d->o = old; d->zmargin = 0; float step = dir.magnitude(); #if 1 // weaker check, just enough to avoid hopping up slopes if(trystepdown(d, dir, step, 4, 1, init)) return true; #else if(trystepdown(d, dir, step, 2, 1, init)) return true; if(trystepdown(d, dir, step, 1, 1, init)) return true; if(trystepdown(d, dir, step, 1, 2, init)) return true; #endif return false; } void falling(physent *d, vec &dir, const vec &floor) { if(floor.z > 0.0f && floor.z < SLOPEZ) { if(floor.z >= WALLZ) switchfloor(d, dir, floor); d->timeinair = 0; d->physstate = PHYS_SLIDE; d->floor = floor; } else if(d->physstate < PHYS_SLOPE || dir.dot(d->floor) > 0.01f*dir.magnitude() || (floor.z != 0.0f && floor.z != 1.0f) || !trystepdown(d, dir, true)) d->physstate = PHYS_FALL; } void landing(physent *d, vec &dir, const vec &floor, bool collided) { #if 0 if(d->physstate == PHYS_FALL) { d->timeinair = 0; if(dir.z < 0.0f) dir.z = d->vel.z = 0.0f; } #endif switchfloor(d, dir, floor); d->timeinair = 0; if((d->physstate!=PHYS_STEP_UP && d->physstate!=PHYS_STEP_DOWN) || !collided) d->physstate = floor.z >= FLOORZ ? PHYS_FLOOR : PHYS_SLOPE; d->floor = floor; } bool findfloor(physent *d, bool collided, const vec &obstacle, bool &slide, vec &floor) { bool found = false; vec moved(d->o); d->o.z -= 0.1f; if(!collide(d, vec(0, 0, -1), d->physstate == PHYS_SLOPE || d->physstate == PHYS_STEP_DOWN ? SLOPEZ : FLOORZ)) { floor = wall; found = true; } else if(collided && obstacle.z >= SLOPEZ) { floor = obstacle; found = true; slide = false; } else if(d->physstate == PHYS_STEP_UP || d->physstate == PHYS_SLIDE) { if(!collide(d, vec(0, 0, -1)) && wall.z > 0.0f) { floor = wall; if(floor.z >= SLOPEZ) found = true; } } else if(d->physstate >= PHYS_SLOPE && d->floor.z < 1.0f) { if(!collide(d, vec(d->floor).neg(), 0.95f) || !collide(d, vec(0, 0, -1))) { floor = wall; if(floor.z >= SLOPEZ && floor.z < 1.0f) found = true; } } if(collided && (!found || obstacle.z > floor.z)) { floor = obstacle; slide = !found && (floor.z < WALLZ || floor.z >= SLOPEZ); } d->o = moved; return found; } bool move(physent *d, vec &dir) { vec old(d->o); bool collided = false, slidecollide = false; vec obstacle; d->o.add(dir); if(!collide(d, dir) || ((d->type==ENT_AI || d->type==ENT_INANIMATE) && !collide(d, vec(0, 0, 0), 0, false))) { obstacle = wall; /* check to see if there is an obstacle that would prevent this one from being used as a floor (or ceiling bump) */ if(d->type==ENT_PLAYER && ((wall.z>=SLOPEZ && dir.z<0) || (wall.z<=-SLOPEZ && dir.z>0)) && (dir.x || dir.y) && !collide(d, vec(dir.x, dir.y, 0))) { if(wall.dot(dir) >= 0) slidecollide = true; obstacle = wall; } d->o = old; d->o.z -= STAIRHEIGHT; d->zmargin = -STAIRHEIGHT; if(d->physstate == PHYS_SLOPE || d->physstate == PHYS_FLOOR || (!collide(d, vec(0, 0, -1), SLOPEZ) && (d->physstate==PHYS_STEP_UP || d->physstate==PHYS_STEP_DOWN || wall.z>=FLOORZ))) { d->o = old; d->zmargin = 0; if(trystepup(d, dir, obstacle, STAIRHEIGHT, d->physstate == PHYS_SLOPE || d->physstate == PHYS_FLOOR ? d->floor : vec(wall))) return true; } else { d->o = old; d->zmargin = 0; } /* can't step over the obstacle, so just slide against it */ collided = true; } else if(d->physstate == PHYS_STEP_UP) { if(!collide(d, vec(0, 0, -1), SLOPEZ)) { d->o = old; if(trystepup(d, dir, vec(0, 0, 1), STAIRHEIGHT, vec(wall))) return true; d->o.add(dir); } } else if(d->physstate == PHYS_STEP_DOWN && dir.dot(d->floor) <= 1e-6f) { vec moved(d->o); d->o = old; if(trystepdown(d, dir)) return true; d->o = moved; } vec floor(0, 0, 0); bool slide = collided, found = findfloor(d, collided, obstacle, slide, floor); if(slide || (!collided && floor.z > 0 && floor.z < WALLZ)) { slideagainst(d, dir, slide ? obstacle : floor, found, slidecollide); //if(d->type == ENT_AI || d->type == ENT_INANIMATE) d->blocked = true; } if(found) landing(d, dir, floor, collided); else falling(d, dir, floor); return !collided; } bool bounce(physent *d, float secs, float elasticity, float waterfric) { // make sure bouncers don't start inside geometry if(d->physstate!=PHYS_BOUNCE && !collide(d, vec(0, 0, 0), 0, false)) return true; int mat = lookupmaterial(vec(d->o.x, d->o.y, d->o.z + (d->aboveeye - d->eyeheight)/2)); bool water = isliquid(mat); if(water) { d->vel.z -= gravity/16*secs; d->vel.mul(max(1.0f - secs/waterfric, 0.0f)); } else d->vel.z -= gravity*secs; vec old(d->o); loopi(2) { vec dir(d->vel); dir.mul(secs); d->o.add(dir); if(collide(d, dir)) { if(inside) { d->o = old; d->vel.mul(-elasticity); } break; } else if(hitplayer) break; d->o = old; game::bounced(d, wall); float c = wall.dot(d->vel), k = 1.0f + (1.0f-elasticity)*c/d->vel.magnitude(); d->vel.mul(k); d->vel.sub(vec(wall).mul(elasticity*2.0f*c)); } if(d->physstate!=PHYS_BOUNCE) { // make sure bouncers don't start inside geometry if(d->o == old) return !hitplayer; d->physstate = PHYS_BOUNCE; } return hitplayer!=0; } void avoidcollision(physent *d, const vec &dir, physent *obstacle, float space) { float rad = obstacle->radius+d->radius; vec bbmin(obstacle->o); bbmin.x -= rad; bbmin.y -= rad; bbmin.z -= obstacle->eyeheight+d->aboveeye; bbmin.sub(space); vec bbmax(obstacle->o); bbmax.x += rad; bbmax.y += rad; bbmax.z += obstacle->aboveeye+d->eyeheight; bbmax.add(space); loopi(3) if(d->o[i] <= bbmin[i] || d->o[i] >= bbmax[i]) return; float mindist = 1e16f; loopi(3) if(dir[i] != 0) { float dist = ((dir[i] > 0 ? bbmax[i] : bbmin[i]) - d->o[i]) / dir[i]; mindist = min(mindist, dist); } if(mindist >= 0.0f && mindist < 1e15f) d->o.add(vec(dir).mul(mindist)); } bool movecamera(physent *pl, const vec &dir, float dist, float stepdist) { int steps = (int)ceil(dist/stepdist); if(steps <= 0) return true; vec d(dir); d.mul(dist/steps); loopi(steps) { vec oldpos(pl->o); pl->o.add(d); if(!collide(pl, vec(0, 0, 0), 0, false)) { pl->o = oldpos; return false; } } return true; } bool droptofloor(vec &o, float radius, float height) { static struct dropent : physent { dropent() { type = ENT_CAMERA; collidetype = COLLIDE_AABB; vel = vec(0, 0, -1); } } d; d.o = o; if(!insideworld(d.o)) { if(d.o.z < worldsize) return false; d.o.z = worldsize - 1e-3f; if(!insideworld(d.o)) return false; } vec v(0.0001f, 0.0001f, -1); v.normalize(); if(raycube(d.o, v, worldsize) >= worldsize) return false; d.radius = d.xradius = d.yradius = radius; d.eyeheight = height; d.aboveeye = radius; if(!movecamera(&d, d.vel, worldsize, 1)) { o = d.o; return true; } return false; } float dropheight(entity &e) { switch(e.type) { case ET_PARTICLES: case ET_MAPMODEL: return 0.0f; default: if(e.type >= ET_GAMESPECIFIC) return entities::dropheight(e); return 4.0f; } } void dropenttofloor(entity *e) { droptofloor(e->o, 1.0f, dropheight(*e)); } void phystest() { static const char *states[] = {"float", "fall", "slide", "slope", "floor", "step up", "step down", "bounce"}; printf ("PHYS(pl): %s, air %d, floor: (%f, %f, %f), vel: (%f, %f, %f), g: (%f, %f, %f)\n", states[player->physstate], player->timeinair, player->floor.x, player->floor.y, player->floor.z, player->vel.x, player->vel.y, player->vel.z, player->falling.x, player->falling.y, player->falling.z); printf ("PHYS(cam): %s, air %d, floor: (%f, %f, %f), vel: (%f, %f, %f), g: (%f, %f, %f)\n", states[camera1->physstate], camera1->timeinair, camera1->floor.x, camera1->floor.y, camera1->floor.z, camera1->vel.x, camera1->vel.y, camera1->vel.z, camera1->falling.x, camera1->falling.y, camera1->falling.z); } COMMAND(phystest, ""); void vecfromyawpitch(float yaw, float pitch, int move, int strafe, vec &m) { if(move) { m.x = move*-sinf(RAD*yaw); m.y = move*cosf(RAD*yaw); } else m.x = m.y = 0; if(pitch) { m.x *= cosf(RAD*pitch); m.y *= cosf(RAD*pitch); m.z = move*sinf(RAD*pitch); } else m.z = 0; if(strafe) { m.x += strafe*cosf(RAD*yaw); m.y += strafe*sinf(RAD*yaw); } } void vectoyawpitch(const vec &v, float &yaw, float &pitch) { yaw = -atan2(v.x, v.y)/RAD; pitch = asin(v.z/v.magnitude())/RAD; } VARP(maxroll, 0, 3, 20); FVAR(straferoll, 0, 0.033f, 90); VAR(floatspeed, 10, 100, 10000); void modifyvelocity(physent *pl, bool local, bool water, bool floating, int curtime) { if(floating) { if(pl->jumping) { pl->jumping = false; pl->vel.z = max(pl->vel.z, pl->jumpvel * (jumpvel / 200.0f)); pl->lastjump = lastmillis; } } else if(pl->physstate >= PHYS_SLOPE || water || game::allowdoublejump()) { if(water && !pl->inwater) pl->vel.div(8); if(pl->jumping) { pl->jumping = false; if(pl->physstate < PHYS_SLOPE && !water) { particle_splash(PART_STEAM, 80, 200, vec(pl->o.x, pl->o.y, pl->o.z-pl->eyeheight), 0xBFBFBF, 2, 150, -10); //double jump pl->falling.div(8); } pl->vel.z = max(pl->vel.z, pl->jumpvel * (jumpvel / 200.0f)); // physics impulse upwards pl->lastjump = lastmillis; if(water) { pl->vel.x /= 8.0f; pl->vel.y /= 8.0f; } // dampen velocity change even harder, gives correct water feel game::physicstrigger(pl, local, 1, 0); } } if(!floating && pl->physstate == PHYS_FALL) pl->timeinair += curtime; vec m(0.0f, 0.0f, 0.0f); if(game::allowmove(pl) && (pl->move || pl->strafe)) { vecfromyawpitch(pl->yaw, floating || water || pl->type==ENT_CAMERA ? pl->pitch : 0, pl->move, pl->strafe, m); if(!floating && pl->physstate >= PHYS_SLOPE) { /* move up or down slopes in air * but only move up slopes in water */ float dz = -(m.x*pl->floor.x + m.y*pl->floor.y)/pl->floor.z; m.z = water ? max(m.z, dz) : dz; } m.normalize(); } if(editmode && pl->altitude) {m.z = pl->altitude;} vec d(m); d.mul(pl->maxspeed); if(pl->type==ENT_PLAYER) { if(!floating) { d.mul(movespeed/100.0f); } if(floating) { if(pl==player) d.mul(floatspeed/pl->maxspeed); } else if(!water && game::allowmove(pl)) d.mul((pl->move && !pl->strafe ? 1.3f : 1.0f) * (pl->physstate < PHYS_SLOPE ? 1.3f : 1.0f)); // EXPERIMENTAL } float fric = water && !floating ? 20.0f : (pl->physstate >= PHYS_SLOPE || floating ? 6.0f : 30.0f); pl->vel.lerp(d, pl->vel, pow(1 - 1/fric, curtime/20.0f)); // old fps friction // float friction = water && !floating ? 20.0f : (pl->physstate >= PHYS_SLOPE || floating ? 6.0f : 30.0f); // float fpsfric = min(curtime/(20.0f*friction), 1.0f); // pl->vel.lerp(pl->vel, d, fpsfric); } void modifygravity(physent *pl, bool water, int curtime) { float secs = curtime/1000.0f; vec g(0, 0, 0); if(pl->physstate == PHYS_FALL) g.z -= gravity*secs; else if(pl->floor.z > 0 && pl->floor.z < FLOORZ) { g.z = -1; g.project(pl->floor); g.normalize(); g.mul(gravity*secs); } if(!water || !game::allowmove(pl) || (!pl->move && !pl->strafe)) pl->falling.add(g); if(water || pl->physstate >= PHYS_SLOPE) { float fric = water ? 2.0f : 6.0f, c = water ? 1.0f : clamp((pl->floor.z - SLOPEZ)/(FLOORZ-SLOPEZ), 0.0f, 1.0f); pl->falling.mul(pow(1 - c/fric, curtime/20.0f)); // old fps friction // float friction = water ? 2.0f : 6.0f, // fpsfric = friction/curtime*20.0f, // c = water ? 1.0f : clamp((pl->floor.z - SLOPEZ)/(FLOORZ-SLOPEZ), 0.0f, 1.0f); // pl->falling.mul(1 - c/fpsfric); } } // main physics routine, moves a player/monster for a curtime step // moveres indicated the physics precision (which is lower for monsters and multiplayer prediction) // local is false for multiplayer prediction VARR(nastylava, 0, 1, 1); bool moveplayer(physent *pl, int moveres, bool local, int curtime) { int material = lookupmaterial(vec(pl->o.x, pl->o.y, pl->o.z + (3*pl->aboveeye - pl->eyeheight)/4)); bool water = isliquid(material&MATF_VOLUME); bool floating = pl->type==ENT_PLAYER && (pl->state==CS_EDITING || pl->state==CS_SPECTATOR); float secs = curtime/1000.f; // apply gravity if(!floating) modifygravity(pl, water, curtime); // apply any player generated changes in velocity modifyvelocity(pl, local, water, floating, curtime); vec d(pl->vel), oldpos(pl->o); if(!floating && water) d.mul(0.5f); d.add(pl->falling); d.mul(secs); pl->blocked = false; if(floating) // just apply velocity { if(pl->physstate != PHYS_FLOAT) { pl->physstate = PHYS_FLOAT; pl->timeinair = 0; pl->falling = vec(0, 0, 0); } pl->o.add(d); } else // apply velocity with collision { const float f = 1.0f/moveres; const int timeinair = pl->timeinair; int collisions = 0; d.mul(f); loopi(moveres) if(!move(pl, d) && ++collisions<5) i--; // discrete steps collision detection & sliding if(timeinair > 800 && !pl->timeinair && !water) // if we land after long time must have been a high jump, make thud sound { game::physicstrigger(pl, local, -1, 0); } } if(pl->state==CS_ALIVE) updatedynentcache(pl); // automatically apply smooth roll when strafing if(pl->strafe==0) { pl->roll = pl->roll/(1+(float)sqrtf((float)curtime)/25); } else { pl->roll -= pl->strafe*curtime*straferoll; if(pl->roll > maxroll) pl->roll = maxroll; else if(pl->roll < -maxroll) pl->roll = -maxroll; } // play sounds on water transitions if(pl->inwater && !water) { material = lookupmaterial(vec(pl->o.x, pl->o.y, pl->o.z + (pl->aboveeye - pl->eyeheight)/2)); water = isliquid(material&MATF_VOLUME); } if(!pl->inwater && water) game::physicstrigger(pl, local, 0, -1, material&MATF_VOLUME); else if(pl->inwater && !water) game::physicstrigger(pl, local, 0, 1, pl->inwater); pl->inwater = water ? material&MATF_VOLUME : MAT_AIR; if(pl->state==CS_ALIVE && (pl->o.z < 0 || (material&MAT_DEATH && nastylava))) game::suicide(pl); return true; } #define PHYSFRAMETIME 5 int physsteps = 0, physframetime = PHYSFRAMETIME, lastphysframe = 0; void physicsframe() // optimally schedule physics frames inside the graphics frames { int diff = lastmillis - lastphysframe; if(diff <= 0) physsteps = 0; else { extern int gamespeed; physframetime = clamp((PHYSFRAMETIME*gamespeed)/100, 1, PHYSFRAMETIME); physsteps = (diff + physframetime - 1)/physframetime; lastphysframe += physsteps * physframetime; } cleardynentcache(); } VAR(physinterp, 0, 1, 1); void interppos(physent *pl) { pl->o = pl->newpos; int diff = lastphysframe - lastmillis; if(diff <= 0 || !physinterp) return; vec deltapos(pl->deltapos); deltapos.mul(min(diff, physframetime)/float(physframetime)); pl->o.add(deltapos); } void moveplayer(physent *pl, int moveres, bool local) { if(physsteps <= 0) { if(local) interppos(pl); return; } if(local) pl->o = pl->newpos; loopi(physsteps-1) moveplayer(pl, moveres, local, physframetime); if(local) pl->deltapos = pl->o; moveplayer(pl, moveres, local, physframetime); if(local) { pl->newpos = pl->o; pl->deltapos.sub(pl->newpos); interppos(pl); } } bool bounce(physent *d, float elasticity, float waterfric) { if(physsteps <= 0) { interppos(d); return false; } d->o = d->newpos; bool hitplayer = false; loopi(physsteps-1) { if(bounce(d, physframetime/1000.0f, elasticity, waterfric)) hitplayer = true; } d->deltapos = d->o; if(bounce(d, physframetime/1000.0f, elasticity, waterfric)) hitplayer = true; d->newpos = d->o; d->deltapos.sub(d->newpos); interppos(d); return hitplayer; } void updatephysstate(physent *d) { if(d->physstate == PHYS_FALL) return; d->timeinair = 0; vec old(d->o); /* Attempt to reconstruct the floor state. * May be inaccurate since movement collisions are not considered. * If good floor is not found, just keep the old floor and hope it's correct enough. */ switch(d->physstate) { case PHYS_SLOPE: case PHYS_FLOOR: case PHYS_STEP_DOWN: d->o.z -= 0.15f; if(!collide(d, vec(0, 0, -1), d->physstate == PHYS_SLOPE || d->physstate == PHYS_STEP_DOWN ? SLOPEZ : FLOORZ)) d->floor = wall; break; case PHYS_STEP_UP: d->o.z -= STAIRHEIGHT+0.15f; if(!collide(d, vec(0, 0, -1), SLOPEZ)) d->floor = wall; break; case PHYS_SLIDE: d->o.z -= .15f; if(!collide(d, vec(0, 0, -1)) && wall.z < SLOPEZ) d->floor = wall; break; } if(d->physstate > PHYS_FALL && d->floor.z <= 0) d->floor = vec(0, 0, 1); d->o = old; } const float PLATFORMMARGIN = 0.2f; const float PLATFORMBORDER = 10.0f; struct platforment { physent *d; int stacks, chains; platforment() {} platforment(physent *d) : d(d), stacks(-1), chains(-1) {} bool operator==(const physent *o) const { return d == o; } }; struct platformcollision { platforment *ent; int next; platformcollision() {} platformcollision(platforment *ent, int next) : ent(ent), next(next) {} }; template static inline bool platformcollide(physent *d, const vec &dir, physent *o, float margin) { E entvol(d); O obvol(o, margin); vec cp; if(mpr::collide(entvol, obvol, NULL, NULL, &cp)) { vec wn = vec(cp).sub(obvol.center()); return obvol.contactface(wn, dir.iszero() ? vec(wn).neg() : dir).iszero(); } return true; } bool platformcollide(physent *d, physent *o, const vec &dir, float margin = 0) { if(d->collidetype == COLLIDE_ELLIPSE) { if(o->collidetype == COLLIDE_ELLIPSE) return ellipsecollide(d, dir, o->o, vec(0, 0, 0), o->yaw, o->xradius, o->yradius, o->aboveeye, o->eyeheight + margin); else return ellipserectcollide(d, dir, o->o, vec(0, 0, 0), o->yaw, o->xradius, o->yradius, o->aboveeye, o->eyeheight + margin); } else if(o->collidetype == COLLIDE_ELLIPSE) return platformcollide(d, dir, o, margin); else return platformcollide(d, dir, o, margin); } bool moveplatform(physent *p, const vec &dir) { if(!insideworld(p->newpos)) return false; vec oldpos(p->o); (p->o = p->newpos).add(dir); if(!collide(p, dir, 0, dir.z<=0)) { p->o = oldpos; return false; } p->o = oldpos; static vector ents; ents.setsize(0); for(int x = int(max(p->o.x-p->radius-PLATFORMBORDER, 0.0f))>>dynentsize, ex = int(min(p->o.x+p->radius+PLATFORMBORDER, worldsize-1.0f))>>dynentsize; x <= ex; x++) for(int y = int(max(p->o.y-p->radius-PLATFORMBORDER, 0.0f))>>dynentsize, ey = int(min(p->o.y+p->radius+PLATFORMBORDER, worldsize-1.0f))>>dynentsize; y <= ey; y++) { const vector &dynents = checkdynentcache(x, y); loopv(dynents) { physent *d = dynents[i]; if(p==d || d->o.z-d->eyeheight < p->o.z+p->aboveeye || p->o.reject(d->o, p->radius+PLATFORMBORDER+d->radius) || ents.find(d) >= 0) continue; ents.add(d); } } static vector passengers, colliders; passengers.setsize(0); colliders.setsize(0); static vector collisions; collisions.setsize(0); // build up collision DAG of colliders to be pushed off, and DAG of stacked passengers loopv(ents) { platforment &ent = ents[i]; physent *d = ent.d; // check if the dynent is on top of the platform if(!platformcollide(p, d, vec(0, 0, 1), PLATFORMMARGIN)) passengers.add(&ent); vec doldpos(d->o); (d->o = d->newpos).add(dir); if(!collide(d, dir, 0, false)) colliders.add(&ent); d->o = doldpos; loopvj(ents) { platforment &o = ents[j]; if(!platformcollide(d, o.d, dir)) { collisions.add(platformcollision(&ent, o.chains)); o.chains = collisions.length() - 1; } if(d->o.z < o.d->o.z && !platformcollide(d, o.d, vec(0, 0, 1), PLATFORMMARGIN)) { collisions.add(platformcollision(&o, ent.stacks)); ent.stacks = collisions.length() - 1; } } } loopv(colliders) // propagate collisions { platforment *ent = colliders[i]; for(int n = ent->chains; n>=0; n = collisions[n].next) { platforment *o = collisions[n].ent; if(colliders.find(o)<0) colliders.add(o); } } if(dir.z>0) { loopv(passengers) // if any stacked passengers collide, stop the platform { platforment *ent = passengers[i]; if(colliders.find(ent)>=0) return false; for(int n = ent->stacks; n>=0; n = collisions[n].next) { platforment *o = collisions[n].ent; if(passengers.find(o)<0) passengers.add(o); } } loopv(passengers) { physent *d = passengers[i]->d; d->o.add(dir); d->newpos.add(dir); if(dir.x || dir.y) updatedynentcache(d); } } else loopv(passengers) // move any stacked passengers who aren't colliding with non-passengers { platforment *ent = passengers[i]; if(colliders.find(ent)>=0) continue; physent *d = ent->d; d->o.add(dir); d->newpos.add(dir); if(dir.x || dir.y) updatedynentcache(d); for(int n = ent->stacks; n>=0; n = collisions[n].next) { platforment *o = collisions[n].ent; if(passengers.find(o)<0) passengers.add(o); } } p->o.add(dir); p->newpos.add(dir); if(dir.x || dir.y) updatedynentcache(p); return true; } #define dir(name,v,d,s,os) ICOMMAND(name, "D", (int *down), { player->s = *down!=0; player->v = player->s ? d : (player->os ? -(d) : 0); }); dir(backward, move, -1, k_down, k_up); dir(forward, move, 1, k_up, k_down); dir(left, strafe, 1, k_left, k_right); dir(right, strafe, -1, k_right, k_left); dir(rise, altitude, 1, k_rise, k_des); dir(descent, altitude, -1, k_des, k_rise); ICOMMAND(jump, "D", (int *down), { if(!*down || game::canjump()) player->jumping = *down!=0; }); bool entinmap(dynent *d, bool avoidplayers) // brute force but effective way to find a free spawn spot in the map { d->o.z += d->eyeheight; // pos specified is at feet vec orig = d->o; loopi(100) // try max 100 times { if(i) { d->o = orig; d->o.x += (rnd(21)-10)*i/5; // increasing distance d->o.y += (rnd(21)-10)*i/5; d->o.z += (rnd(21)-10)*i/5; } if(collide(d) && !inside) { if(hitplayer) { if(!avoidplayers) continue; d->o = orig; d->resetinterp(); return false; } d->resetinterp(); return true; } } // leave ent at original pos, possibly stuck d->o = orig; d->resetinterp(); conoutf(CON_WARN, "can't find entity spawn spot! (%.1f, %.1f, %.1f)", d->o.x, d->o.y, d->o.z); return false; } sandboxgamemaker-2.7.1+dfsg/src/engine/3dgui.cpp0000664000175000017500000012465611660231274021445 0ustar showardshoward// creates multiple gui windows that float inside the 3d world // special feature is that its mostly *modeless*: you can use this menu while playing, without turning menus on or off // implementationwise, it is *stateless*: it keeps no internal gui structure, hit tests are instant, usage & implementation is greatly simplified #include "engine.h" #ifndef NEWGUI #include "textedit.h" HVARP(guirollovercolour, 0, 0x00FFC0, 0xFFFFFF); static bool layoutpass, actionon = false; static int mousebuttons = 0; static struct gui *windowhit = NULL; static float firstx, firsty; enum {FIELDCOMMIT, FIELDABORT, FIELDEDIT, FIELDSHOW, FIELDKEY}; static int fieldmode = FIELDSHOW; static bool fieldsactive = false; extern char *guioverlaytex, *guiskintex, *guislidertex; SVARP(guiicondir, "hud/2.2/icons"); static bool hascursor; static float cursorx = 0.5f, cursory = 0.5f; #define SHADOW 4 #define ICON_SIZE (FONTH-SHADOW) #define SKIN_W 256 #define SKIN_H 128 #define SKIN_SCALE 4 #define INSERT (3*SKIN_SCALE) VARP(guiautotab, 6, 16, 40); VARP(guiclicktab, 0, 1, 1); struct gui : g3d_gui { struct list { int parent, w, h, align; }; int nextlist; static vector lists; static float hitx, hity; static int curdepth, curlist, xsize, ysize, curx, cury; static bool shouldmergehits, shouldautotab; static void reset() { lists.shrink(0); } static int ty, tx, tpos, *tcurrent, tcolor; //tracking tab size and position since uses different layout method... void allowautotab(bool on) { shouldautotab = on; } void autotab() { if(tcurrent) { if(layoutpass && !tpos) tcurrent = NULL; //disable tabs because you didn't start with one if(shouldautotab && !curdepth && (layoutpass ? 0 : cury) + ysize > guiautotab*FONTH) tab(NULL, tcolor); } } bool shouldtab() { if(tcurrent && shouldautotab) { if(layoutpass) { int space = guiautotab*FONTH - ysize; if(space < 0) return true; int l = lists[curlist].parent; while(l >= 0) { space -= lists[l].h; if(space < 0) return true; l = lists[l].parent; } } else { int space = guiautotab*FONTH - cury; if(ysize > space) return true; int l = lists[curlist].parent; while(l >= 0) { if(lists[l].h > space) return true; l = lists[l].parent; } } } return false; } bool visible() { return (!tcurrent || tpos==*tcurrent) && !layoutpass; } //tab is always at top of page void tab(const char *name, int color) { if(curdepth != 0) return; if(color) tcolor = color; tpos++; if(!name) { static string title; formatstring(title)("%d", tpos); name = title; } int w = max(text_width(name) - 2*INSERT, 0); if(layoutpass) { ty = max(ty, ysize); ysize = 0; } else { cury = -ysize; int h = FONTH-2*INSERT, x1 = curx + tx, x2 = x1 + w + ((skinx[3]-skinx[2]) + (skinx[5]-skinx[4]))*SKIN_SCALE, y1 = cury - ((skiny[6]-skiny[1])-(skiny[3]-skiny[2]))*SKIN_SCALE-h, y2 = cury; bool hit = tcurrent && windowhit==this && hitx>=x1 && hity>=y1 && hitx=0) { lists[curlist].w = xsize; lists[curlist].h = ysize; } list &l = lists.add(); l.parent = curlist; l.align = align; curlist = lists.length()-1; xsize = ysize = 0; } else { int xpad = xsize, ypad = ysize; curlist = nextlist++; xsize = lists[curlist].w; ysize = lists[curlist].h; switch(align) { case 0: if(ishorizontal()) cury += max(ypad - ysize, 0)/2; else curx += max(xpad - xsize, 0)/2; break; case 1: if(ishorizontal()) cury += max(ypad - ysize, 0); else curx += max(xpad - xsize, 0); break; } } curdepth++; } void poplist() { list &l = lists[curlist]; if(layoutpass) { l.w = xsize; l.h = ysize; } curlist = l.parent; curdepth--; if(curlist>=0) { xsize = lists[curlist].w; ysize = lists[curlist].h; if(ishorizontal()) cury -= l.h; else curx -= l.w; layout(l.w, l.h); if(!layoutpass) switch(l.align) { case 0: if(ishorizontal()) cury -= max(ysize - l.h, 0)/2; else curx -= max(xsize - l.w, 0)/2; break; case 1: if(ishorizontal()) cury -= max(ysize - l.h, 0); else curx -= max(xsize - l.w, 0); break; } } } int text (const char *text, int color, const char *icon) { autotab(); return button_(text, color, icon, false, false); } int button(const char *text, int color, const char *icon) { autotab(); return button_(text, color, icon, true, false); } int title (const char *text, int color, const char *icon) { autotab(); return button_(text, color, icon, false, true); } void separator() { autotab(); line_(5); } void progress(float percent) { autotab(); line_(FONTH*2/5, percent); } //use to set min size (useful when you have progress bars) void strut(float size) { layout(isvertical() ? int(size*FONTW) : 0, isvertical() ? 0 : int(size*FONTH)); } //add space between list items void space(float size) { layout(isvertical() ? 0 : int(size*FONTW), isvertical() ? int(size*FONTH) : 0); } int layout(int w, int h) { if(layoutpass) { if(ishorizontal()) { xsize += w; ysize = max(ysize, h); } else { xsize = max(xsize, w); ysize += h; } return 0; } else { bool hit = ishit(w, h); if(ishorizontal()) curx += w; else cury += h; return (hit && visible()) ? mousebuttons|G3D_ROLLOVER : 0; } } void mergehits(bool on) { shouldmergehits = on; } bool ishit(int w, int h, int x = curx, int y = cury) { if(shouldmergehits) return windowhit==this && (ishorizontal() ? hitx>=x && hitx=y && hity=x && hity>=y && hitxmode==EDITORFOCUSED && (e!=currentfocus() || fieldmode == FIELDSHOW)) { if(strcmp(e->lines[0].text, initval)) e->clear(initval); } e->linewrap = (length<0); e->maxx = (e->linewrap) ? -1 : length; e->maxy = (height<=0)?1:-1; e->pixelwidth = abs(length)*FONTW; if(e->linewrap && e->maxy==1) { int temp; text_bounds(e->lines[0].text, temp, e->pixelheight, e->pixelwidth); //only single line editors can have variable height } else e->pixelheight = FONTH*max(height, 1); } int h = e->pixelheight; int w = e->pixelwidth + FONTW; bool wasvertical = isvertical(); if(wasvertical && e->maxy != 1) pushlist(); char *result = NULL; if(visible() && !layoutpass) { e->rendered = true; bool hit = ishit(w, h); if(hit) { if(mousebuttons&G3D_DOWN) //mouse request focus { if(fieldtype==FIELDKEY) e->clear(); useeditor(name, initmode, true); e->mark(false); fieldmode = fieldtype; } } bool editing = (fieldmode != FIELDSHOW) && (e==currentfocus()); if(hit && editing && (mousebuttons&G3D_PRESSED)!=0 && fieldtype==FIELDEDIT) e->hit(int(floor(hitx-(curx+FONTW/2))), int(floor(hity-cury)), (mousebuttons&G3D_DRAGGED)!=0); //mouse request position if(editing && ((fieldmode==FIELDCOMMIT) || (fieldmode==FIELDABORT) || !hit)) // commit field if user pressed enter or wandered out of focus { if(fieldmode==FIELDCOMMIT || (fieldmode!=FIELDABORT && !hit)) result = e->currentline().text; e->active = (e->mode!=EDITORFOCUSED); fieldmode = FIELDSHOW; } else fieldsactive = true; e->draw(curx+FONTW/2, cury, color, hit && editing); lineshader->set(); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); if(editing) glColor3ub(guirollovercolour >> 16, (guirollovercolour >> 8)&0xFF, guirollovercolour&0xFF); else glColor3ub(color>>16, (color>>8)&0xFF, color&0xFF); rect_(curx, cury, w, h, -1, true); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); defaultshader->set(); } layout(w, h); if(e->maxy != 1) { int slines = e->limitscrolly(); if(slines > 0) { int pos = e->scrolly; slider(e->scrolly, slines, 0, color, NULL, false); if(pos != e->scrolly) e->cy = e->scrolly; } if(wasvertical) poplist(); } return result; } void rect_(float x, float y, float w, float h, int usetc = -1, bool lines = false) { glBegin(lines ? GL_LINE_LOOP : GL_TRIANGLE_STRIP); static const GLfloat tc[4][2] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}}; if(usetc>=0) glTexCoord2fv(tc[usetc]); glVertex2f(x, y); if(usetc>=0) glTexCoord2fv(tc[(usetc+1)%4]); glVertex2f(x + w, y); if(lines) { if(usetc>=0) glTexCoord2fv(tc[(usetc+2)%4]); glVertex2f(x + w, y + h); } if(usetc>=0) glTexCoord2fv(tc[(usetc+3)%4]); glVertex2f(x, y + h); if(!lines) { if(usetc>=0) glTexCoord2fv(tc[(usetc+2)%4]); glVertex2f(x + w, y + h); } glEnd(); xtraverts += 4; } void text_(const char *text, int x, int y, int color, bool shadow) { if(shadow) draw_text(text, x+SHADOW, y+SHADOW, 0x00, 0x00, 0x00, -0xC0); draw_text(text, x, y, color>>16, (color>>8)&0xFF, color&0xFF); } void background(int color, int inheritw, int inherith) { if(layoutpass) return; glDisable(GL_TEXTURE_2D); notextureshader->set(); glColor4ub(color>>16, (color>>8)&0xFF, color&0xFF, 0x80); int w = xsize, h = ysize; if(inheritw>0) { int parentw = curlist; while(inheritw>0 && lists[parentw].parent>=0) { parentw = lists[parentw].parent; inheritw--; } w = lists[parentw].w; } if(inherith>0) { int parenth = curlist; while(inherith>0 && lists[parenth].parent>=0) { parenth = lists[parenth].parent; inherith--; } h = lists[parenth].h; } rect_(curx, cury, w, h); glEnable(GL_TEXTURE_2D); defaultshader->set(); } void icon_(Texture *t, bool overlaid, int x, int y, int size, bool hit) { float scale = float(size)/max(t->xs, t->ys); //scale and preserve aspect ratio float xs = t->xs*scale, ys = t->ys*scale; x += int((size-xs)/2); y += int((size-ys)/2); if(hit && actionon) { glDisable(GL_TEXTURE_2D); notextureshader->set(); glColor4f(0, 0, 0, 0.75f); rect_(x+SHADOW, y+SHADOW, xs, ys); glEnable(GL_TEXTURE_2D); defaultshader->set(); } static const float tc[4][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; const vec &color = hit ? vec((guirollovercolour >> 16) / 255.0f, ((guirollovercolour >> 8) & 0xFF) / 255.0f, (guirollovercolour & 0xFF) / 255.0f) : (overlaid ? vec(1, 1, 1) : light); glBindTexture(GL_TEXTURE_2D, t->id); glColor3fv(color.v); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x, y); glTexCoord2fv(tc[1]); glVertex2f(x+xs, y); glTexCoord2fv(tc[3]); glVertex2f(x, y+ys); glTexCoord2fv(tc[2]); glVertex2f(x+xs, y+ys); glEnd(); if(overlaid) { if(!overlaytex || overlaytex == notexture) { defformatstring(tname)("data/%s", guioverlaytex); overlaytex = textureload(tname, 3); } glBindTexture(GL_TEXTURE_2D, overlaytex->id); glColor3fv(light.v); rect_(x, y, xs, ys, 0); } } void previewslot(VSlot &vslot, bool overlaid, int x, int y, int size, bool hit) { Slot &slot = *vslot.slot; if(slot.sts.empty()) return; VSlot *layer = NULL; Texture *t = NULL, *glowtex = NULL, *layertex = NULL; if(slot.loaded) { t = slot.sts[0].t; if(t == notexture) return; Slot &slot = *vslot.slot; if(slot.texmask&(1<slot->sts.empty()) layertex = layer->slot->sts[0].t; } } else if(slot.thumbnail && slot.thumbnail != notexture) t = slot.thumbnail; else return; float xt = min(1.0f, t->xs/(float)t->ys), yt = min(1.0f, t->ys/(float)t->xs), xs = size, ys = size; if(hit && actionon) { glColor4f(0, 0, 0, 0.75f); glBindTexture(GL_TEXTURE_2D, t->id); glBegin(GL_TRIANGLE_FAN); rect_(x+SHADOW, y+SHADOW, xs, ys, 0); glEnd(); } static Shader *rgbonlyshader = NULL; if(!rgbonlyshader) rgbonlyshader = lookupshaderbyname("rgbonly"); rgbonlyshader->set(); const vec &color = hit ? vec((guirollovercolour >> 16) / 255.0f, ((guirollovercolour >> 8) & 0xFF) / 255.0f, (guirollovercolour & 0xFF) / 255.0f) : (overlaid ? vec(1, 1, 1) : light); float tc[4][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; int xoff = vslot.xoffset, yoff = vslot.yoffset; if(vslot.rotation) { if((vslot.rotation&5) == 1) { swap(xoff, yoff); loopk(4) swap(tc[k][0], tc[k][1]); } if(vslot.rotation >= 2 && vslot.rotation <= 4) { xoff *= -1; loopk(4) tc[k][0] *= -1; } if(vslot.rotation <= 2 || vslot.rotation == 5) { yoff *= -1; loopk(4) tc[k][1] *= -1; } } loopk(4) { tc[k][0] = tc[k][0]/xt - float(xoff)/t->xs; tc[k][1] = tc[k][1]/yt - float(yoff)/t->ys; } if(slot.loaded) glColor3f(color.x*vslot.colorscale.x, color.y*vslot.colorscale.y, color.z*vslot.colorscale.z); else glColor3fv(color.v); glBindTexture(GL_TEXTURE_2D, t->id); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x, y); glTexCoord2fv(tc[1]); glVertex2f(x+xs, y); glTexCoord2fv(tc[3]); glVertex2f(x, y+ys); glTexCoord2fv(tc[2]); glVertex2f(x+xs, y+ys); glEnd(); if(glowtex) { glBlendFunc(GL_SRC_ALPHA, GL_ONE); glBindTexture(GL_TEXTURE_2D, glowtex->id); if(hit || overlaid) glColor3f(color.x*vslot.glowcolor.x, color.y*vslot.glowcolor.y, color.z*vslot.glowcolor.z); else glColor3fv(vslot.glowcolor.v); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x, y); glTexCoord2fv(tc[1]); glVertex2f(x+xs, y); glTexCoord2fv(tc[3]); glVertex2f(x, y+ys); glTexCoord2fv(tc[2]); glVertex2f(x+xs, y+ys); glEnd(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } if(layertex) { glBindTexture(GL_TEXTURE_2D, layertex->id); glColor3f(color.x*layer->colorscale.x, color.y*layer->colorscale.y, color.z*layer->colorscale.z); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x+xs/2, y+ys/2); glTexCoord2fv(tc[1]); glVertex2f(x+xs, y+ys/2); glTexCoord2fv(tc[3]); glVertex2f(x+xs/2, y+ys); glTexCoord2fv(tc[2]); glVertex2f(x+xs, y+ys); glEnd(); } defaultshader->set(); if(overlaid) { if(!overlaytex || overlaytex == notexture) { defformatstring(tname)("data/%s", guioverlaytex); overlaytex = textureload(tname, 3); } glBindTexture(GL_TEXTURE_2D, overlaytex->id); glColor3fv(light.v); rect_(x, y, xs, ys, 0); } } void line_(int size, float percent = 1.0f) { if(visible()) { if(!slidertex || slidertex == notexture) { defformatstring(tname)("data/%s", guislidertex); slidertex = textureload(tname, 3); } glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, slidertex->id); if(percent < 0.99f) { glColor4f(light.x, light.y, light.z, 0.375f); if(ishorizontal()) rect_(curx + FONTH/2 - size, cury, size*2, ysize, 0); else rect_(curx, cury + FONTH/2 - size, xsize, size*2, 1); } glColor3fv(light.v); if(ishorizontal()) rect_(curx + FONTH/2 - size, cury + ysize*(1-percent), size*2, ysize*percent, 0); else rect_(curx, cury + FONTH/2 - size, xsize*percent, size*2, 1); } layout(ishorizontal() ? FONTH : 0, ishorizontal() ? 0 : FONTH); } void textbox(const char *text, int width, int height, int color) { width *= FONTW; height *= FONTH; int w, h; text_bounds(text, w, h, width); if(h > height) height = h; if(visible()) draw_text(text, curx, cury, color>>16, (color>>8)&0xFF, color&0xFF, 0xFF, -1, width); layout(width, height); } int button_(const char *text, int color, const char *icon, bool clickable, bool center) { const int padding = 10; int w = 0; if(icon) w += ICON_SIZE; if(icon && text) w += padding; if(text) w += text_width(text); if(visible()) { bool hit = ishit(w, FONTH); if(hit && clickable) color = guirollovercolour; int x = curx; if(isvertical() && center) x += (xsize-w)/2; if(icon) { if(!isspace(icon[0])) { defformatstring(tname)("data/%s/%s", guiicondir, icon); icon_(textureload(tname, 3), false, x, cury, ICON_SIZE, clickable && hit); } x += ICON_SIZE; } if(icon && text) x += padding; if(text) text_(text, x, cury, color, center || (hit && clickable && actionon)); } return layout(w, FONTH); } static Texture *skintex, *overlaytex, *slidertex; static const int skinx[], skiny[]; static const struct patch { ushort left, right, top, bottom; uchar flags; } patches[]; static void drawskin(int x, int y, int gapw, int gaph, int start, int n, int passes = 1, const vec &light = vec(1, 1, 1), float alpha = 0.80f)//int vleft, int vright, int vtop, int vbottom, int start, int n) { if(!skintex || skintex == notexture) { defformatstring(tname)("data/%s", guiskintex); skintex = textureload(tname, 3); } glBindTexture(GL_TEXTURE_2D, skintex->id); int gapx1 = INT_MAX, gapy1 = INT_MAX, gapx2 = INT_MAX, gapy2 = INT_MAX; float wscale = 1.0f/(SKIN_W*SKIN_SCALE), hscale = 1.0f/(SKIN_H*SKIN_SCALE); loopj(passes) { bool quads = false; if(passes>1) glDepthFunc(j ? GL_LEQUAL : GL_GREATER); glColor4f(j ? light.x : 1.0f, j ? light.y : 1.0f, j ? light.z : 1.0f, passes<=1 || j ? alpha : alpha/2); //ghost when its behind something in depth loopi(n) { const patch &p = patches[start+i]; int left = skinx[p.left]*SKIN_SCALE, right = skinx[p.right]*SKIN_SCALE, top = skiny[p.top]*SKIN_SCALE, bottom = skiny[p.bottom]*SKIN_SCALE; float tleft = left*wscale, tright = right*wscale, ttop = top*hscale, tbottom = bottom*hscale; if(p.flags&0x1) { gapx1 = left; gapx2 = right; } else if(left >= gapx2) { left += gapw - (gapx2-gapx1); right += gapw - (gapx2-gapx1); } if(p.flags&0x10) { gapy1 = top; gapy2 = bottom; } else if(top >= gapy2) { top += gaph - (gapy2-gapy1); bottom += gaph - (gapy2-gapy1); } //multiple tiled quads if necessary rather than a single stretched one int ystep = bottom-top; int yo = y+top; while(ystep > 0) { if(p.flags&0x10 && yo+ystep-(y+top) > gaph) { ystep = gaph+y+top-yo; tbottom = ttop+ystep*hscale; } int xstep = right-left; int xo = x+left; float tright2 = tright; while(xstep > 0) { if(p.flags&0x01 && xo+xstep-(x+left) > gapw) { xstep = gapw+x+left-xo; tright = tleft+xstep*wscale; } if(!quads) { quads = true; glBegin(GL_QUADS); } glTexCoord2f(tleft, ttop); glVertex2f(xo, yo); glTexCoord2f(tright, ttop); glVertex2f(xo+xstep, yo); glTexCoord2f(tright, tbottom); glVertex2f(xo+xstep, yo+ystep); glTexCoord2f(tleft, tbottom); glVertex2f(xo, yo+ystep); xtraverts += 4; if(!(p.flags&0x01)) break; xo += xstep; } tright = tright2; if(!(p.flags&0x10)) break; yo += ystep; } } if(quads) glEnd(); else break; //if it didn't happen on the first pass, it won't happen on the second.. } if(passes>1) glDepthFunc(GL_ALWAYS); } vec origin, scale, *savedorigin; float dist; g3d_callback *cb; bool gui2d; static float basescale, maxscale; static bool passthrough; static float alpha; static vec light; void adjustscale() { int w = xsize + (skinx[2]-skinx[1])*SKIN_SCALE + (skinx[10]-skinx[9])*SKIN_SCALE, h = ysize + (skiny[9]-skiny[7])*SKIN_SCALE; if(tcurrent) h += ((skiny[5]-skiny[1])-(skiny[3]-skiny[2]))*SKIN_SCALE + FONTH-2*INSERT; else h += (skiny[6]-skiny[3])*SKIN_SCALE; float aspect = float(screen->h)/float(screen->w), fit = 1.0f; if(w*aspect*basescale>1.0f) fit = 1.0f/(w*aspect*basescale); if(h*basescale*fit>maxscale) fit *= maxscale/(h*basescale*fit); origin = vec(0.5f-((w-xsize)/2 - (skinx[2]-skinx[1])*SKIN_SCALE)*aspect*scale.x*fit, 0.5f + (0.5f*h-(skiny[9]-skiny[7])*SKIN_SCALE)*scale.y*fit, 0); scale = vec(aspect*scale.x*fit, scale.y*fit, 1); } void start(int starttime, float initscale, int *tab, bool allowinput) { if(gui2d) { initscale *= 0.025f; if(allowinput) hascursor = true; } basescale = initscale; if(layoutpass) scale.x = scale.y = scale.z = min(basescale*(totalmillis-starttime)/300.0f, basescale); alpha = allowinput ? 0.80f : 0.60f; passthrough = scale.xo.y, origin.x-camera1->o.x); glTranslatef(origin.x, origin.y, origin.z); glRotatef(yaw/RAD-90, 0, 0, 1); glRotatef(-90, 1, 0, 0); glScalef(-scale.x, scale.y, scale.z); vec dir; lightreaching(origin, light, dir, false, 0, 0.5f); float intensity = vec(yaw, 0.0f).dot(dir); light.mul(1.0f + max(intensity, 0.0f)); } drawskin(curx-skinx[2]*SKIN_SCALE, cury-skiny[6]*SKIN_SCALE, xsize, ysize, 0, 9, gui2d ? 1 : 2, light, alpha); if(!tcurrent) drawskin(curx-skinx[5]*SKIN_SCALE, cury-skiny[6]*SKIN_SCALE, xsize, 0, 9, 1, gui2d ? 1 : 2, light, alpha); } } void end() { if(layoutpass) { xsize = max(tx, xsize); ysize = max(ty, ysize); ysize = max(ysize, (skiny[7]-skiny[6])*SKIN_SCALE); if(tcurrent) *tcurrent = max(1, min(*tcurrent, tpos)); if(gui2d) adjustscale(); if(!windowhit && !passthrough) { float dist = 0; if(gui2d) { hitx = (cursorx - origin.x)/scale.x; hity = (cursory - origin.y)/scale.y; } else { plane p; p.toplane(vec(origin).sub(camera1->o).set(2, 0).normalize(), origin); if(p.rayintersect(camera1->o, camdir, dist) && dist>=0) { vec hitpos(camdir); hitpos.mul(dist).add(camera1->o).sub(origin); hitx = vec(-p.y, p.x, 0).dot(hitpos)/scale.x; hity = -hitpos.z/scale.y; } } if((mousebuttons & G3D_PRESSED) && (fabs(hitx-firstx) > 2 || fabs(hity - firsty) > 2)) mousebuttons |= G3D_DRAGGED; if(dist>=0 && hitx>=-xsize/2 && hitx<=xsize/2 && hity<=0) { if(hity>=-ysize || (tcurrent && hity>=-ysize-(FONTH-2*INSERT)-((skiny[6]-skiny[1])-(skiny[3]-skiny[2]))*SKIN_SCALE && hitx<=tx-xsize/2)) windowhit = this; } } } else { if(tcurrent && tx gui::lists; float gui::basescale, gui::maxscale = 1, gui::hitx, gui::hity, gui::alpha; bool gui::passthrough, gui::shouldmergehits = false, gui::shouldautotab = true; vec gui::light; int gui::curdepth, gui::curlist, gui::xsize, gui::ysize, gui::curx, gui::cury; int gui::ty, gui::tx, gui::tpos, *gui::tcurrent, gui::tcolor; static vector guis2d, guis3d; VARP(guipushdist, 1, 4, 64); bool menukey(int code, bool isdown, int cooked) { editor *e = currentfocus(); if(fieldmode == FIELDKEY) { switch(code) { case SDLK_ESCAPE: if(isdown) fieldmode = FIELDCOMMIT; return true; } const char *keyname = getkeyname(code); if(keyname && isdown) { if(e->lines.length()!=1 || !e->lines[0].empty()) e->insert(" "); e->insert(keyname); } return true; } if(code==-1 && g3d_windowhit(isdown, true)) return true; else if(code==-3 && g3d_windowhit(isdown, false)) return true; if(fieldmode == FIELDSHOW || !e) { if(windowhit) switch(code) { case -4: // window "management" if(isdown) { if(windowhit->gui2d) { vec origin = *guis2d.last().savedorigin; int i = windowhit - &guis2d[0]; for(int j = guis2d.length()-1; j > i; j--) *guis2d[j].savedorigin = *guis2d[j-1].savedorigin; *windowhit->savedorigin = origin; if(guis2d.length() > 1) { if(camera1->o.dist(*windowhit->savedorigin) <= camera1->o.dist(*guis2d.last().savedorigin)) windowhit->savedorigin->add(camdir); } } else windowhit->savedorigin->add(vec(camdir).mul(guipushdist)); } return true; case -5: if(isdown) { if(windowhit->gui2d) { vec origin = *guis2d[0].savedorigin; loopj(guis2d.length()-1) *guis2d[j].savedorigin = *guis2d[j + 1].savedorigin; *guis2d.last().savedorigin = origin; if(guis2d.length() > 1) { if(camera1->o.dist(*guis2d.last().savedorigin) >= camera1->o.dist(*guis2d[0].savedorigin)) guis2d.last().savedorigin->sub(camdir); } } else windowhit->savedorigin->sub(vec(camdir).mul(guipushdist)); } return true; } return false; } switch(code) { case SDLK_ESCAPE: //cancel editing without commit if(isdown) fieldmode = FIELDABORT; return true; case SDLK_RETURN: case SDLK_TAB: if(cooked && (e->maxy != 1)) break; case SDLK_KP_ENTER: if(isdown) fieldmode = FIELDCOMMIT; //signal field commit (handled when drawing field) return true; case SDLK_HOME: case SDLK_END: case SDLK_PAGEUP: case SDLK_PAGEDOWN: case SDLK_DELETE: case SDLK_BACKSPACE: case SDLK_UP: case SDLK_DOWN: case SDLK_LEFT: case SDLK_RIGHT: case SDLK_LSHIFT: case SDLK_RSHIFT: case -4: case -5: break; default: if(!cooked || (code<32)) return false; } if(!isdown) return true; e->key(code, cooked); return true; } void g3d_cursorpos(float &x, float &y) { if(guis2d.length()) { x = cursorx; y = cursory; } else x = y = 0.5f; } void g3d_resetcursor() { cursorx = cursory = 0.5f; } FVARP(guisens, 1e-3f, 1, 1e3f); bool g3d_movecursor(int dx, int dy) { if(!guis2d.length() || !hascursor) return false; const float CURSORSCALE = 500.0f; cursorx = max(0.0f, min(1.0f, cursorx+guisens*dx*(screen->h/(screen->w*CURSORSCALE)))); cursory = max(0.0f, min(1.0f, cursory+guisens*dy/CURSORSCALE)); return true; } VARNP(guifollow, useguifollow, 0, 1, 1); VARNP(gui2d, usegui2d, 0, 1, 1); void g3d_addgui(g3d_callback *cb, vec &origin, int flags) { bool gui2d = flags&GUI_FORCE_2D || (flags&GUI_2D && usegui2d) || mainmenu; if(!gui2d && flags&GUI_FOLLOW && useguifollow) origin.z = player->o.z-(player->eyeheight-1); gui &g = (gui2d ? guis2d : guis3d).add(); g.cb = cb; g.origin = origin; g.savedorigin = &origin; g.dist = flags&GUI_BOTTOM && gui2d ? 1e16f : camera1->o.dist(g.origin); g.gui2d = gui2d; } void g3d_limitscale(float scale) { gui::maxscale = scale; } static inline bool g3d_sort(const gui &a, const gui &b) { return a.dist > b.dist; } bool g3d_windowhit(bool on, bool act) { extern int cleargui(int n); if(act) { if(actionon || windowhit) { if(on) { firstx = gui::hitx; firsty = gui::hity; } mousebuttons |= (actionon=on) ? G3D_DOWN : G3D_UP; } } else if(!on && windowhit) cleargui(1); return (guis2d.length() && hascursor) || (windowhit && !windowhit->gui2d); } void g3d_render() { windowhit = NULL; if(actionon) mousebuttons |= G3D_PRESSED; gui::reset(); guis2d.shrink(0); guis3d.shrink(0); // call all places in the engine that may want to render a gui from here, they call g3d_addgui() extern void g3d_texturemenu(); if(!mainmenu) g3d_texturemenu(); g3d_mainmenu(); if(!mainmenu) game::g3d_gamemenus(); guis2d.sort(g3d_sort); guis3d.sort(g3d_sort); readyeditors(); bool wasfocused = (fieldmode!=FIELDSHOW); fieldsactive = false; hascursor = false; layoutpass = true; loopv(guis2d) guis2d[i].cb->gui(guis2d[i], true); loopv(guis3d) guis3d[i].cb->gui(guis3d[i], true); layoutpass = false; if(guis2d.length() || guis3d.length()) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } if(guis3d.length()) { glEnable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glDepthMask(GL_FALSE); loopvrev(guis3d) guis3d[i].cb->gui(guis3d[i], false); glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); glDisable(GL_DEPTH_TEST); } if(guis2d.length()) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, 1, 1, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); loopvrev(guis2d) guis2d[i].cb->gui(guis2d[i], false); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } if(guis2d.length() || guis3d.length()) { glDisable(GL_BLEND); } flusheditors(); if(!fieldsactive) fieldmode = FIELDSHOW; //didn't draw any fields, so loose focus - mainly for menu closed if((fieldmode!=FIELDSHOW) != wasfocused) { SDL_EnableUNICODE(fieldmode!=FIELDSHOW); keyrepeat(fieldmode!=FIELDSHOW || editmode); } mousebuttons = 0; } void consolebox(int x1, int y1, int x2, int y2) { glPushMatrix(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTranslatef(x1, y1, 0); float bw = x2 - x1, bh = y2 - y1, aspect = bw/bh, sh = bh, sw = sh*aspect; bw *= float(4*FONTH)/(SKIN_H*SKIN_SCALE); bh *= float(4*FONTH)/(SKIN_H*SKIN_SCALE); sw /= bw + (gui::skinx[2]-gui::skinx[1] + gui::skinx[10]-gui::skinx[9])*SKIN_SCALE; sh /= bh + (gui::skiny[9]-gui::skiny[7] + gui::skiny[6]-gui::skiny[4])*SKIN_SCALE; glScalef(sw, sh, 1); gui::drawskin(-gui::skinx[1]*SKIN_SCALE, -gui::skiny[4]*SKIN_SCALE, int(bw), int(bh), 0, 9, 1, vec(1, 1, 1), 0.60f); gui::drawskin((-gui::skinx[1] + gui::skinx[2] - gui::skinx[5])*SKIN_SCALE, -gui::skiny[4]*SKIN_SCALE, int(bw), 0, 9, 1, 1, vec(1, 1, 1), 0.60f); glPopMatrix(); } #endif sandboxgamemaker-2.7.1+dfsg/src/engine/world.cpp0000664000175000017500000011132511654260372021552 0ustar showardshoward// world.cpp: core map management stuff #include "engine.h" VARR(mapversion, 1, MAPVERSION, 0); VARNR(mapscale, worldscale, 1, 0, 0); VARNR(mapsize, worldsize, 1, 0, 0); SVARR(maptitle, "Untitled Map by Unknown"); VAR(octaentsize, 0, 128, 1024); VAR(entselradius, 0, 2, 10); bool getentboundingbox(extentity &e, ivec &o, ivec &r) { switch(e.type) { case ET_EMPTY: return false; case ET_MAPMODEL: { model *m = loadmodel(NULL, e.attr[1]); if(m) { vec center, radius; m->boundbox(0, center, radius); rotatebb(center, radius, e.attr[0]); o = e.o; o.add(center); r = radius; r.add(1); o.sub(r); r.mul(2); break; } } // invisible mapmodels use entselradius default: o = e.o; o.sub(entselradius); r.x = r.y = r.z = entselradius*2; break; } return true; } enum { MODOE_ADD = 1<<0, MODOE_UPDATEBB = 1<<1 }; void modifyoctaentity(int flags, int id, cube *c, const ivec &cor, int size, const ivec &bo, const ivec &br, int leafsize, vtxarray *lastva = NULL) { loopoctabox(cor, size, bo, br) { ivec o(i, cor.x, cor.y, cor.z, size); vtxarray *va = c[i].ext && c[i].ext->va ? c[i].ext->va : lastva; if(c[i].children != NULL && size > leafsize) modifyoctaentity(flags, id, c[i].children, o, size>>1, bo, br, leafsize, va); else if(flags&MODOE_ADD) { if(!c[i].ext || !c[i].ext->ents) ext(c[i]).ents = new octaentities(o, size); octaentities &oe = *c[i].ext->ents; switch(entities::getents()[id]->type) { case ET_MAPMODEL: if(loadmodel(NULL, entities::getents()[id]->attr[1])) { if(va) { va->bbmin.x = -1; if(oe.mapmodels.empty()) va->mapmodels.add(&oe); } oe.mapmodels.add(id); loopk(3) { oe.bbmin[k] = min(oe.bbmin[k], max(oe.o[k], bo[k])); oe.bbmax[k] = max(oe.bbmax[k], min(oe.o[k]+size, bo[k]+br[k])); } break; } // invisible mapmodel default: oe.other.add(id); break; } } else if(c[i].ext && c[i].ext->ents) { octaentities &oe = *c[i].ext->ents; switch(entities::getents()[id]->type) { case ET_MAPMODEL: if(loadmodel(NULL, entities::getents()[id]->attr[1])) { oe.mapmodels.removeobj(id); if(va) { va->bbmin.x = -1; if(oe.mapmodels.empty()) va->mapmodels.removeobj(&oe); } oe.bbmin = oe.bbmax = oe.o; oe.bbmin.add(oe.size); loopvj(oe.mapmodels) { extentity &e = *entities::getents()[oe.mapmodels[j]]; ivec eo, er; if(getentboundingbox(e, eo, er)) loopk(3) { oe.bbmin[k] = min(oe.bbmin[k], eo[k]); oe.bbmax[k] = max(oe.bbmax[k], eo[k]+er[k]); } } loopk(3) { oe.bbmin[k] = max(oe.bbmin[k], oe.o[k]); oe.bbmax[k] = min(oe.bbmax[k], oe.o[k]+size); } break; } // invisible mapmodel default: oe.other.removeobj(id); break; } if(oe.mapmodels.empty() && oe.other.empty()) freeoctaentities(c[i]); } if(c[i].ext && c[i].ext->ents) c[i].ext->ents->query = NULL; if(va && va!=lastva) { if(lastva) { if(va->bbmin.x < 0) lastva->bbmin.x = -1; } else if(flags&MODOE_UPDATEBB) updatevabb(va); } } } vector outsideents; static bool modifyoctaent(int flags, int id) { vector &ents = entities::getents(); if(!ents.inrange(id)) return false; ivec o, r; extentity &e = *ents[id]; if((flags&MODOE_ADD ? e.inoctanode : !e.inoctanode) || !getentboundingbox(e, o, r)) return false; if(!insideworld(e.o)) { int idx = outsideents.find(id); if(flags&MODOE_ADD) { if(idx < 0) outsideents.add(id); } else if(idx >= 0) outsideents.removeunordered(idx); } else { int leafsize = octaentsize, limit = max(r.x, max(r.y, r.z)); while(leafsize < limit) leafsize *= 2; int diff = ~(leafsize-1) & ((o.x^(o.x+r.x))|(o.y^(o.y+r.y))|(o.z^(o.z+r.z))); if(diff && (limit > octaentsize/2 || diff < leafsize*2)) leafsize *= 2; modifyoctaentity(flags, id, worldroot, ivec(0, 0, 0), worldsize>>1, o, r, leafsize); } e.inoctanode = flags&MODOE_ADD ? 1 : 0; if(e.type == ET_LIGHT) clearlightcache(id); else if(e.type == ET_PARTICLES) clearparticleemitters(); else if(flags&MODOE_ADD) lightent(e); return true; } static inline void addentity(int id) { modifyoctaent(MODOE_ADD|MODOE_UPDATEBB, id); } static inline void removeentity(int id) { modifyoctaent(MODOE_UPDATEBB, id); } void freeoctaentities(cube &c) { if(!c.ext) return; if(entities::getents().length()) { while(c.ext->ents && !c.ext->ents->mapmodels.empty()) removeentity(c.ext->ents->mapmodels.pop()); while(c.ext->ents && !c.ext->ents->other.empty()) removeentity(c.ext->ents->other.pop()); } if(c.ext->ents) { delete c.ext->ents; c.ext->ents = NULL; } } void entitiesinoctanodes() { const vector &ents = entities::getents(); loopv(ents) modifyoctaent(MODOE_ADD, i); } static inline void findents(octaentities &oe, int low, int high, bool notspawned, const vec &pos, const vec &radius, vector &found) { vector &ents = entities::getents(); loopv(oe.other) { int id = oe.other[i]; extentity &e = *ents[id]; if(e.type >= low && e.type <= high && (e.spawned || notspawned) && vec(e.o).mul(radius).squaredlen() <= 1) found.add(id); } } static inline void findents(cube *c, const ivec &o, int size, const ivec &bo, const ivec &br, int low, int high, bool notspawned, const vec &pos, const vec &radius, vector &found) { loopoctabox(o, size, bo, br) { if(c[i].ext && c[i].ext->ents) findents(*c[i].ext->ents, low, high, notspawned, pos, radius, found); if(c[i].children && size > octaentsize) { ivec co(i, o.x, o.y, o.z, size); findents(c[i].children, co, size>>1, bo, br, low, high, notspawned, pos, radius, found); } } } void findents(int low, int high, bool notspawned, const vec &pos, const vec &radius, vector &found) { vec invradius(1/radius.x, 1/radius.y, 1/radius.z); ivec bo = vec(pos).sub(radius).sub(1), br = vec(radius).add(1).mul(2); int diff = (bo.x^(bo.x+br.x)) | (bo.y^(bo.y+br.y)) | (bo.z^(bo.z+br.z)) | octaentsize, scale = worldscale-1; if(diff&~((1<= uint(worldsize)) { findents(worldroot, ivec(0, 0, 0), 1<ext && c->ext->ents) findents(*c->ext->ents, low, high, notspawned, pos, invradius, found); scale--; while(c->children && !(diff&(1<children[octastep(bo.x, bo.y, bo.z, scale)]; if(c->ext && c->ext->ents) findents(*c->ext->ents, low, high, notspawned, pos, invradius, found); scale--; } if(c->children && 1<= octaentsize) findents(c->children, ivec(bo).mask(~((2<= sel.o.x && o.y <= sel.o.y+sel.s.y*sel.grid && o.y >= sel.o.y && o.z <= sel.o.z+sel.s.z*sel.grid && o.z >= sel.o.z); } vector entgroup; bool haveselent() { return entgroup.length() > 0; } void entcancel() { entgroup.shrink(0); } void entadd(int id) { undonext = true; entgroup.add(id); } undoblock *newundoent() { int numents = entgroup.length(); if(numents <= 0) return NULL; undoblock *u = (undoblock *)new uchar[sizeof(undoblock) + numents*sizeof(undoent)]; u->numents = numents; undoent *e = (undoent *)(u + 1); loopv(entgroup) { e->i = entgroup[i]; e->e.attr.disown(); //points to random values; this causes problems e->e = *entities::getents()[entgroup[i]]; e++; } return u; } void makeundoent() { if(!undonext) return; undonext = false; oldhover = enthover; undoblock *u = newundoent(); if(u) addundo(u); } void detachentity(extentity &e) { if(!e.attached) return; e.attached->attached = NULL; e.attached = NULL; } VAR(attachradius, 1, 100, 1000); void attachentity(extentity &e) { switch(e.type) { case ET_SPOTLIGHT: break; default: if(e.type &ents = entities::getents(); int closest = -1; float closedist = 1e10f; loopv(ents) { extentity *a = ents[i]; if(a->attached) continue; switch(e.type) { case ET_SPOTLIGHT: if(a->type!=ET_LIGHT) continue; break; default: if(e.typeo); if(dist < closedist) { closest = i; closedist = dist; } } if(closedist>attachradius) return; e.attached = ents[closest]; ents[closest]->attached = &e; } void attachentities() { vector &ents = entities::getents(); loopv(ents) attachentity(*ents[i]); } // convenience macros implicitly define: // e entity, currently edited ent // n int, index to currently edited ent #define addimplicit(f) { if(entgroup.empty() && enthover>=0) { entadd(enthover); undonext = (enthover != oldhover); f; entgroup.drop(); } else f; } #define entfocus(i, f) { int n = efocus = (i); if(n>=0) { extentity &e = *entities::getents()[n]; f; } } #define entedit(i, f) \ { \ entfocus(i, \ int oldtype = e.type; \ removeentity(n); \ f; \ if(oldtype!=e.type) detachentity(e); \ if(e.type!=ET_EMPTY) { addentity(n); if(oldtype!=e.type) attachentity(e); } \ entities::editent(n, true)); \ } #define addgroup(exp) { loopv(entities::getents()) entfocus(i, if(exp) entadd(n)); } #define setgroup(exp) { entcancel(); addgroup(exp); } #define groupeditloop(f){ entlooplevel++; int _ = efocus; loopv(entgroup) entedit(entgroup[i], f); efocus = _; entlooplevel--; } #define groupeditpure(f){ if(entlooplevel>0) { entedit(efocus, f); } else groupeditloop(f); } #define groupeditundo(f){ makeundoent(); groupeditpure(f); } #define groupedit(f) { addimplicit(groupeditundo(f)); } vec getselpos() { vector &ents = entities::getents(); if(entgroup.length() && ents.inrange(entgroup[0])) return ents[entgroup[0]]->o; if(ents.inrange(enthover)) return ents[enthover]->o; return sel.o.tovec(); } undoblock *copyundoents(undoblock *u) { entcancel(); undoent *e = u->ents(); loopi(u->numents) entadd(e[i].i); undoblock *c = newundoent(); loopi(u->numents) if(e[i].e.type==ET_EMPTY) entgroup.removeobj(e[i].i); return c; } void pasteundoents(undoblock *u) { undoent *ue = u->ents(); loopi(u->numents) entedit(ue[i].i, (entity &)e = ue[i].e); } void entflip() { if(noentedit()) return; int d = dimension(sel.orient); float mid = sel.s[d]*sel.grid/2+sel.o[d]; groupeditundo(e.o[d] -= (e.o[d]-mid)*2); } void entrotate(int *cw) { if(noentedit()) return; int d = dimension(sel.orient); int dd = (*cw<0) == dimcoord(sel.orient) ? R[d] : C[d]; float mid = sel.s[dd]*sel.grid/2+sel.o[dd]; vec s(sel.o.v); groupeditundo( e.o[dd] -= (e.o[dd]-mid)*2; e.o.sub(s); swap(e.o[R[d]], e.o[C[d]]); e.o.add(s); ); } void entselectionbox(const entity &e, vec &eo, vec &es) { model *m = NULL; const char *mname = entities::entmodel(e); if(mname && (m = loadmodel(mname))) { m->collisionbox(0, eo, es); if(es.x > es.y) es.y = es.x; else es.x = es.y; // square es.z = (es.z + eo.z + 1 + entselradius)/2; // enclose ent radius box and model box eo.x += e.o.x; eo.y += e.o.y; eo.z = e.o.z - entselradius + es.z; } else if(e.type == ET_MAPMODEL && (m = loadmodel(NULL, e.attr[1]))) { m->collisionbox(0, eo, es); rotatebb(eo, es, e.attr[0]); #if 0 if(m->collide) eo.z -= player->aboveeye; // wacky but true. see physics collide else es.div(2); // cause the usual bb is too big... #endif eo.add(e.o); } else { es = vec(entselradius); eo = e.o; } eo.sub(es); es.mul(2); } VAR(entselsnap, 0, 0, 1); VAR(entmovingshadow, 0, 1, 1); extern void boxs(int orient, vec o, const vec &s); extern void boxs3D(const vec &o, vec s, int g); extern void editmoveplane(const vec &o, const vec &ray, int d, float off, vec &handle, vec &dest, bool first); bool initentdragging = true; void entdrag(const vec &ray) { if(noentedit() || !haveselent()) return; float r = 0, c = 0; static vec v, handle; vec eo, es; int d = dimension(entorient), dc= dimcoord(entorient); entfocus(entgroup.last(), entselectionbox(e, eo, es); editmoveplane(e.o, ray, d, eo[d] + (dc ? es[d] : 0), handle, v, initentdragging); ivec g(v); int z = g[d]&(~(sel.grid-1)); g.add(sel.grid/2).mask(~(sel.grid-1)); g[d] = z; r = (entselsnap ? g[R[d]] : v[R[d]]) - e.o[R[d]]; c = (entselsnap ? g[C[d]] : v[C[d]]) - e.o[C[d]]; ); if(initentdragging) makeundoent(); groupeditpure(e.o[R[d]] += r; e.o[C[d]] += c); initentdragging = false; } VARP(showenthelpers, 0, 1, 2); // editmode, always VARP(showentradius, 0, 1, 2); //1 when selected, 2 always VARP(showentdir, 0, 1, 2); void renderentring(const extentity &e, float radius, int axis) { if(radius <= 0 || !showentradius) return; glBegin(GL_LINE_LOOP); loopi(16) { vec p(e.o); p[axis>=2 ? 1 : 0] += radius*cosf(2*M_PI*i/16.0f); p[axis>=1 ? 2 : 1] += radius*sinf(2*M_PI*i/16.0f); glVertex3fv(p.v); } glEnd(); } void renderentsphere(const extentity &e, float radius) { if(radius <= 0||!showentradius) return; loopk(3) renderentring(e, radius, k); } void renderentattachment(const extentity &e) { if(!e.attached || !showentdir) return; glBegin(GL_LINES); glVertex3fv(e.o.v); glVertex3fv(e.attached->o.v); glEnd(); } void renderentarrow(const extentity &e, const vec &dir, float radius) { if(radius <= 0 || !showentdir) return; float arrowsize = min(radius/8, 0.5f); vec target = vec(dir).mul(radius).add(e.o), arrowbase = vec(dir).mul(radius - arrowsize).add(e.o), spoke; spoke.orthogonal(dir); spoke.normalize(); spoke.mul(arrowsize); glBegin(GL_LINES); glVertex3fv(e.o.v); glVertex3fv(target.v); glEnd(); glBegin(GL_TRIANGLE_FAN); glVertex3fv(target.v); loopi(5) { vec p(spoke); p.rotate(2*M_PI*i/4.0f, dir); p.add(arrowbase); glVertex3fv(p.v); } glEnd(); } void renderentcone(const extentity &e, const vec &dir, float radius, float angle) { if(radius <= 0 || !showentdir) return; vec spot = vec(dir).mul(radius*cosf(angle*RAD)).add(e.o), spoke; spoke.orthogonal(dir); spoke.normalize(); spoke.mul(radius*sinf(angle*RAD)); glBegin(GL_LINES); loopi(8) { vec p(spoke); p.rotate(2*M_PI*i/8.0f, dir); p.add(spot); glVertex3fv(e.o.v); glVertex3fv(p.v); } glEnd(); glBegin(GL_LINE_LOOP); loopi(8) { vec p(spoke); p.rotate(2*M_PI*i/8.0f, dir); p.add(spot); glVertex3fv(p.v); } glEnd(); } void renderentradius(extentity &e, bool color) { switch(e.type) { case ET_LIGHT: if(color) glColor3f(e.attr[1]/255.0f, e.attr[2]/255.0f, e.attr[3]/255.0f); renderentsphere(e, e.attr[0]); break; case ET_SPOTLIGHT: if(e.attached) { if(color) glColor3f(e.attached->attr[1]/255.0f, e.attached->attr[2]/255.0f, e.attached->attr[3]/255.0f); float radius = e.attached->attr[0]; if(!radius) radius = 2*e.o.dist(e.attached->o); vec dir = vec(e.o).sub(e.attached->o).normalize(); float angle = max(1, min(90, int(e.attr[0]))); renderentattachment(e); renderentcone(*e.attached, dir, radius, angle); } break; case ET_SOUND: if(color) glColor3f(0, 1, 1); renderentsphere(e, e.attr[1]); renderentsphere(e, min(e.attr[1], e.attr[2])); break; case ET_ENVMAP: { extern int envmapradius; if(color) glColor3f(0, 1, 1); renderentsphere(e, e.attr[0] ? max(0, min(10000, int(e.attr[0]))) : envmapradius); break; } case ET_MAPMODEL: case ET_PLAYERSTART: { if(color) glColor3f(0, 1, 1); entities::entradius(e, color); vec dir; vecfromyawpitch(e.attr[0], 0, 1, 0, dir); renderentarrow(e, dir, 4); break; } default: if(e.type>=ET_GAMESPECIFIC) { if(color) glColor3f(0, 1, 1); entities::entradius(e, color); } break; } } void renderhelpers() { if(showentradius < 2 && showentdir < 2) return; loopv(entities::getents()) { extentity &e = *entities::getents()[i]; if((showentradius == 2 && entities::radiusent(e))|| (showentdir == 2 && entities::dirent(e))) { glDepthFunc(GL_GREATER); glColor3f(0.25f, 0.25f, 0.25f); renderentradius(e, false); glDepthFunc(GL_LESS); renderentradius(e, true); } } } void renderentselection(const vec &o, const vec &ray, bool entmoving) { if(!noentedit()) { vec eo, es; glColor3ub(0, 40, 0); loopv(entgroup) entfocus(entgroup[i], entselectionbox(e, eo, es); boxs3D(eo, es, 1); ); if(enthover >= 0) { entfocus(enthover, entselectionbox(e, eo, es)); // also ensures enthover is back in focus boxs3D(eo, es, 1); if(entmoving && entmovingshadow==1) { vec a, b; glColor3ub(20, 20, 20); (a = eo).x = eo.x - fmod(eo.x, worldsize); (b = es).x = a.x + worldsize; boxs3D(a, b, 1); (a = eo).y = eo.y - fmod(eo.y, worldsize); (b = es).y = a.x + worldsize; boxs3D(a, b, 1); (a = eo).z = eo.z - fmod(eo.z, worldsize); (b = es).z = a.x + worldsize; boxs3D(a, b, 1); } glColor3ub(150,0,0); glLineWidth(5); boxs(entorient, eo, es); glLineWidth(1); } if(showenthelpers>=1 && (entgroup.length() || enthover >= 0)) { glDepthFunc(GL_GREATER); glColor3f(0.25f, 0.25f, 0.25f); loopv(entgroup) { extentity &e = *entities::getents()[entgroup[i]]; if((showentdir == 2 && entities::dirent(e)) || (showentradius == 2 && entities::radiusent(e))) continue; renderentradius(e, false); } if(enthover>=0) entfocus(enthover, renderentradius(e, false)); glDepthFunc(GL_LESS); loopv(entgroup) { extentity &e = *entities::getents()[entgroup[i]]; if((showentdir == 2 && entities::dirent(e)) || (showentradius == 2 && entities::radiusent(e))) continue; renderentradius(e, true); } if(enthover>=0) entfocus(enthover, renderentradius(e, true)); } } } bool enttoggle(int id) { undonext = true; int i = entgroup.find(id); if(i < 0) entadd(id); else entgroup.remove(i); return i < 0; } bool hoveringonent(int ent, int orient) { if(noentedit()) return false; entorient = orient; if((efocus = enthover = ent) >= 0) return true; efocus = entgroup.empty() ? -1 : entgroup.last(); enthover = -1; return false; } VAR(entitysurf, 0, 0, 1); VARF(entmoving, 0, 0, 2, if(enthover < 0 || noentedit()) entmoving = 0; else if(entmoving == 1) entmoving = enttoggle(enthover); else if(entmoving == 2 && entgroup.find(enthover) < 0) entadd(enthover); if(entmoving > 0) initentdragging = true; ); void entpush(int *dir) { if(noentedit()) return; int d = dimension(entorient); int s = dimcoord(entorient) ? -*dir : *dir; if(entmoving) { groupeditpure(e.o[d] += float(s*sel.grid)); // editdrag supplies the undo } else groupedit(e.o[d] += float(s*sel.grid)); if(entitysurf==1) { player->o[d] += float(s*sel.grid); player->resetinterp(); } } VAR(entautoviewdist, 0, 25, 100); void entautoview(int *dir) { if(!haveselent()) return; static int s = 0; vec v(player->o); v.sub(worldpos); v.normalize(); v.mul(entautoviewdist); int t = s + *dir; s = abs(t) % entgroup.length(); if(t<0 && s>0) s = entgroup.length() - s; entfocus(entgroup[s], v.add(e.o); player->o = v; player->resetinterp(); ); } COMMAND(entautoview, "i"); COMMAND(entflip, ""); COMMAND(entrotate, "i"); COMMAND(entpush, "i"); void delent() { if(noentedit()) return; groupedit(e.type = ET_EMPTY;); entcancel(); } int findtype(const char *what) { for(int i = 0; *entities::entname(i); i++) if(!strcmp(what, entities::entname(i))) return i; conoutf(CON_ERROR, "unknown entity type \"%s\"", what); return ET_EMPTY; } VAR(entdrop, 0, 2, 3); bool dropentity(entity &e, int drop = -1) { vec radius(4.0f, 4.0f, 4.0f); if(drop<0) drop = entdrop; if(e.type == ET_MAPMODEL) { model *m = loadmodel(NULL, e.attr[1]); if(m) { vec center; m->boundbox(0, center, radius); rotatebb(center, radius, e.attr[0]); radius.x += fabs(center.x); radius.y += fabs(center.y); } radius.z = 0.0f; } switch(drop) { case 1: if(e.type != ET_LIGHT && e.type != ET_SPOTLIGHT) dropenttofloor(&e); break; case 2: case 3: int cx = 0, cy = 0; if(sel.cxs == 1 && sel.cys == 1) { cx = (sel.cx ? 1 : -1) * sel.grid / 2; cy = (sel.cy ? 1 : -1) * sel.grid / 2; } e.o = sel.o.tovec(); int d = dimension(sel.orient), dc = dimcoord(sel.orient); e.o[R[d]] += sel.grid / 2 + cx; e.o[C[d]] += sel.grid / 2 + cy; if(!dc) e.o[D[d]] -= radius[D[d]]; else e.o[D[d]] += sel.grid + radius[D[d]]; if(drop == 3) dropenttofloor(&e); break; } return true; } void dropent() { if(noentedit()) return; groupedit(dropentity(e)); } void attachent() { if(noentedit()) return; groupedit(attachentity(e)); } COMMAND(attachent, ""); extentity *newentity(bool local, const vec &o, int type, int *attrs) { extentity &e = *entities::newentity(); e.o = o; loopi(getattrnum(type)) e.attr.add(attrs[i]); e.type = type; e.spawned = false; e.inoctanode = false; e.light.color = vec(1, 1, 1); e.light.dir = vec(0, 0, 1); if(local) { switch(type) { case ET_PARTICLES: switch(e.attr[0]) { case 0: case 1: case 2: case 6: case 7: case 9: case 10: case 11: case 12: case 13: case 14: case 15: if(!e.attr[3]) e.attr[3] |= 0x0F0F0F; if(e.attr[0] != 6 && e.attr[0] != 7) break; case 5: case 8: if(!e.attr[2]) e.attr[2] |= 0x0F0F0F; break; } break; case ET_MAPMODEL: case ET_PLAYERSTART: e.attr.pop(); e.attr.insert(0, camera1->yaw); break; } entities::fixentity(e); } return &e; } const int getattrnum(int type) { if(type >= ET_GAMESPECIFIC) return entities::numattrs(type); static const int num[] = { 0, //empty 4, //light 6, //mapmodel 2, //playerstart 3, //envmap 8, //particles 3, //sound 1 //spotlight }; return type >= 0 && size_t(type) < sizeof(num)/sizeof(num[0]) ? num[type] : 0; } ICOMMAND(getattrnum, "s", (char *s), int type = findtype(s); intret(getattrnum(type)); ) void newentity(int type, int *attrs) { if(entities::getents().length() >= MAXENTS) { conoutf("too many entities"); return; } extentity *t = newentity(true, player->o, type, attrs); dropentity(*t); entities::getents().add(t); int i = entities::getents().length()-1; t->type = ET_EMPTY; enttoggle(i); makeundoent(); entedit(i, e.type = type); } void newent(tagval *args, int num) { if(noentedit() || num == 0) return; int type = findtype(args[0].getstr()); const int numattrs = getattrnum(type); int *attrs = new int[numattrs]; loopi(numattrs) attrs[i] = (num - 1 >= i) ? args[i + 1].getint() : 0; if(type != ET_EMPTY) newentity(type, attrs); delete[] attrs; } int entcopygrid; vector entcopybuf; void entcopy() { if(noentedit()) return; entcopygrid = sel.grid; entcopybuf.shrink(0); loopv(entgroup) entfocus(entgroup[i], entcopybuf.add(e).o.sub(sel.o.tovec())); } void entpaste() { if(noentedit()) return; if(entcopybuf.length()==0) return; entcancel(); int last = entities::getents().length()-1; float m = float(sel.grid)/float(entcopygrid); loopv(entcopybuf) { entity &c = entcopybuf[i]; vec o(c.o); o.mul(m).add(sel.o.tovec()); extentity *e = newentity(true, o, ET_EMPTY, c.attr.getbuf()); entities::getents().add(e); entadd(++last); } int j = 0; groupeditundo(e.attr = entcopybuf[j].attr; e.type = entcopybuf[j++].type;); } COMMAND(newent, "V"); COMMAND(delent, ""); COMMAND(dropent, ""); COMMAND(entcopy, ""); COMMAND(entpaste, ""); void entset(tagval *args, int num) //char *what, int *a1, int *a2, int *a3, int *a4, int *a5, int *a6, int *a7, int *a8) { if(noentedit()) return; int type = num ? findtype(args[0].getstr()) : 0; int numattrs = getattrnum(type); int *attrs = new int[numattrs]; loopi(numattrs) attrs[i] = (num - 1 >= i) ? args[i + 1].getint() : 0; groupedit(e.type=type; e.attr.setsize(0); e.attr.put(attrs, numattrs); ); delete[] attrs; } void printent(extentity &e, char *buf) { switch(e.type) { case ET_PARTICLES: if(printparticles(e, buf)) return; break; default: if(e.type >= ET_GAMESPECIFIC && entities::printent(e, buf)) return; break; } static string tmp; loopv(e.attr) { formatstring(tmp)("%s%d", i ? " " : "", e.attr[i]); concatstring(buf, tmp); } } void nearestent() { if(noentedit()) return; int closest = -1; float closedist = 1e16f; vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; if(e.type == ET_EMPTY) continue; float dist = e.o.dist(player->o); if(dist < closedist) { closest = i; closedist = dist; } } if(closest >= 0) entadd(closest); } ICOMMAND(enthavesel,"", (), addimplicit(intret(entgroup.length()))); ICOMMAND(entselect, "e", (uint *body), if(!noentedit()) addgroup(e.type != ET_EMPTY && entgroup.find(n)<0 && execute(body)>0)); ICOMMAND(entloop, "e", (uint *body), if(!noentedit()) addimplicit(groupeditloop(((void)e, execute(body))))); ICOMMAND(insel, "", (), entfocus(efocus, intret(pointinsel(sel, e.o)))); ICOMMAND(entget, "", (), entfocus(efocus, defformatstring(s)("%s ", entities::entname(e.type)); printent(e, s); result(s) ) ); ICOMMAND(entindex, "", (), intret(efocus)); ICOMMAND(entgetinfo, "", (), entfocus(efocus,result(entities::entnameinfo(e)))); COMMAND(entset, "V"); COMMAND(nearestent, ""); int findentity(int type, int index, int attr1, int attr2) { const vector &ents = entities::getents(); for(int i = index; ipitch = 0; d->roll = 0; for(int attempt = pick;;) { d->o = entities::getents()[attempt]->o; d->yaw = entities::getents()[attempt]->attr[0]; if(entinmap(d, true)) break; attempt = findentity(ET_PLAYERSTART, attempt+1, -1, tag); if(attempt<0 || attempt==pick) { d->o = entities::getents()[attempt]->o; d->yaw = entities::getents()[attempt]->attr[0]; entinmap(d); break; } } } else { d->o.x = d->o.y = d->o.z = 0.5f*worldsize; d->o.z += 1; entinmap(d); } } void splitocta(cube *c, int size) { if(size <= 0x1000) return; loopi(8) { if(!c[i].children) c[i].children = newcubes(isempty(c[i]) ? F_EMPTY : F_SOLID); splitocta(c[i].children, size>>1); } } void resetmap() { clearoverrides(); clearmapsounds(); cleanreflections(); resetblendmap(); resetlightmaps(); clearpvs(); clearslots(); clearparticles(); cleardecals(); clearsleep(); cancelsel(); pruneundos(); setvar("gamespeed", 100, false); setvar("paused", 0, false); entities::clearents(); outsideents.setsize(0); } void startmap(const char *name) { game::startmap(name); } bool emptymap(int scale, bool force, const char *mname, bool usecfg) // main empty world creation routine { if(!force && !editmode) { conoutf(CON_ERROR, "newmap only allowed in edit mode"); return false; } resetmap(); setvar("mapscale", scale<10 ? 10 : (scale>16 ? 16 : scale), true, false); setvar("mapsize", 1< 0x1000) splitocta(worldroot, worldsize>>1); #ifndef NEWGUI clearmainmenu(); #else UI::clearmainmenu(); #endif if(usecfg) { identflags |= IDF_OVERRIDDEN; execfile("data/default_map_settings.cfg", false); identflags &= ~IDF_OVERRIDDEN; } clearlights(); allchanged(true); startmap(mname); game::setwindowcaption(); return true; } bool enlargemap(bool force) { if(!force && !editmode) { conoutf(CON_ERROR, "mapenlarge only allowed in edit mode"); return false; } if(worldsize >= 1<<16) return false; while(outsideents.length()) removeentity(outsideents.pop()); worldscale++; worldsize *= 2; cube *c = newcubes(F_EMPTY); c[0].children = worldroot; loopi(3) solidfaces(c[i+1]); worldroot = c; if(worldsize > 0x1000) splitocta(worldroot, worldsize>>1); enlargeblendmap(); allchanged(); return true; } static bool isallempty(cube &c) { if(!c.children) return isempty(c); loopi(8) if(!isallempty(c.children[i])) return false; return true; } void shrinkmap() { extern int nompedit; if(noedit(true) || (nompedit && multiplayer())) return; if(worldsize <= 1<<10) return; int octant = -1; loopi(8) if(!isallempty(worldroot[i])) { if(octant >= 0) return; octant = i; } if(octant < 0) return; while(outsideents.length()) removeentity(outsideents.pop()); if(!worldroot[octant].children) subdividecube(worldroot[octant], false, false); cube *root = worldroot[octant].children; worldroot[octant].children = NULL; freeocta(worldroot); worldroot = root; worldscale--; worldsize /= 2; ivec offset(octant, 0, 0, 0, worldsize); vector &ents = entities::getents(); loopv(ents) ents[i]->o.sub(offset.tovec()); shrinkblendmap(octant); allchanged(); conoutf("shrunk map to size %d", worldscale); } void newmap(int *i) { bool force = !isconnected() && !haslocalclients(); if(force) game::forceedit(""); if(emptymap(*i, force, NULL)) game::newmap(max(*i, 0)); } void mapenlarge() { if(enlargemap(false)) game::newmap(-1); } COMMAND(newmap, "i"); COMMAND(mapenlarge, ""); COMMAND(shrinkmap, ""); void mapname() { result(game::getclientmap()); } COMMAND(mapname, ""); void mpeditent(int i, const vec &o, int type, int *attrs, bool local) { if(i < 0 || i >= MAXENTS) return; if(entities::getents().length()<=i) { while(entities::getents().length()type = ET_EMPTY; extentity *e = newentity(local, o, type, attrs); entities::getents().add(e); addentity(i); attachentity(*e); } else { extentity &e = *entities::getents()[i]; removeentity(i); int oldtype = e.type; if(oldtype!=type) detachentity(e); e.type = type; e.o = o; e.attr.setsize(0); e.attr.put(attrs, getattrnum(type)); addentity(i); if(oldtype!=type) attachentity(e); } entities::editent(i, local); } int getworldsize() { return worldsize; } int getmapversion() { return mapversion; } sandboxgamemaker-2.7.1+dfsg/src/engine/decal.cpp0000664000175000017500000005132411642642476021503 0ustar showardshoward#include "engine.h" struct decalvert { vec pos; float u, v; bvec color; uchar alpha; }; struct decalinfo { int millis; bvec color; ushort startvert, endvert; }; enum { DF_RND4 = 1<<0, DF_ROTATE = 1<<1, DF_INVMOD = 1<<2, DF_OVERBRIGHT = 1<<3, DF_ADD = 1<<4, DF_SATURATE = 1<<5 }; VARFP(maxdecaltris, 1, 1024, 16384, initdecals()); VARP(decalfade, 1000, 10000, 60000); VAR(dbgdec, 0, 0, 1); struct decalrenderer { const char *texname; int flags, fadeintime, fadeouttime, timetolive; Texture *tex; decalinfo *decals; int maxdecals, startdecal, enddecal; decalvert *verts; int maxverts, startvert, endvert, availverts; decalrenderer(const char *texname, int flags = 0, int fadeintime = 0, int fadeouttime = 1000, int timetolive = -1) : texname(texname), flags(flags), fadeintime(fadeintime), fadeouttime(fadeouttime), timetolive(timetolive), tex(NULL), decals(NULL), maxdecals(0), startdecal(0), enddecal(0), verts(NULL), maxverts(0), startvert(0), endvert(0), availverts(0), decalu(0), decalv(0) { } void init(int tris) { if(decals) { DELETEA(decals); maxdecals = startdecal = enddecal = 0; } if(verts) { DELETEA(verts); maxverts = startvert = endvert = availverts = 0; } decals = new decalinfo[tris]; maxdecals = tris; tex = textureload(texname, 3); maxverts = tris*3 + 3; availverts = maxverts - 3; verts = new decalvert[maxverts]; } int hasdecals() { return enddecal < startdecal ? maxdecals - (startdecal - enddecal) : enddecal - startdecal; } void cleardecals() { startdecal = enddecal = 0; startvert = endvert = 0; availverts = maxverts - 3; } int freedecal() { if(startdecal==enddecal) return 0; decalinfo &d = decals[startdecal]; startdecal++; if(startdecal >= maxdecals) startdecal = 0; int removed = d.endvert < d.startvert ? maxverts - (d.startvert - d.endvert) : d.endvert - d.startvert; startvert = d.endvert; if(startvert==endvert) startvert = endvert = 0; availverts += removed; return removed; } void fadedecal(decalinfo &d, uchar alpha) { bvec color; if(flags&DF_OVERBRIGHT) { if(renderpath!=R_FIXEDFUNCTION || hasTE) color = bvec(128, 128, 128); else color = bvec(alpha, alpha, alpha); } else { color = d.color; if(flags&(DF_ADD|DF_INVMOD)) loopk(3) color[k] = uchar((int(color[k])*int(alpha))>>8); } decalvert *vert = &verts[d.startvert], *end = &verts[d.endvert < d.startvert ? maxverts : d.endvert]; while(vert < end) { vert->color = color; vert->alpha = alpha; vert++; } if(d.endvert < d.startvert) { vert = verts; end = &verts[d.endvert]; while(vert < end) { vert->color = color; vert->alpha = alpha; vert++; } } } void clearfadeddecals() { int threshold = lastmillis - (timetolive>=0 ? timetolive : decalfade) - fadeouttime; decalinfo *d = &decals[startdecal], *end = &decals[enddecal < startdecal ? maxdecals : enddecal]; while(d < end && d->millis <= threshold) d++; if(d >= end && enddecal < startdecal) { d = decals; end = &decals[enddecal]; while(d < end && d->millis <= threshold) d++; } startdecal = d - decals; if(startdecal!=enddecal) startvert = decals[startdecal].startvert; else startvert = endvert = 0; availverts = endvert < startvert ? startvert - endvert - 3 : maxverts - 3 - (endvert - startvert); } void fadeindecals() { if(!fadeintime) return; decalinfo *d = &decals[enddecal], *end = &decals[enddecal < startdecal ? 0 : startdecal]; while(d > end) { d--; int fade = lastmillis - d->millis; if(fade >= fadeintime) return; fadedecal(*d, (fade<<8)/fadeintime); } if(enddecal < startdecal) { d = &decals[maxdecals]; end = &decals[startdecal]; while(d > end) { d--; int fade = lastmillis - d->millis; if(fade >= fadeintime) return; fadedecal(*d, (fade<<8)/fadeintime); } } } void fadeoutdecals() { decalinfo *d = &decals[startdecal], *end = &decals[enddecal < startdecal ? maxdecals : enddecal]; int offset = (timetolive>=0 ? timetolive : decalfade) + fadeouttime - lastmillis; while(d < end) { int fade = d->millis + offset; if(fade >= fadeouttime) return; fadedecal(*d, (fade<<8)/fadeouttime); d++; } if(enddecal < startdecal) { d = decals; end = &decals[enddecal]; while(d < end) { int fade = d->millis + offset; if(fade >= fadeouttime) return; fadedecal(*d, (fade<<8)/fadeouttime); d++; } } } static void setuprenderstate() { enablepolygonoffset(GL_POLYGON_OFFSET_FILL); glDepthMask(GL_FALSE); glEnable(GL_BLEND); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); } static void cleanuprenderstate() { glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDepthMask(GL_TRUE); glDisable(GL_BLEND); disablepolygonoffset(GL_POLYGON_OFFSET_FILL); } void render() { if(startvert==endvert) return; float oldfogc[4]; if(flags&(DF_ADD|DF_INVMOD|DF_OVERBRIGHT)) { glGetFloatv(GL_FOG_COLOR, oldfogc); static float zerofog[4] = { 0, 0, 0, 1 }, grayfog[4] = { 0.5f, 0.5f, 0.5f, 1 }; glFogfv(GL_FOG_COLOR, flags&DF_OVERBRIGHT && (renderpath!=R_FIXEDFUNCTION || hasTE) ? grayfog : zerofog); } if(flags&DF_OVERBRIGHT) { if(renderpath!=R_FIXEDFUNCTION) { glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); SETSHADER(overbrightdecal); } else if(hasTE) { glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); setuptmu(0, "T , C @ Ca"); } else glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); } else { if(flags&DF_INVMOD) glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); else if(flags&DF_ADD) glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); else glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(flags&DF_SATURATE) { if(renderpath!=R_FIXEDFUNCTION) SETSHADER(saturatedecal); else if(hasTE) setuptmu(0, "C * T x 2"); } else foggedshader->set(); } glBindTexture(GL_TEXTURE_2D, tex->id); glVertexPointer(3, GL_FLOAT, sizeof(decalvert), &verts->pos); glTexCoordPointer(2, GL_FLOAT, sizeof(decalvert), &verts->u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(decalvert), &verts->color); int count = endvert < startvert ? maxverts - startvert : endvert - startvert; glDrawArrays(GL_TRIANGLES, startvert, count); if(endvert < startvert) { count += endvert; glDrawArrays(GL_TRIANGLES, 0, endvert); } xtravertsva += count; if(flags&(DF_ADD|DF_INVMOD|DF_OVERBRIGHT)) glFogfv(GL_FOG_COLOR, oldfogc); if(flags&(DF_OVERBRIGHT|DF_SATURATE) && hasTE) resettmu(0); } decalinfo &newdecal() { decalinfo &d = decals[enddecal]; int next = enddecal + 1; if(next>=maxdecals) next = 0; if(next==startdecal) freedecal(); enddecal = next; return d; } ivec bborigin, bbsize; vec decalcenter, decalnormal, decaltangent, decalbitangent; float decalradius, decalu, decalv; bvec decalcolor; void adddecal(const vec ¢er, const vec &dir, float radius, const bvec &color, int info) { int isz = int(ceil(radius)); bborigin = ivec(center).sub(isz); bbsize = ivec(isz*2, isz*2, isz*2); decalcolor = color; decalcenter = center; decalradius = radius; decalnormal = dir; #if 0 decaltangent.orthogonal(dir); #else decaltangent = vec(dir.z, -dir.x, dir.y); decaltangent.sub(vec(dir).mul(decaltangent.dot(dir))); #endif if(flags&DF_ROTATE) decaltangent.rotate(rnd(360)*RAD, dir); decaltangent.normalize(); decalbitangent.cross(decaltangent, dir); if(flags&DF_RND4) { decalu = 0.5f*(info&1); decalv = 0.5f*((info>>1)&1); } ushort dstart = endvert; gentris(worldroot, ivec(0, 0, 0), worldsize>>1); if(dbgdec) { int nverts = endvert < dstart ? endvert + maxverts - dstart : endvert - dstart; conoutf(CON_DEBUG, "tris = %d, verts = %d, total tris = %d", nverts/3, nverts, (maxverts - 3 - availverts)/3); } if(endvert==dstart) return; decalinfo &d = newdecal(); d.color = color; d.millis = lastmillis; d.startvert = dstart; d.endvert = endvert; } static int clip(const vec *in, int numin, const vec &dir, float below, float above, vec *out) { int numout = 0; const vec *p = &in[numin-1]; float pc = dir.dot(*p); loopi(numin) { const vec &v = in[i]; float c = dir.dot(v); if(c < below) { if(pc > above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); if(pc > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(c > above) { if(pc < below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); if(pc < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); } else { if(pc < below) { if(c > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(pc > above && c < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); out[numout++] = v; } p = &v; pc = c; } return numout; } void gentris(cube &cu, int orient, const ivec &o, int size, materialsurface *mat = NULL) { vec pos[MAXFACEVERTS+4]; int numverts = 0, numplanes = 1; vec planes[2]; if(mat) { vec vo = o.tovec(), scale; int dim = dimension(orient), dc = dimcoord(orient), c = C[dim], r = R[dim]; vo[dim] += dc ? -0.1f : 0.1f; scale[c] = mat->csize/8.0f; scale[r] = mat->rsize/8.0f; scale[dim] = 0; loopk(4) pos[numverts++] = facecoords[orient][k].tovec().mul(scale).add(vo); planes[0] = vec(0, 0, 0); planes[0][dim] = dc ? 1 : -1; } else if(cu.texture[orient] == DEFAULT_SKY) return; else if(cu.ext && (numverts = cu.ext->surfaces[orient].numverts&MAXFACEVERTS)) { vertinfo *verts = cu.ext->verts() + cu.ext->surfaces[orient].verts; ivec vo = ivec(o).mask(~0xFFF).shl(3); loopj(numverts) pos[j] = verts[j].getxyz().add(vo).tovec().mul(1/8.0f); planes[0].cross(pos[0], pos[1], pos[2]).normalize(); if(numverts >= 4 && !(cu.merged&(1< decalradius) continue; vec pcenter = vec(decalnormal).mul(dist).add(decalcenter); #else // travel back along plane normal from the decal center float dist = n.dot(p); if(fabs(dist) > decalradius) continue; vec pcenter = vec(n).mul(dist).add(decalcenter); #endif vec ft, fb; ft.orthogonal(n); ft.normalize(); fb.cross(ft, n); vec pt = vec(ft).mul(ft.dot(decaltangent)).add(vec(fb).mul(fb.dot(decaltangent))).normalize(), pb = vec(ft).mul(ft.dot(decalbitangent)).add(vec(fb).mul(fb.dot(decalbitangent))).normalize(); // orthonormalize projected bitangent to prevent streaking pb.sub(vec(pt).mul(pt.dot(pb))).normalize(); vec v1[MAXFACEVERTS+4], v2[MAXFACEVERTS+4]; float ptc = pt.dot(pcenter), pbc = pb.dot(pcenter); int numv; if(numplanes >= 2) { if(l) { pos[1] = pos[2]; pos[2] = pos[3]; } numv = clip(pos, 3, pt, ptc - decalradius, ptc + decalradius, v1); if(numv<3) continue; } else { numv = clip(pos, numverts, pt, ptc - decalradius, ptc + decalradius, v1); if(numv<3) continue; } numv = clip(v1, numv, pb, pbc - decalradius, pbc + decalradius, v2); if(numv<3) continue; float tsz = flags&DF_RND4 ? 0.5f : 1.0f, scale = tsz*0.5f/decalradius, tu = decalu + tsz*0.5f - ptc*scale, tv = decalv + tsz*0.5f - pbc*scale; pt.mul(scale); pb.mul(scale); decalvert dv1 = { v2[0], pt.dot(v2[0]) + tu, pb.dot(v2[0]) + tv, decalcolor, 255 }, dv2 = { v2[1], pt.dot(v2[1]) + tu, pb.dot(v2[1]) + tv, decalcolor, 255 }; int totalverts = 3*(numv-2); if(totalverts > maxverts-3) return; while(availverts < totalverts) { if(!freedecal()) return; } availverts -= totalverts; loopk(numv-2) { verts[endvert++] = dv1; verts[endvert++] = dv2; dv2.pos = v2[k+2]; dv2.u = pt.dot(v2[k+2]) + tu; dv2.v = pb.dot(v2[k+2]) + tv; verts[endvert++] = dv2; if(endvert>=maxverts) endvert = 0; } } } void findmaterials(vtxarray *va) { materialsurface *matbuf = va->matbuf; int matsurfs = va->matsurfs; loopi(matsurfs) { materialsurface &m = matbuf[i]; if(!isclipped(m.material&MATF_VOLUME)) { i += m.skip; continue; } int dim = dimension(m.orient), dc = dimcoord(m.orient); if(dc ? decalnormal[dim] <= 0 : decalnormal[dim] >= 0) { i += m.skip; continue; } int c = C[dim], r = R[dim]; for(;;) { materialsurface &m = matbuf[i]; if(m.o[dim] >= bborigin[dim] && m.o[dim] <= bborigin[dim] + bbsize[dim] && m.o[c] + m.csize >= bborigin[c] && m.o[c] <= bborigin[c] + bbsize[c] && m.o[r] + m.rsize >= bborigin[r] && m.o[r] <= bborigin[r] + bbsize[r]) { static cube dummy; gentris(dummy, m.orient, m.o, max(m.csize, m.rsize), &m); } if(i+1 >= matsurfs) break; materialsurface &n = matbuf[i+1]; if(n.material != m.material || n.orient != m.orient) break; i++; } } } void findescaped(cube *cu, const ivec &o, int size, int escaped) { loopi(8) { if(escaped&(1<>1, cu[i].escaped); else { int vismask = cu[i].escaped&cu[i].merged; if(vismask) loopj(6) if(vismask&(1<va && cu[i].ext->va->matsurfs) findmaterials(cu[i].ext->va); if(cu[i].children) gentris(cu[i].children, co, size>>1, cu[i].escaped); else { int vismask = cu[i].visible|cu[i].merged; if(vismask) loopj(6) if(vismask&(1<>1, cu[i].escaped); else { int vismask = cu[i].escaped&cu[i].merged; if(vismask) loopj(6) if(vismask&(1<=sizeof(decals)/sizeof(decals[0]) || center.dist(camera1->o) - radius > maxdecaldistance) return; decalrenderer &d = decals[type]; d.adddecal(center, surface, radius, color, info); } sandboxgamemaker-2.7.1+dfsg/src/engine/lensflare.h0000664000175000017500000001532111400572336022035 0ustar showardshowardstatic struct flaretype { int type; /* flaretex index, 0..5, -1 for 6+random shine */ float loc; /* postion on axis */ float scale; /* texture scaling */ uchar alpha; /* color alpha */ } flaretypes[] = { {2, 1.30f, 0.04f, 153}, //flares {3, 1.00f, 0.10f, 102}, {1, 0.50f, 0.20f, 77}, {3, 0.20f, 0.05f, 77}, {0, 0.00f, 0.04f, 77}, {5, -0.25f, 0.07f, 127}, {5, -0.40f, 0.02f, 153}, {5, -0.60f, 0.04f, 102}, {5, -1.00f, 0.03f, 51}, {-1, 1.00f, 0.30f, 255}, //shine - red, green, blue {-2, 1.00f, 0.20f, 255}, {-3, 1.00f, 0.25f, 255} }; struct flare { vec o, center; float size; uchar color[3]; bool sparkle; }; VARR(flarelights, 0, 0, 1); VARR(flarecutoff, 0, 1000, 10000); VARR(flaresize, 20, 100, 500); struct flarerenderer : partrenderer { int maxflares, numflares; unsigned int shinetime; flare *flares; flarerenderer(const char *texname, int maxflares) : partrenderer(texname, 3, PT_FLARE), maxflares(maxflares), shinetime(0) { flares = new flare[maxflares]; } void reset() { numflares = 0; } void newflare(vec &o, const vec ¢er, uchar r, uchar g, uchar b, float mod, float size, bool sun, bool sparkle) { if(numflares >= maxflares) return; vec target; //occlusion check (neccessary as depth testing is turned off) if(!raycubelos(o, camera1->o, target)) return; flare &f = flares[numflares++]; f.o = o; f.center = center; f.size = size; f.color[0] = uchar(r*mod); f.color[1] = uchar(g*mod); f.color[2] = uchar(b*mod); f.sparkle = sparkle; } void addflare(vec &o, uchar r, uchar g, uchar b, bool sun, bool sparkle, int sizemod) { //frustrum + fog check if(isvisiblesphere(0.0f, o) > (sun?VFC_FOGGED:VFC_FULL_VISIBLE)) return; //find closest point between camera line of sight and flare pos vec viewdir; vecfromyawpitch(camera1->yaw, camera1->pitch, 1, 0, viewdir); vec flaredir = vec(o).sub(camera1->o); vec center = viewdir.mul(flaredir.dot(viewdir)).add(camera1->o); float mod, size; if(sun) //fixed size { mod = 1.0; size = flaredir.magnitude() * flaresize / 100.0f * (sizemod > 0 ? sizemod / 100.0f : 1); } else { mod = ((flarecutoff * (sizemod > 0 ? (sizemod / 100.0f) : 1))-vec(o).sub(center).squaredlen())/(flarecutoff * (sizemod > 0 ? (sizemod / 100.0f) : 1)); if(mod > 1.0f) mod = 1.0f; if(mod < 0.0f) return; size = flaresize / 5.0f * (sizemod > 0 ? sizemod / 100.0f : 1); } newflare(o, center, r, g, b, mod, size, sun, sparkle); } void makelightflares() { numflares = 0; //regenerate flarelist each frame shinetime = lastmillis/10; if(editmode || !flarelights) return; const vector &ents = entities::getents(); vec viewdir; vecfromyawpitch(camera1->yaw, camera1->pitch, 1, 0, viewdir); extern const vector &checklightcache(int x, int y); const vector &lights = checklightcache(int(camera1->o.x), int(camera1->o.y)); loopv(lights) { entity &e = *ents[lights[i]]; if(e.type != ET_LIGHT) continue; bool sun = (e.attr[0]==0); float radius = float(e.attr[0]); vec flaredir = vec(e.o).sub(camera1->o); float len = flaredir.magnitude(); if(!sun && (len > radius)) continue; if(isvisiblesphere(0.0f, e.o) > (sun?VFC_FOGGED:VFC_FULL_VISIBLE)) continue; vec center = vec(viewdir).mul(flaredir.dot(viewdir)).add(camera1->o); float mod, size; if(sun) //fixed size { mod = 1.0; size = len * flaresize / 100.0f; } else { mod = (radius-len)/radius; size = flaresize / 5.0f; } newflare(e.o, center, e.attr[1], e.attr[2], e.attr[3], mod, size, sun, sun); } } int count() { return numflares; } bool haswork() { return (numflares != 0) && !glaring && !reflecting && !refracting; } void render() { glDisable(GL_FOG); defaultshader->set(); glDisable(GL_DEPTH_TEST); if(!tex) tex = textureload(texname); glBindTexture(GL_TEXTURE_2D, tex->id); glBegin(GL_QUADS); loopi(numflares) { flare *f = flares+i; vec center = f->center; vec axis = vec(f->o).sub(center); uchar color[4] = {f->color[0], f->color[1], f->color[2], 255}; loopj(f->sparkle?12:9) { const flaretype &ft = flaretypes[j]; vec o = vec(axis).mul(ft.loc).add(center); float sz = ft.scale * f->size; int tex = ft.type; if(ft.type < 0) //sparkles - always done last { shinetime = (shinetime + 1) % 10; tex = 6+shinetime; color[0] = 0; color[1] = 0; color[2] = 0; color[-ft.type-1] = f->color[-ft.type-1]; //only want a single channel } color[3] = ft.alpha; glColor4ubv(color); const float tsz = 0.25; //flares are aranged in 4x4 grid float tx = tsz*(tex&0x03); float ty = tsz*((tex>>2)&0x03); glTexCoord2f(tx, ty+tsz); glVertex3f(o.x+(-camright.x+camup.x)*sz, o.y+(-camright.y+camup.y)*sz, o.z+(-camright.z+camup.z)*sz); glTexCoord2f(tx+tsz, ty+tsz); glVertex3f(o.x+( camright.x+camup.x)*sz, o.y+( camright.y+camup.y)*sz, o.z+( camright.z+camup.z)*sz); glTexCoord2f(tx+tsz, ty); glVertex3f(o.x+( camright.x-camup.x)*sz, o.y+( camright.y-camup.y)*sz, o.z+( camright.z-camup.z)*sz); glTexCoord2f(tx, ty); glVertex3f(o.x+(-camright.x-camup.x)*sz, o.y+(-camright.y-camup.y)*sz, o.z+(-camright.z-camup.z)*sz); } } glEnd(); glEnable(GL_DEPTH_TEST); glEnable(GL_FOG); } //square per round hole - use addflare(..) instead particle *addpart(const vec &o, const vec &d, int fade, int color, float size, int gravity = 0) { return NULL; } }; static flarerenderer flares("packages/particles/lensflares", 64); sandboxgamemaker-2.7.1+dfsg/src/engine/movie.cpp0000664000175000017500000013042311654260372021542 0ustar showardshoward// Feedback on playing videos: // quicktime - ok // vlc - ok // xine - ok // mplayer - ok // totem - ok // avidemux - ok - 3Apr09-RockKeyman:had to swap UV channels as it showed up blue // kino - ok #include "engine.h" #include "SDL_mixer.h" VAR(dbgmovie, 0, 0, 1); struct aviindexentry { int frame, type, size; uint offset; aviindexentry() {} aviindexentry(int frame, int type, int size, uint offset) : frame(frame), type(type), size(size), offset(offset) {} }; struct avisegmentinfo { stream::offset offset, videoindexoffset, soundindexoffset; int firstindex; uint videoindexsize, soundindexsize, indexframes, videoframes, soundframes; avisegmentinfo() {} avisegmentinfo(stream::offset offset, int firstindex) : offset(offset), videoindexoffset(0), soundindexoffset(0), firstindex(firstindex), videoindexsize(0), soundindexsize(0), indexframes(0), videoframes(0), soundframes(0) {} }; struct aviwriter { stream *f; uchar *yuv; uint videoframes; stream::offset totalsize; const uint videow, videoh, videofps; string filename; int soundfrequency, soundchannels; Uint16 soundformat; vector index; vector segments; stream::offset fileframesoffset, fileextframesoffset, filevideooffset, filesoundoffset, superindexvideooffset, superindexsoundoffset; enum { MAX_CHUNK_DEPTH = 16, MAX_SUPER_INDEX = 1024 }; stream::offset chunkoffsets[MAX_CHUNK_DEPTH]; int chunkdepth; aviindexentry &addindex(int frame, int type, int size) { avisegmentinfo &seg = segments.last(); int i = index.length(); while(--i >= seg.firstindex) { aviindexentry &e = index[i]; if(frame > e.frame || (frame == e.frame && type <= e.type)) break; } return index.insert(i + 1, aviindexentry(frame, type, size, uint(totalsize - chunkoffsets[chunkdepth]))); } double filespaceguess() { return double(totalsize); } void startchunk(const char *fcc, uint size = 0) { f->write(fcc, 4); f->putlil(size); totalsize += 4 + 4; chunkoffsets[++chunkdepth] = totalsize; totalsize += size; } void listchunk(const char *fcc, const char *lfcc) { startchunk(fcc); f->write(lfcc, 4); totalsize += 4; } void endchunk() { assert(chunkdepth >= 0); --chunkdepth; } void endlistchunk() { assert(chunkdepth >= 0); int size = int(totalsize - chunkoffsets[chunkdepth]); f->seek(-4 - size, SEEK_CUR); f->putlil(size); f->seek(0, SEEK_END); if(size & 1) { f->putchar(0x00); totalsize++; } endchunk(); } void writechunk(const char *fcc, const void *data, uint len) // simplify startchunk()/endchunk() to avoid f->seek() { f->write(fcc, 4); f->putlil(len); f->write(data, len); totalsize += 4 + 4 + len; if(len & 1) { f->putchar(0x00); totalsize++; } } void close() { if(!f) return; flushsegment(); uint soundindexes = 0, videoindexes = 0, soundframes = 0, videoframes = 0, indexframes = 0; loopv(segments) { avisegmentinfo &seg = segments[i]; if(seg.soundindexsize) soundindexes++; videoindexes++; soundframes += seg.soundframes; videoframes += seg.videoframes; indexframes += seg.indexframes; } if(dbgmovie) conoutf(CON_DEBUG, "fileframes: sound=%d, video=%d+%d(dups)\n", soundframes, videoframes, indexframes-videoframes); f->seek(fileframesoffset, SEEK_SET); f->putlil(segments[0].indexframes); f->seek(filevideooffset, SEEK_SET); f->putlil(segments[0].videoframes); if(segments[0].soundframes > 0) { f->seek(filesoundoffset, SEEK_SET); f->putlil(segments[0].soundframes); } f->seek(fileextframesoffset, SEEK_SET); f->putlil(indexframes); // total video frames f->seek(superindexvideooffset + 2 + 2, SEEK_SET); f->putlil(videoindexes); f->seek(superindexvideooffset + 2 + 2 + 4 + 4 + 4 + 4 + 4, SEEK_SET); loopv(segments) { avisegmentinfo &seg = segments[i]; f->putlil(seg.videoindexoffset&stream::offset(0xFFFFFFFFU)); f->putlil(seg.videoindexoffset>>32); f->putlil(seg.videoindexsize); f->putlil(seg.indexframes); } if(soundindexes > 0) { f->seek(superindexsoundoffset + 2 + 2, SEEK_SET); f->putlil(soundindexes); f->seek(superindexsoundoffset + 2 + 2 + 4 + 4 + 4 + 4 + 4, SEEK_SET); loopv(segments) { avisegmentinfo &seg = segments[i]; if(!seg.soundindexsize) continue; f->putlil(seg.soundindexoffset&stream::offset(0xFFFFFFFFU)); f->putlil(seg.soundindexoffset>>32); f->putlil(seg.soundindexsize); f->putlil(seg.soundframes); } } f->seek(0, SEEK_END); DELETEP(f); } aviwriter(const char *name, uint w, uint h, uint fps, bool sound) : f(NULL), yuv(NULL), videoframes(0), totalsize(0), videow(w&~1), videoh(h&~1), videofps(fps), soundfrequency(0),soundchannels(0),soundformat(0) { copystring(filename, name); path(filename); if(!strrchr(filename, '.')) concatstring(filename, ".avi"); extern bool nosound; // sound.cpp if(sound && !nosound) { Mix_QuerySpec(&soundfrequency, &soundformat, &soundchannels); const char *desc; switch(soundformat) { case AUDIO_U8: desc = "u8"; break; case AUDIO_S8: desc = "s8"; break; case AUDIO_U16LSB: desc = "u16l"; break; case AUDIO_U16MSB: desc = "u16b"; break; case AUDIO_S16LSB: desc = "s16l"; break; case AUDIO_S16MSB: desc = "s16b"; break; default: desc = "unkn"; } if(dbgmovie) conoutf(CON_DEBUG, "soundspec: %dhz %s x %d", soundfrequency, desc, soundchannels); } } ~aviwriter() { close(); if(yuv) delete [] yuv; } bool open() { f = openfile(filename, "wb"); if(!f) return false; chunkdepth = -1; listchunk("RIFF", "AVI "); listchunk("LIST", "hdrl"); startchunk("avih", 56); f->putlil(1000000 / videofps); // microsecsperframe f->putlil(0); // maxbytespersec f->putlil(0); // reserved f->putlil(0x10 | 0x20); // flags - hasindex|mustuseindex fileframesoffset = f->tell(); f->putlil(0); // totalvideoframes f->putlil(0); // initialframes f->putlil(soundfrequency > 0 ? 2 : 1); // streams f->putlil(0); // buffersize f->putlil(videow); // video width f->putlil(videoh); // video height loopi(4) f->putlil(0); // reserved endchunk(); // avih listchunk("LIST", "strl"); startchunk("strh", 56); f->write("vids", 4); // fcctype f->write("I420", 4); // fcchandler f->putlil(0); // flags f->putlil(0); // priority f->putlil(0); // initialframes f->putlil(1); // scale f->putlil(videofps); // rate f->putlil(0); // start filevideooffset = f->tell(); f->putlil(0); // length f->putlil(videow*videoh*3/2); // suggested buffersize f->putlil(0); // quality f->putlil(0); // samplesize f->putlil(0); // frame left f->putlil(0); // frame top f->putlil(videow); // frame right f->putlil(videoh); // frame bottom endchunk(); // strh startchunk("strf", 40); f->putlil(40); //headersize f->putlil(videow); // width f->putlil(videoh); // height f->putlil(3); // planes f->putlil(12); // bitcount f->write("I420", 4); // compression f->putlil(videow*videoh*3/2); // imagesize f->putlil(0); // xres f->putlil(0); // yres; f->putlil(0); // colorsused f->putlil(0); // colorsrequired endchunk(); // strf startchunk("indx", 24 + 16*MAX_SUPER_INDEX); superindexvideooffset = f->tell(); f->putlil(4); // longs per entry f->putlil(0); // index of indexes f->putlil(0); // entries in use f->write("00dc", 4); // chunk id f->putlil(0); // reserved 1 f->putlil(0); // reserved 2 f->putlil(0); // reserved 3 loopi(MAX_SUPER_INDEX) { f->putlil(0); // offset low f->putlil(0); // offset high f->putlil(0); // size f->putlil(0); // duration } endchunk(); // indx startchunk("vprp", 68); f->putlil(0); // video format token f->putlil(0); // video standard f->putlil(videofps); // vertical refresh rate f->putlil(videow); // horizontal total f->putlil(videoh); // vertical total int gcd = screen->w, rem = screen->h; while(rem > 0) { gcd %= rem; swap(gcd, rem); } f->putlil(screen->h/gcd); // aspect denominator f->putlil(screen->w/gcd); // aspect numerator f->putlil(videow); // frame width f->putlil(videoh); // frame height f->putlil(1); // fields per frame f->putlil(videoh); // compressed bitmap height f->putlil(videow); // compressed bitmap width f->putlil(videoh); // valid bitmap height f->putlil(videow); // valid bitmap width f->putlil(0); // valid bitmap x offset f->putlil(0); // valid bitmap y offset f->putlil(0); // video x offset f->putlil(0); // video y start endchunk(); // vprp endlistchunk(); // LIST strl if(soundfrequency > 0) { const int bps = (soundformat==AUDIO_U8 || soundformat == AUDIO_S8) ? 1 : 2; listchunk("LIST", "strl"); startchunk("strh", 56); f->write("auds", 4); // fcctype f->putlil(1); // fcchandler - normally 4cc, but audio is a special case f->putlil(0); // flags f->putlil(0); // priority f->putlil(0); // initialframes f->putlil(1); // scale f->putlil(soundfrequency); // rate f->putlil(0); // start filesoundoffset = f->tell(); f->putlil(0); // length f->putlil(soundfrequency*bps*soundchannels/2); // suggested buffer size (this is a half second) f->putlil(0); // quality f->putlil(bps*soundchannels); // samplesize f->putlil(0); // frame left f->putlil(0); // frame top f->putlil(0); // frame right f->putlil(0); // frame bottom endchunk(); // strh startchunk("strf", 18); f->putlil(1); // format (uncompressed PCM) f->putlil(soundchannels); // channels f->putlil(soundfrequency); // sampleframes per second f->putlil(soundfrequency*bps*soundchannels); // average bytes per second f->putlil(bps*soundchannels); // block align <-- guess f->putlil(bps*8); // bits per sample f->putlil(0); // size endchunk(); //strf startchunk("indx", 24 + 16*MAX_SUPER_INDEX); superindexsoundoffset = f->tell(); f->putlil(4); // longs per entry f->putlil(0); // index of indexes f->putlil(0); // entries in use f->write("01wb", 4); // chunk id f->putlil(0); // reserved 1 f->putlil(0); // reserved 2 f->putlil(0); // reserved 3 loopi(MAX_SUPER_INDEX) { f->putlil(0); // offset low f->putlil(0); // offset high f->putlil(0); // size f->putlil(0); // duration } endchunk(); // indx endlistchunk(); // LIST strl } listchunk("LIST", "odml"); startchunk("dmlh", 4); fileextframesoffset = f->tell(); f->putlil(0); endchunk(); // dmlh endlistchunk(); // LIST odml listchunk("LIST", "INFO"); const char *software = "Cube 2: Sauerbraten"; writechunk("ISFT", software, strlen(software)+1); endlistchunk(); // LIST INFO endlistchunk(); // LIST hdrl nextsegment(); return true; } static inline void boxsample(const uchar *src, const uint stride, const uint area, const uint w, uint h, const uint xlow, const uint xhigh, const uint ylow, const uint yhigh, uint &bdst, uint &gdst, uint &rdst) { const uchar *end = &src[w<<2]; uint bt = 0, gt = 0, rt = 0; for(const uchar *cur = &src[4]; cur < end; cur += 4) { bt += cur[0]; gt += cur[1]; rt += cur[2]; } bt = ylow*(bt + ((src[0]*xlow + end[0]*xhigh)>>12)); gt = ylow*(gt + ((src[1]*xlow + end[1]*xhigh)>>12)); rt = ylow*(rt + ((src[2]*xlow + end[2]*xhigh)>>12)); if(h) { for(src += stride, end += stride; --h; src += stride, end += stride) { uint b = 0, g = 0, r = 0; for(const uchar *cur = &src[4]; cur < end; cur += 4) { b += cur[0]; g += cur[1]; r += cur[2]; } bt += (b<<12) + src[0]*xlow + end[0]*xhigh; gt += (g<<12) + src[1]*xlow + end[1]*xhigh; rt += (r<<12) + src[2]*xlow + end[2]*xhigh; } uint b = 0, g = 0, r = 0; for(const uchar *cur = &src[4]; cur < end; cur += 4) { b += cur[0]; g += cur[1]; r += cur[2]; } bt += yhigh*(b + ((src[0]*xlow + end[0]*xhigh)>>12)); gt += yhigh*(g + ((src[1]*xlow + end[1]*xhigh)>>12)); rt += yhigh*(r + ((src[2]*xlow + end[2]*xhigh)>>12)); } bdst = (bt*area)>>24; gdst = (gt*area)>>24; rdst = (rt*area)>>24; } void scaleyuv(const uchar *pixels, uint srcw, uint srch) { const int flip = -1; const uint planesize = videow * videoh; if(!yuv) yuv = new uchar[(planesize*3)/2]; uchar *yplane = yuv, *uplane = yuv + planesize, *vplane = yuv + planesize + planesize/4; const int ystride = flip*int(videow), uvstride = flip*int(videow)/2; if(flip < 0) { yplane -= int(videoh-1)*ystride; uplane -= int(videoh/2-1)*uvstride; vplane -= int(videoh/2-1)*uvstride; } const uint stride = srcw<<2; srcw &= ~1; srch &= ~1; const uint wfrac = (srcw<<12)/videow, hfrac = (srch<<12)/videoh, area = ((ullong)planesize<<12)/(srcw*srch + 1), dw = videow*wfrac, dh = videoh*hfrac; for(uint y = 0; y < dh;) { uint yn = y + hfrac - 1, yi = y>>12, h = (yn>>12) - yi, ylow = ((yn|(-int(h)>>24))&0xFFFU) + 1 - (y&0xFFFU), yhigh = (yn&0xFFFU) + 1; y += hfrac; uint y2n = y + hfrac - 1, y2i = y>>12, h2 = (y2n>>12) - y2i, y2low = ((y2n|(-int(h2)>>24))&0xFFFU) + 1 - (y&0xFFFU), y2high = (y2n&0xFFFU) + 1; y += hfrac; const uchar *src = &pixels[yi*stride], *src2 = &pixels[y2i*stride]; uchar *ydst = yplane, *ydst2 = yplane + ystride, *udst = uplane, *vdst = vplane; for(uint x = 0; x < dw;) { uint xn = x + wfrac - 1, xi = x>>12, w = (xn>>12) - xi, xlow = ((w+0xFFFU)&0x1000U) - (x&0xFFFU), xhigh = (xn&0xFFFU) + 1; x += wfrac; uint x2n = x + wfrac - 1, x2i = x>>12, w2 = (x2n>>12) - x2i, x2low = ((w2+0xFFFU)&0x1000U) - (x&0xFFFU), x2high = (x2n&0xFFFU) + 1; x += wfrac; uint b1, g1, r1, b2, g2, r2, b3, g3, r3, b4, g4, r4; boxsample(&src[xi<<2], stride, area, w, h, xlow, xhigh, ylow, yhigh, b1, g1, r1); boxsample(&src[x2i<<2], stride, area, w2, h, x2low, x2high, ylow, yhigh, b2, g2, r2); boxsample(&src2[xi<<2], stride, area, w, h2, xlow, xhigh, y2low, y2high, b3, g3, r3); boxsample(&src2[x2i<<2], stride, area, w2, h2, x2low, x2high, y2low, y2high, b4, g4, r4); // Y = 16 + 65.481*R + 128.553*G + 24.966*B // Cb = 128 - 37.797*R - 74.203*G + 112.0*B // Cr = 128 + 112.0*R - 93.786*G - 18.214*B *ydst++ = ((16<<12) + 1052*r1 + 2065*g1 + 401*b1)>>12; *ydst++ = ((16<<12) + 1052*r2 + 2065*g2 + 401*b2)>>12; *ydst2++ = ((16<<12) + 1052*r3 + 2065*g3 + 401*b3)>>12;; *ydst2++ = ((16<<12) + 1052*r4 + 2065*g4 + 401*b4)>>12;; const uint b = b1 + b2 + b3 + b4, g = g1 + g2 + g3 + g4, r = r1 + r2 + r3 + r4; // note: weights here are scaled by 1<<10, as opposed to 1<<12, since r/g/b are already *4 *udst++ = ((128<<12) - 152*r - 298*g + 450*b)>>12; *vdst++ = ((128<<12) + 450*r - 377*g - 73*b)>>12; } yplane += 2*ystride; uplane += uvstride; vplane += uvstride; } } void encodeyuv(const uchar *pixels) { const int flip = -1; const uint planesize = videow * videoh; if(!yuv) yuv = new uchar[(planesize*3)/2]; uchar *yplane = yuv, *uplane = yuv + planesize, *vplane = yuv + planesize + planesize/4; const int ystride = flip*int(videow), uvstride = flip*int(videow)/2; if(flip < 0) { yplane -= int(videoh-1)*ystride; uplane -= int(videoh/2-1)*uvstride; vplane -= int(videoh/2-1)*uvstride; } const uint stride = videow<<2; const uchar *src = pixels, *yend = src + videoh*stride; while(src < yend) { const uchar *src2 = src + stride, *xend = src2; uchar *ydst = yplane, *ydst2 = yplane + ystride, *udst = uplane, *vdst = vplane; while(src < xend) { const uint b1 = src[0], g1 = src[1], r1 = src[2], b2 = src[4], g2 = src[5], r2 = src[6], b3 = src2[0], g3 = src2[1], r3 = src2[2], b4 = src2[4], g4 = src2[5], r4 = src2[6]; // Y = 16 + 65.481*R + 128.553*G + 24.966*B // Cb = 128 - 37.797*R - 74.203*G + 112.0*B // Cr = 128 + 112.0*R - 93.786*G - 18.214*B *ydst++ = ((16<<12) + 1052*r1 + 2065*g1 + 401*b1)>>12; *ydst++ = ((16<<12) + 1052*r2 + 2065*g2 + 401*b2)>>12; *ydst2++ = ((16<<12) + 1052*r3 + 2065*g3 + 401*b3)>>12;; *ydst2++ = ((16<<12) + 1052*r4 + 2065*g4 + 401*b4)>>12;; const uint b = b1 + b2 + b3 + b4, g = g1 + g2 + g3 + g4, r = r1 + r2 + r3 + r4; // note: weights here are scaled by 1<<10, as opposed to 1<<12, since r/g/b are already *4 *udst++ = ((128<<12) - 152*r - 298*g + 450*b)>>12; *vdst++ = ((128<<12) + 450*r - 377*g - 73*b)>>12; src += 8; src2 += 8; } src = src2; yplane += 2*ystride; uplane += uvstride; vplane += uvstride; } } void compressyuv(const uchar *pixels) { const int flip = -1; const uint planesize = videow * videoh; if(!yuv) yuv = new uchar[(planesize*3)/2]; uchar *yplane = yuv, *uplane = yuv + planesize, *vplane = yuv + planesize + planesize/4; const int ystride = flip*int(videow), uvstride = flip*int(videow)/2; if(flip < 0) { yplane -= int(videoh-1)*ystride; uplane -= int(videoh/2-1)*uvstride; vplane -= int(videoh/2-1)*uvstride; } const uint stride = videow<<2; const uchar *src = pixels, *yend = src + videoh*stride; while(src < yend) { const uchar *src2 = src + stride, *xend = src2; uchar *ydst = yplane, *ydst2 = yplane + ystride, *udst = uplane, *vdst = vplane; while(src < xend) { *ydst++ = src[0]; *ydst++ = src[4]; *ydst2++ = src2[0]; *ydst2++ = src2[4]; *udst++ = (uint(src[1]) + uint(src[5]) + uint(src2[1]) + uint(src2[5])) >> 2; *vdst++ = (uint(src[2]) + uint(src[6]) + uint(src2[2]) + uint(src2[6])) >> 2; src += 8; src2 += 8; } src = src2; yplane += 2*ystride; uplane += uvstride; vplane += uvstride; } } bool writesound(uchar *data, uint framesize, uint frame) { // do conversion in-place to little endian format // note that xoring by half the range yields the same bit pattern as subtracting the range regardless of signedness // ... so can toggle signedness just by xoring the high byte with 0x80 switch(soundformat) { case AUDIO_U8: for(uchar *dst = data, *end = &data[framesize]; dst < end; dst++) *dst ^= 0x80; break; case AUDIO_S8: break; case AUDIO_U16LSB: for(uchar *dst = &data[1], *end = &data[framesize]; dst < end; dst += 2) *dst ^= 0x80; break; case AUDIO_U16MSB: for(ushort *dst = (ushort *)data, *end = (ushort *)&data[framesize]; dst < end; dst++) #if SDL_BYTEORDER == SDL_BIG_ENDIAN *dst = endianswap(*dst) ^ 0x0080; #else *dst = endianswap(*dst) ^ 0x8000; #endif break; case AUDIO_S16LSB: break; case AUDIO_S16MSB: endianswap((short *)data, framesize/2); break; } if(totalsize - segments.last().offset + framesize > 1000*1000*1000 && !nextsegment()) return false; addindex(frame, 1, framesize); writechunk("01wb", data, framesize); return true; } enum { VID_RGB = 0, VID_YUV, VID_YUV420 }; void flushsegment() { endlistchunk(); // LIST movi avisegmentinfo &seg = segments.last(); uint indexframes = 0, videoframes = 0, soundframes = 0; for(int i = seg.firstindex; i < index.length(); i++) { aviindexentry &e = index[i]; if(e.type) soundframes++; else { if(i == seg.firstindex || e.offset != index[i-1].offset) videoframes++; indexframes++; } } if(segments.length() == 1) { startchunk("idx1", index.length()*16); loopv(index) { aviindexentry &entry = index[i]; // printf("%3d %s %08x\n", i, (entry.type==1)?"s":"v", entry.offset); f->write(entry.type ? "01wb" : "00dc", 4); // chunkid f->putlil(0x10); // flags - KEYFRAME f->putlil(entry.offset); // offset (relative to movi) f->putlil(entry.size); // size } endchunk(); } seg.videoframes = videoframes; seg.videoindexoffset = totalsize; startchunk("ix00", 24 + indexframes*8); f->putlil(2); // longs per entry f->putlil(0x0100); // index of chunks f->putlil(indexframes); // entries in use f->write("00dc", 4); // chunk id f->putlil(seg.offset&stream::offset(0xFFFFFFFFU)); // offset low f->putlil(seg.offset>>32); // offset high f->putlil(0); // reserved 3 for(int i = seg.firstindex; i < index.length(); i++) { aviindexentry &e = index[i]; if(e.type) continue; f->putlil(e.offset + 4 + 4); f->putlil(e.size); } endchunk(); // ix00 seg.videoindexsize = uint(totalsize - seg.videoindexoffset); if(soundframes) { seg.soundframes = soundframes; seg.soundindexoffset = totalsize; startchunk("ix01", 24 + soundframes*8); f->putlil(2); // longs per entry f->putlil(0x0100); // index of chunks f->putlil(soundframes); // entries in use f->write("01wb", 4); // chunk id f->putlil(seg.offset&stream::offset(0xFFFFFFFFU)); // offset low f->putlil(seg.offset>>32); // offset high f->putlil(0); // reserved 3 for(int i = seg.firstindex; i < index.length(); i++) { aviindexentry &e = index[i]; if(!e.type) continue; f->putlil(e.offset + 4 + 4); f->putlil(e.size); } endchunk(); // ix01 seg.soundindexsize = uint(totalsize - seg.soundindexoffset); } endlistchunk(); // RIFF AVI/AVIX } bool nextsegment() { if(segments.length()) { if(segments.length() >= MAX_SUPER_INDEX) return false; flushsegment(); listchunk("RIFF", "AVIX"); } listchunk("LIST", "movi"); segments.add(avisegmentinfo(chunkoffsets[chunkdepth], index.length())); return true; } bool writevideoframe(const uchar *pixels, uint srcw, uint srch, int format, uint frame) { if(frame < videoframes) return true; switch(format) { case VID_RGB: if(srcw != videow || srch != videoh) scaleyuv(pixels, srcw, srch); else encodeyuv(pixels); break; case VID_YUV: compressyuv(pixels); break; } const uint framesize = (videow * videoh * 3) / 2; if(totalsize - segments.last().offset + framesize > 1000*1000*1000 && !nextsegment()) return false; while(videoframes <= frame) addindex(videoframes++, 0, framesize); writechunk("00dc", format == VID_YUV420 ? pixels : yuv, framesize); return true; } }; VAR(movieaccelblit, 0, 0, 1); VAR(movieaccelyuv, 0, 1, 1); VARP(movieaccel, 0, 1, 1); VARP(moviesync, 0, 0, 1); FVARP(movieminquality, 0, 0, 1); namespace recorder { static enum { REC_OK = 0, REC_USERHALT, REC_TOOSLOW, REC_FILERROR } state = REC_OK; static aviwriter *file = NULL; ICOMMAND(movierecording, "", (), intret(file ? 1 : 0)); static int starttime = 0; static int stats[1000]; static int statsindex = 0; static uint dps = 0; // dropped frames per sample enum { MAXSOUNDBUFFERS = 128 }; // sounds queue up until there is a video frame, so at low fps you'll need a bigger queue struct soundbuffer { uchar *sound; uint size, maxsize; uint frame; soundbuffer() : sound(NULL), maxsize(0) {} ~soundbuffer() { cleanup(); } void load(uchar *stream, uint len, uint fnum) { if(len > maxsize) { DELETEA(sound); sound = new uchar[len]; maxsize = len; } size = len; frame = fnum; memcpy(sound, stream, len); } void cleanup() { DELETEA(sound); maxsize = 0; } }; static queue soundbuffers; static SDL_mutex *soundlock = NULL; enum { MAXVIDEOBUFFERS = 2 }; // double buffer struct videobuffer { uchar *video; uint w, h, bpp, frame; int format; videobuffer() : video(NULL){} ~videobuffer() { cleanup(); } void init(int nw, int nh, int nbpp) { DELETEA(video); w = nw; h = nh; bpp = nbpp; video = new uchar[w*h*bpp]; format = -1; } void cleanup() { DELETEA(video); } }; static queue videobuffers; static uint lastframe = ~0U; static GLuint scalefb = 0, scaletex[2] = { 0, 0 }; static uint scalew = 0, scaleh = 0; static GLuint encodefb = 0, encoderb = 0; static SDL_Thread *thread = NULL; static SDL_mutex *videolock = NULL; static SDL_cond *shouldencode = NULL, *shouldread = NULL; bool isrecording() { return file != NULL; } float calcquality() { return 1.0f - float(dps)/float(dps+file->videofps); // strictly speaking should lock to read dps - 1.0=perfect, 0.5=half of frames are beingdropped } int gettime() { return inbetweenframes ? getclockmillis() : totalmillis; } int videoencoder(void *data) // runs on a separate thread { for(int numvid = 0, numsound = 0;;) { SDL_LockMutex(videolock); for(; numvid > 0; numvid--) videobuffers.remove(); SDL_CondSignal(shouldread); while(videobuffers.empty() && state == REC_OK) SDL_CondWait(shouldencode, videolock); if(state != REC_OK) { SDL_UnlockMutex(videolock); break; } videobuffer &m = videobuffers.removing(); numvid++; SDL_UnlockMutex(videolock); if(file->soundfrequency > 0) { // chug data from lock protected buffer to avoid holding lock while writing to file SDL_LockMutex(soundlock); for(; numsound > 0; numsound--) soundbuffers.remove(); for(; numsound < soundbuffers.length(); numsound++) { soundbuffer &s = soundbuffers.removing(numsound); if(s.frame > m.frame) break; // sync with video } SDL_UnlockMutex(soundlock); loopi(numsound) { soundbuffer &s = soundbuffers.removing(i); if(!file->writesound(s.sound, s.size, s.frame)) state = REC_FILERROR; } } int duplicates = m.frame - (int)file->videoframes + 1; if(duplicates > 0) // determine how many frames have been dropped over the sample window { dps -= stats[statsindex]; stats[statsindex] = duplicates-1; dps += stats[statsindex]; statsindex = (statsindex+1)%file->videofps; } //printf("frame %d->%d (%d dps): sound = %d bytes\n", file->videoframes, nextframenum, dps, m.soundlength); if(calcquality() < movieminquality) state = REC_TOOSLOW; else if(!file->writevideoframe(m.video, m.w, m.h, m.format, m.frame)) state = REC_FILERROR; m.frame = ~0U; } return 0; } void soundencoder(void *udata, Uint8 *stream, int len) // callback occurs on a separate thread { SDL_LockMutex(soundlock); if(soundbuffers.full()) { if(movieminquality >= 1) state = REC_TOOSLOW; } else if(state == REC_OK) { uint nextframe = (max(gettime() - starttime, 0)*file->videofps)/1000; soundbuffer &s = soundbuffers.add(); s.load((uchar *)stream, len, nextframe); } SDL_UnlockMutex(soundlock); } void start(const char *filename, int videofps, int videow, int videoh, bool sound) { if(file) return; useshaderbyname("moviergb"); useshaderbyname("movieyuv"); useshaderbyname("moviey"); useshaderbyname("movieu"); useshaderbyname("moviev"); int fps, bestdiff, worstdiff; getfps(fps, bestdiff, worstdiff); if(videofps > fps) conoutf(CON_WARN, "frame rate may be too low to capture at %d fps", videofps); if(videow%2) videow += 1; if(videoh%2) videoh += 1; file = new aviwriter(filename, videow, videoh, videofps, sound); if(!file->open()) { conoutf(CON_ERROR, "unable to create file %s", filename); DELETEP(file); return; } conoutf("movie recording to: %s %dx%d @ %dfps%s", file->filename, file->videow, file->videoh, file->videofps, (file->soundfrequency>0)?" + sound":""); starttime = gettime(); loopi(file->videofps) stats[i] = 0; statsindex = 0; dps = 0; lastframe = ~0U; videobuffers.clear(); loopi(MAXVIDEOBUFFERS) { uint w = screen->w, h = screen->w; videobuffers.data[i].init(w, h, 4); videobuffers.data[i].frame = ~0U; } soundbuffers.clear(); soundlock = SDL_CreateMutex(); videolock = SDL_CreateMutex(); shouldencode = SDL_CreateCond(); shouldread = SDL_CreateCond(); thread = SDL_CreateThread(videoencoder, NULL); if(file->soundfrequency > 0) Mix_SetPostMix(soundencoder, NULL); } void cleanup() { if(scalefb) { glDeleteFramebuffers_(1, &scalefb); scalefb = 0; } if(scaletex[0] || scaletex[1]) { glDeleteTextures(2, scaletex); memset(scaletex, 0, sizeof(scaletex)); } scalew = scaleh = 0; if(encodefb) { glDeleteFramebuffers_(1, &encodefb); encodefb = 0; } if(encoderb) { glDeleteRenderbuffers_(1, &encoderb); encoderb = 0; } } void stop() { if(!file) return; if(state == REC_OK) state = REC_USERHALT; if(file->soundfrequency > 0) Mix_SetPostMix(NULL, NULL); SDL_LockMutex(videolock); // wakeup thread enough to kill it SDL_CondSignal(shouldencode); SDL_UnlockMutex(videolock); SDL_WaitThread(thread, NULL); // block until thread is finished cleanup(); loopi(MAXVIDEOBUFFERS) videobuffers.data[i].cleanup(); loopi(MAXSOUNDBUFFERS) soundbuffers.data[i].cleanup(); SDL_DestroyMutex(soundlock); SDL_DestroyMutex(videolock); SDL_DestroyCond(shouldencode); SDL_DestroyCond(shouldread); soundlock = videolock = NULL; shouldencode = shouldread = NULL; thread = NULL; static const char *mesgs[] = { "ok", "stopped", "computer too slow", "file error"}; conoutf("movie recording halted: %s, %d frames", mesgs[state], file->videoframes); DELETEP(file); state = REC_OK; } void drawquad(float tw, float th, float x, float y, float w, float h) { glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(tw, 0); glVertex2f(x+w, y); glTexCoord2f(0, th); glVertex2f(x, y+h); glTexCoord2f(tw, th); glVertex2f(x+w, y+h); glEnd(); } void readbuffer(videobuffer &m, uint nextframe) { bool accelyuv = movieaccelyuv && renderpath!=R_FIXEDFUNCTION && !(m.w%8), usefbo = movieaccel && hasFBO && hasTR && file->videow <= (uint)screen->w && file->videoh <= (uint)screen->h && (accelyuv || file->videow < (uint)screen->w || file->videoh < (uint)screen->h); uint w = screen->w, h = screen->h; if(usefbo) { w = file->videow; h = file->videoh; } if(w != m.w || h != m.h) m.init(w, h, 4); m.format = aviwriter::VID_RGB; m.frame = nextframe; glPixelStorei(GL_PACK_ALIGNMENT, texalign(m.video, m.w, 4)); if(usefbo) { uint tw = screen->w, th = screen->h; if(hasFBB && movieaccelblit) { tw = max(tw/2, m.w); th = max(th/2, m.h); } if(tw != scalew || th != scaleh) { if(!scalefb) glGenFramebuffers_(1, &scalefb); loopi(2) { if(!scaletex[i]) glGenTextures(1, &scaletex[i]); createtexture(scaletex[i], tw, th, NULL, 3, 1, GL_RGB, GL_TEXTURE_RECTANGLE_ARB); } scalew = tw; scaleh = th; } if(accelyuv && (!encodefb || !encoderb)) { if(!encodefb) glGenFramebuffers_(1, &encodefb); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, encodefb); if(!encoderb) glGenRenderbuffers_(1, &encoderb); glBindRenderbuffer_(GL_RENDERBUFFER_EXT, encoderb); glRenderbufferStorage_(GL_RENDERBUFFER_EXT, GL_RGBA, (m.w*3)/8, m.h); glFramebufferRenderbuffer_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, encoderb); glBindRenderbuffer_(GL_RENDERBUFFER_EXT, 0); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); } if(tw < (uint)screen->w || th < (uint)screen->h) { glBindFramebuffer_(GL_READ_FRAMEBUFFER_EXT, 0); glBindFramebuffer_(GL_DRAW_FRAMEBUFFER_EXT, scalefb); glFramebufferTexture2D_(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_RECTANGLE_ARB, scaletex[0], 0); glBlitFramebuffer_(0, 0, screen->w, screen->h, 0, 0, tw, th, GL_COLOR_BUFFER_BIT, GL_LINEAR); glBindFramebuffer_(GL_DRAW_FRAMEBUFFER_EXT, 0); } else { glBindTexture(GL_TEXTURE_RECTANGLE_ARB, scaletex[0]); glCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, screen->w, screen->h); } if(tw > m.w || th > m.h || (!accelyuv && renderpath != R_FIXEDFUNCTION && tw >= m.w && th >= m.h)) { glBindFramebuffer_(GL_FRAMEBUFFER_EXT, scalefb); glViewport(0, 0, tw, th); glColor3f(1, 1, 1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, tw, 0, th, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_TEXTURE_RECTANGLE_ARB); do { glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_RECTANGLE_ARB, scaletex[1], 0); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, scaletex[0]); uint dw = max(tw/2, m.w), dh = max(th/2, m.h); if(dw == m.w && dh == m.h && !accelyuv && renderpath != R_FIXEDFUNCTION) { SETSHADER(movieyuv); m.format = aviwriter::VID_YUV; } else SETSHADER(moviergb); drawquad(tw, th, 0, 0, dw, dh); tw = dw; th = dh; swap(scaletex[0], scaletex[1]); } while(tw > m.w || th > m.h); glDisable(GL_TEXTURE_RECTANGLE_ARB); } if(accelyuv) { glBindFramebuffer_(GL_FRAMEBUFFER_EXT, encodefb); glViewport(0, 0, (m.w*3)/8, m.h); glColor3f(1, 1, 1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, (m.w*3)/8, m.h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_TEXTURE_RECTANGLE_ARB); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, scaletex[0]); SETSHADER(moviey); drawquad(m.w, m.h, 0, 0, m.w/4, m.h); SETSHADER(moviev); drawquad(m.w, m.h, m.w/4, 0, m.w/8, m.h/2); SETSHADER(movieu); drawquad(m.w, m.h, m.w/4, m.h/2, m.w/8, m.h/2); glDisable(GL_TEXTURE_RECTANGLE_ARB); const uint planesize = m.w * m.h; glPixelStorei(GL_PACK_ALIGNMENT, texalign(m.video, m.w/4, 4)); glReadPixels(0, 0, m.w/4, m.h, GL_BGRA, GL_UNSIGNED_BYTE, m.video); glPixelStorei(GL_PACK_ALIGNMENT, texalign(&m.video[planesize], m.w/8, 4)); glReadPixels(m.w/4, 0, m.w/8, m.h/2, GL_BGRA, GL_UNSIGNED_BYTE, &m.video[planesize]); glPixelStorei(GL_PACK_ALIGNMENT, texalign(&m.video[planesize + planesize/4], m.w/8, 4)); glReadPixels(m.w/4, m.h/2, m.w/8, m.h/2, GL_BGRA, GL_UNSIGNED_BYTE, &m.video[planesize + planesize/4]); m.format = aviwriter::VID_YUV420; } else { glBindFramebuffer_(GL_FRAMEBUFFER_EXT, scalefb); glReadPixels(0, 0, m.w, m.h, GL_BGRA, GL_UNSIGNED_BYTE, m.video); } glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); glViewport(0, 0, screen->w, screen->h); } else glReadPixels(0, 0, m.w, m.h, GL_BGRA, GL_UNSIGNED_BYTE, m.video); } bool readbuffer() { if(!file) return false; if(state != REC_OK) { stop(); return false; } SDL_LockMutex(videolock); if(moviesync && videobuffers.full()) SDL_CondWait(shouldread, videolock); uint nextframe = (max(gettime() - starttime, 0)*file->videofps)/1000; if(!videobuffers.full() && (lastframe == ~0U || nextframe > lastframe)) { videobuffer &m = videobuffers.adding(); SDL_UnlockMutex(videolock); readbuffer(m, nextframe); SDL_LockMutex(videolock); lastframe = nextframe; videobuffers.add(); SDL_CondSignal(shouldencode); } SDL_UnlockMutex(videolock); return true; } void drawhud() { int w = screen->w, h = screen->h; gettextres(w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); defaultshader->set(); glPushMatrix(); glScalef(1/3.0f, 1/3.0f, 1); double totalsize = file->filespaceguess(); const char *unit = "KB"; if(totalsize >= 1e9) { totalsize /= 1e9; unit = "GB"; } else if(totalsize >= 1e6) { totalsize /= 1e6; unit = "MB"; } else totalsize /= 1e3; draw_textf("recorded %.1f%s %d%%", w*3-10*FONTH, h*3-FONTH-FONTH*3/2, totalsize, unit, int(calcquality()*100)); glPopMatrix(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } void capture() { if(readbuffer()) drawhud(); } } VARP(moview, 0, 320, 10000); VARP(movieh, 0, 240, 10000); VARP(moviefps, 1, 24, 1000); VARP(moviesound, 0, 1, 1); void movie(char *name) { if(name[0] == '\0') recorder::stop(); else if(!recorder::isrecording()) recorder::start(name, moviefps, moview ? moview : screen->w, movieh ? movieh : screen->h, moviesound!=0); } COMMAND(movie, "s"); sandboxgamemaker-2.7.1+dfsg/src/cube_2_enginelicense.txt0000664000175000017500000000707111405173146023240 0ustar showardshowardSauerbraten source code license, usage, and documentation. You may use the Sauerbraten source code if you abide by the ZLIB license http://www.opensource.org/licenses/zlib-license.php (very similar to the BSD license): LICENSE ======= Sauerbraten game engine source code, any release. Copyright (C) 2001-2010 Wouter van Oortmerssen, Lee Salzman, Mike Dysart, Robert Pointon, and Quinton Reeves This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. LICENSE NOTES ============= The license covers the source code found in the "src" directory of this archive as well as the .cfg files under the "data" directory. The included ENet network library which Sauerbraten uses is covered by an MIT-style license, which is however compatible with the above license for all practical purposes. Game media included in the game (maps, textures, sounds, models etc.) are NOT covered by this license, and may have individual copyrights and distribution restrictions (see individual readmes). USAGE ===== Compiling the sources should be straight forward. Unix users need to make sure to have the development version of all libs installed (OpenGL, SDL, SDL_mixer, SDL_image, zlib). The included Makefile can be used to build. Windows users can use the included Visual Studio project files in the vcpp directory, which references the lib/include directories for the external libraries and should thus be self contained. Release mode builds will place executables in the bin dir ready for testing and distribution. An alternative to Visual Studio for Windows is MinGW/MSYS, which can be compiled using the provided Makefile. Another alternative for Windows is to compile under Code::Blocks with the provided vcpp/sauerbraten.cbp project file. The Sauerbraten sources are very small, compact, and non-redundant, so anyone wishing to modify the source code should be able to gain an overview of Sauerbraten's inner workings by simply reading through the source code in its entirety. Small amounts of comments should guide you through the more tricky sections. When reading the source code and trying to understand Sauerbaten's internal design, keep in mind the goal of Cube: minimalism. I wanted to create a very complete game / game engine with absolutely minimal means, and made a sport out of it keeping the implementation small and simple. Sauerbraten is not a commercial product, it is merely the author's idea of a fun little programming project. AUTHORS ====== Wouter "Aardappel" van Oortmerssen http://strlen.com Lee "eihrul" Salzman http://lee.fov120.com Mike "Gilt" Dysart Robert "baby-rabbit" Pointon http://www.fernlightning.com Quinton "Quin" Reeves http://bloodfrontier.com For additional authors/contributors, see the Sauerbraten binary distribution readme. sandboxgamemaker-2.7.1+dfsg/src/krsgame/0000775000175000017500000000000011660234744020101 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/krsgame/krsai.cpp0000664000175000017500000000532411421064622021711 0ustar showardshoward#include "krsgame.h" namespace bots { using namespace ai; void followroute(krsai *d) { if(!d->route.length()) { waypoint *closest = ai::closestwaypoint(d->feetpos()); ai::findroute(closest - ai::waypoints.getbuf(), rnd(ai::waypoints.length()), d->route); return; } int ind; waypoint *closest = ai::closestwaypoint(d->feetpos()); if(!closest) // this should not happen { d->route.setsize(0); return; } ind = closest - ai::waypoints.getbuf(); if(ind == d->route[0] && closest->o.dist(d->feetpos()) < 8) d->route.remove(0); d->move = 1; vec dir = vec(ai::waypoints[d->route[0]].o).sub(d->feetpos()); vectoyawpitch(dir, d->yaw, d->pitch); game::updateorientation(d); } void updatemove(krsai *d) { if(d->timeinair) d->route.setsize(0); if(!d->onnos && d->hasnos && d->isinvehicle) { d->onnos = true; d->hasnos = false; playsound(S_USENOS, NULL); d->lastnosmillis = lastmillis; } waypoint *closest = ai::closestwaypoint(d->feetpos()); if(closest && closest->o.dist(d->feetpos()) < 20 && !d->route.length()) ai::findroute(closest - ai::waypoints.getbuf(), rnd(ai::waypoints.length()), d->route); else followroute(d); game::updategears(d); game::updatespeed(d); moveplayer(d, 10, false); } void setupbots() { loopv(entities::ents) { extentity &e = *entities::ents[i]; if(e.type == BOT) { if(!ai::waypoints.length()) { conoutf("cannot load bots, map contains no waypoints.."); break; } krsai *newbot = new krsai; newbot->type = ENT_PLAYER; newbot->name = newstring(game::botnames[rnd(game::botnames.length())]); newbot->rank = e.attr[0]; switch(e.attr[0]) { case BOT_VEHICLE: game::assignvehicle(newbot, *game::vehicles[rnd(game::vehicles.length())]); newbot->hasname = false; break; case BOT_POLICE: game::assignvehicle(newbot, *game::vehicles[2]); newbot->hasname = false; break; case BOT_OPPONENT: game::assignvehicle(newbot, *game::vehicles[rnd(game::vehicles.length())]); newbot->hasname = true; break; case BOT_CIVILIAN: default: newbot->vehiclechanged = false; newbot->isinvehicle = false; newbot->playerindex = rnd(1); newbot->hasname = false; newbot->rank = BOT_CIVILIAN; break; } e.spawned = true; game::bots.add(newbot); newbot->o = newbot->newpos = vec(e.o).add(vec(0, 0, newbot->eyeheight)); } } } void updatebots() { loopv(game::bots) { krsai *bot = game::bots[i]; entities::checkitems(bot); updatemove(bot); } } } sandboxgamemaker-2.7.1+dfsg/src/krsgame/TODO.txt0000664000175000017500000000140311450351132021371 0ustar showardshowardVehicle Things: -add traction support -proper acceleration Entites: -tires -oilspill Sounds: -recived cash, -spent cash, -smash vehicle 1 -smash vehicle 2, -using nos, -vehicle idle, -vehicle accelerate, Models: Entites: -nos -playerfinish (flag) -tires -oilspill -spikestrip Vehicles: -car -truck Code: -mdl roll (for proper vehicle picth and roll alighment on surfaces not flat) -gamemodes -player1->eyeheight higher when in firstperson view. Hud: -scaledown speedometer -dashboard (when firstperson view) -nos bar (how much nos left!) Store: -purchase entities via krsitem code. -enumerate owned items and display in gui GUI: -player owned items -player owned vehicles sandboxgamemaker-2.7.1+dfsg/src/krsgame/krshud.cpp0000664000175000017500000000315311544613346022107 0ustar showardshoward#include "krsgame.h" #include "engine.h" namespace game { VARP(metertype, 0, 0, 1); void quad(int x, int y, int xs, int ys) { glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2i(x, y); glTexCoord2f(1, 0); glVertex2i(x+xs, y); glTexCoord2f(0, 1); glVertex2i(x, y+ys); glTexCoord2f(1, 1); glVertex2i(x+xs, y+ys); glEnd(); } void gameplayhud(int w, int h) { float scale = min(w / 1600.0f, h / 1200.0f); float right = w / scale, bottom = h / scale; glPushMatrix(); glScalef(scale, scale, 1); if(thirdperson) { /*apply meter based on meter type selection*/ if(metertype == 0) settexture("data/krs/hud/meter_km.png", 3); else if(metertype == 1) settexture("data/krs/hud/meter_mph.png", 3); quad(right-512, bottom-512, 512, 512); /*apply needel to meter*/ settexture("data/krs/hud/needle.png", 3); const static int coords[4][2] = {{0, 1}, {1, 1}, {0, 0}, {1, 0}}; vec points[4] = { vec(-32, -40, 0), vec(32, -40, 0), vec(-32, 216, 0), vec(32, 216, 0)}; float angle = (player1->vel.magnitude() * 170.0f / 250.0f ) + 60; loopi(4) points[i].rotate_around_z(angle * RAD); glBegin(GL_TRIANGLE_STRIP); loopi(4) { glTexCoord2f(coords[i][0], coords[i][1]); glVertex2i(right - 256 + points[i].x, bottom - 256 + points[i].y); } glEnd(); } glPopMatrix(); } const char *defaultcrosshair(int index) { return editmode ? "packages/crosshairs/edit" : "data/items"; } int selectcrosshair(float &r, float &g, float &b) { r = b = 0.5; g = 1.0f; return editmode; } } sandboxgamemaker-2.7.1+dfsg/src/krsgame/krsstubs.cpp0000664000175000017500000000760611527772734022506 0ustar showardshoward#include "krsgame.h" namespace game { int clipconsole(int w, int h){ return 0;} float abovegameplayhud(int w, int h) {return 1;} const char *getmapinfo() {return NULL;} void g3d_gamemenus() {} void adddynlights() {} void resetgamestate() {} void newmap(int size){} void writemapdata(stream *f) {} void preload() {} void parsepacketclient(int chan, packetbuf &p) {} void writeclientinfo(stream *f) {} void toserver(char *text) {} void connectattempt(const char *name, const char *password, const ENetAddress &address) {} void connectfail() {} void parseoptions(vector &args) {} void renderavatar() {} void setupcamera(){} void lighteffects(dynent *d, vec &color, vec &dir) {} void particletrack(physent *owner, vec &o, vec &d) {} void dynlighttrack(physent *owner, vec &o, vec &hud) {} #ifndef NEWGUI void serverinfoendcolumn(g3d_gui *g, int i) {} #endif void vartrigger(ident *id) {} void bounced(physent *d, const vec &surface) {} void registeranimation(char *dir, char* anim, int num) {} void writegamedata(vector &extras) {} void readgamedata(vector &extras) {} void loadconfigs(){} void dynentcollide(physent *d, physent *o, const vec &dir) {} void edittrigger(const selinfo &sel, int op, int arg1, int arg2, int arg3) {} void texturefailed(char *name, int slot) {} void mmodelfailed(const char *name, int idx) {} void mapfailed(const char *name) {} void suicide(physent *d){} bool showenthelpers() { return editmode; } bool ispaused() { return false; } bool allowdoublejump(){ return false; } bool detachcamera() { return false; } bool needminimap() { return false; } bool allowedittoggle() { return true; } bool allowmove (physent *d) {return true;} bool collidecamera() {return !editmode;} #ifndef NEWGUI bool serverinfostartcolumn(g3d_gui *g, int i) {return false;} bool serverinfoentry(g3d_gui *g, int i, const char *name, int port, const char *desc, const char *map, int ping, const vector &attr, int np) {return false;} #endif } namespace entities { int extraentinfosize() { return 0; } int *getmodelattr(extentity &e) { return NULL; } const char *entnameinfo(entity &e) { return ""; } void fixentity(extentity &e){} void editent(int i, bool local) {} void writeent(entity &e, char *buf) {} void renderhelpertext(extentity &e, int &colour, vec &pos, string &tmp){} void entradius(extentity &e, bool &color){} void readent(entity &e, char *buf, int ver){} bool dirent(extentity &e){return false;} bool radiusent(extentity &e){return false;} bool mayattach(extentity &e) { return false; } bool attachent(extentity &e, extentity &a) { return false; } bool printent(extentity &e, char *buf) { return false; } bool checkmodelusage(extentity &e, int i){ return false; } } namespace server { int reserveclients() { return 0; } int clientconnect(int n, uint ip) { return DISC_NONE; } int numchannels() {return 0;} int laninfoport() {return 0;} int serverinfoport(int servport) {return 0;} int serverport(int infoport) {return 0;} int masterport() {return 0;} const char *defaultmaster() {return "";} void *newclientinfo() {return NULL;} void deleteclientinfo(void *ci) {} void serverinit() {} void clientdisconnect(int n) {} void localdisconnect(int n) {} void localconnect(int n) {} void recordpacket(int chan, void *data, int len) {} void parsepacket(int sender, int chan, packetbuf &p) {} void sendservmsg(const char *s) {} void serverinforeply(ucharbuf &q, ucharbuf &p) {} void serverupdate() {} void processmasterinput(const char *cmd, int cmdlen, const char *args) {} bool allowbroadcast(int n) { return false; } bool sendpackets(bool force) { return false; } bool servercompatible(char *name, char *sdec, char *map, int ping, const vector &attr, int np) { return true; } bool ispaused() {return game::ispaused();} } sandboxgamemaker-2.7.1+dfsg/src/krsgame/krsgame.h0000664000175000017500000001226011450351132021670 0ustar showardshoward#ifndef __KRSGAME_H__ #define __KRSGAME_H__ /*vehicle simulation By: Dale Weiler (graphitemaster) *for use with sandbox and sandbox related projects or mods */ #include "cube.h" /*all time definitions are represented in millisconds */ #define NOSTIME 5000 // half a second #define FIRETIME 5000 // half a second #define ACCELTIME 5000 // half a second #define ENTTIME 30000 // thirty seconds /// static entity types enum { NOTUSED = ET_EMPTY, // entity slot not in use in map LIGHT = ET_LIGHT, // lightsource, attr1 = radius, attr2 = intensity MAPMODEL = ET_MAPMODEL, // attr1 = angle, attr2 = idx PLAYERSTART, // attr1 = angle ENVMAP = ET_ENVMAP, // attr1 = radius PARTICLES = ET_PARTICLES, MAPSOUND = ET_SOUND, SPOTLIGHT = ET_SPOTLIGHT, PLAYERFINISH, // finish for race mode MONEY, // money pickup ent NOS, // nitrous oxide SPIKESTRIP, // spike strip VEHICLE, // vehicle get in entity BOT, // bot entity MAXENTTYPES }; /// hardcodded sounds enum { S_JUMP = 0, S_LAND, S_SPLASH_IN, S_SPLASH_OUT, S_KART_RUNNING, S_KART_IDLE, S_SMASH1, S_SMASH2, S_BURN, S_TIREPOP, S_RECICVEMONEY, S_USEMONEY, S_GAMESTART, S_GAMEFINISHED, S_USENOS, S_PICKUP }; /// gear types enum { GEAR_REVERSE = 0, GEAR_FIRST, GEAR_SECOND, GEAR_THIRD, GEAR_FOURTH, GEAR_FIFTH }; ///bot types enum { BOT_VEHICLE = 0, BOT_OPPONENT, BOT_POLICE, BOT_CIVILIAN }; /// transmission types enum { TRANS_STANDARD = 0, TRANS_AUTOMATIC }; //gamemodes enum { MODE_RACE = 0, MODE_BUMPER, MODE_DRAG, MODE_JUMPPING }; #if 0 static struct gamemodeinfo { const char *name; int mode; const char *info; } gamemodes[] = { { "Track Racing:", MODE_RACE, "You and your opponet races around a track, first one to the finish line wins"}, { "Bumper Cars:", MODE_BUMPER, "Drive around bumping players off the track, last man wins"}, { "Drag Racing:", MODE_DRAG, "You are givin a straight track, make it to the finish line as quick as possible, the quicker the better" }, { "Vehcile Jumpping:", MODE_JUMPPING, "You are givin a track full of jumps, drive around and jump the higher you get the more money you get" } }; #endif struct krsentity : extentity{}; //this is compatible with the FPSGAME waypoints struct waypoint { waypoint *parent; vec o; vector links; int score; waypoint() {} waypoint(const vec &o) : parent(NULL), o(o), score(-1) {} }; struct vehicle { const char *name, *mdl; int maxspeed, price, traction, flags, jumpvel; vehicle() : name(NULL), mdl(NULL), maxspeed(0), price(0), traction(0), flags(0), jumpvel(0) {} ~vehicle() { if(name) delete[] name; if(mdl) delete[] mdl; } }; struct krschar : dynent { const char *name; bool attacking; bool vehiclechanged; bool isinvehicle; bool onnos,onfire; bool hasflat, hasnos; int gear, gears[6]; int vehicleindex, playerindex; int money, traction, damage; vector hasvehicle; int lastnosmillis, lastfiremillis, lastaccelmillis; editinfo *edit; krschar() : attacking(false), vehiclechanged(true), isinvehicle(true), onnos(false), onfire(false), hasflat(false), hasnos(false), gear(0), vehicleindex(0), playerindex(0), money(200), traction(50), damage(0) { respawn(); } void respawn() { dynent::reset(); collidetype = COLLIDE_AABB; attacking = false; vehiclechanged = false; onnos = false; onfire = false; hasflat = false; hasnos = false; gear = GEAR_FIRST; traction = 50; damage = 0; lastnosmillis = 0; lastfiremillis = 0; lastaccelmillis = 0; } }; struct krsai : krschar { vector route; int entindex, rank; bool hasname; }; namespace entities { extern vector ents; extern void renderentities(); extern void checkitems(krschar *d); extern void trypickup(int n, krschar *d); extern int lastpickupmillis; } namespace bots { void setupbots(); void updatebots(); } namespace ai { extern vector waypoints; extern waypoint *closestwaypoint(const vec &o); extern void loadwaypoints(const char *name, bool msg = false); extern void savewaypoints(const char *name); extern void findroute(int from, int to, vector &route); extern void renderwaypoints(); extern void trydrop(); extern void clearwaypoints(); } namespace game { extern krschar *player1; extern vector bots; extern vector vehicles; extern vector botnames; extern void changeplayerstate(krschar *d); extern void spawnplayer(krschar *d); extern void assignvehicle(krschar *d, vehicle &car); extern void updatespeed(krschar *d); extern void updategears(krschar *d); extern void updateorientation(krschar *d); extern void setupbots(); extern bool intermission; extern int debug; extern int dirtmap; extern int gamemode; //krsrender extern void rendersmoke(krschar *d); extern void renderflame(krschar *d); extern void renderplayer(krschar *d); } #endif sandboxgamemaker-2.7.1+dfsg/src/krsgame/krsscript.cpp0000664000175000017500000000316611450351132022623 0ustar showardshoward#include "krsgame.h" using namespace game; namespace krsscript { ICOMMAND(registervehicle, "siiiii", ( const char *mdl, int *flags, int *jumpvel, int *maxspeed, int *traction, int *price ),{ vehicle *vehiclelookup = new vehicle; vehiclelookup->mdl = newstring(mdl); vehiclelookup->flags = *flags; vehiclelookup->jumpvel = *jumpvel; vehiclelookup->maxspeed = *maxspeed; vehiclelookup->traction = *traction; vehiclelookup->price = *price; vehicles.add(vehiclelookup); player1->hasvehicle.add(false); }); ICOMMAND(registerbot, "s", (const char *name), { game::botnames.add(newstring(name)); if(debug) conoutf("DEBUG: Registered Bot Name: %s", name); }); ICOMMAND(buyvehicle, "i", (int *index), { vehicle *vehiclelookup = vehicles[*index]; if(vehiclelookup && !player1->hasvehicle[*index]) { if(player1->money >= vehiclelookup->price) { player1->money -= vehiclelookup->price; player1->hasvehicle[*index] = true; } } }); ICOMMAND(sellvehicle, "i", (int *index), { vehicle *vehiclelookup = vehicles[*index]; if(vehiclelookup && player1->hasvehicle[*index]) { player1->money += vehiclelookup->price; player1->hasvehicle[*index] = false; player1->isinvehicle = false; } }); ICOMMAND(ineedacar, "", (), { bool deserves = true; vehicle *vehiclelookup = vehicles[0]; loopv(player1->hasvehicle) { if(player1->hasvehicle[i]) { deserves = false; } } if(deserves) { player1->hasvehicle[0] = true; player1->isinvehicle = true; } }); } sandboxgamemaker-2.7.1+dfsg/src/krsgame/krs.cpp0000664000175000017500000002155511450351132021400 0ustar showardshoward#include "krsgame.h" using namespace entities; namespace game { string clientmap; const char *getclientmap() { return clientmap; } bool connected = false; bool intermission = false; int gamemode; void gamedisconnect(bool cleanup) {connected = false;} void gameconnect(bool remote) {connected = true;} vector botnames; vector vehicles; vector bots; VARP(debug, 0, 1, 1); VARR(dirtmap, 0, 0, 1); SVARFP(name, "noname", player1->name = newstring(name)); VARFP(playermodel, 0, 0, 1, player1->playerindex = playermodel); krschar *player1 = new krschar();// our player krschar *spawnstate(krschar *d) { d->respawn(); return d; } void spawnplayer(krschar *d) { findplayerspawn(d, -1, 0); spawnstate(d); d->state = d==player1 && editmode ? CS_EDITING : CS_ALIVE; } void respawnself() { if(paused || ispaused()) return; if(gamemode == MODE_BUMPER) return; spawnplayer(player1); } bool canjump() { if(player1->state == CS_ALIVE && !player1->isinvehicle) return true; return false; } /*controls*/ ICOMMAND(accelerate, "D", (int *down), { player1->k_up = *down!=0; if(player1->gear == GEAR_REVERSE) player1->gear = GEAR_FIRST; }); ICOMMAND(reverse, "D", (int *down), { player1->k_down = *down!=0; player1->gear = GEAR_REVERSE; }); ICOMMAND(jump, "D", (int *down), { if(!*down || canjump()) player1->jumping = *down!=0; }); ICOMMAND(usenos, "", (), { if(!player1->onnos && player1->hasnos && player1->isinvehicle) { player1->onnos = true; player1->hasnos = false; playsound(S_USENOS, NULL); player1->lastnosmillis = lastmillis; } }); ICOMMAND(action, "", (), { if(player1->isinvehicle) player1->isinvehicle = false; else player1->isinvehicle = true; }); ICOMMAND(givenos, "s", (), player1->hasnos = true); ICOMMAND(steerleft, "D", (int *down),player1->k_left = *down != 0); ICOMMAND(steerright, "D", (int *down),player1->k_right = *down != 0); ICOMMAND(restart, "", (), spawnplayer(player1)); ///updates void updategears(krschar *d) { if(d->vehiclechanged && d->isinvehicle) { vehicle *vehiclelookup = vehicles[d->vehicleindex]; loopi(6) { d->gears[i] = vehiclelookup->maxspeed*(i+1)/6; if(debug) conoutf("Assigned Gears: %d", d->gears[i]); } d->maxspeed = d->gears[0]; d->vehiclechanged = false; } } ICOMMAND(mydamage, "i", (int *i), player1->damage = *i); void updatedamage(krschar *d) { if(!d->isinvehicle) return; if(d->damage >= 50) rendersmoke(d); if(d->damage >= 80) { if(d->onfire) renderflame(d); else { d->onfire = true; d->lastfiremillis = lastmillis; } if(lastmillis > d->lastfiremillis + FIRETIME && d->onfire) { if(d==player1) respawnself(); else { krsai *pl = (krsai *)d; pl->state = CS_DEAD; } } } } void updatespeed(krschar *d) { if(!d->isinvehicle) d->maxspeed = 100; else { if(totalmillis > d->lastaccelmillis + ACCELTIME && d->gear != GEAR_REVERSE) { d->gear++; d->gear = clamp((int)GEAR_FIFTH, (int)GEAR_FIRST, d->gear); d->lastaccelmillis = lastmillis; } if(!d->onnos && !d->hasflat) d->maxspeed = d->gears[d->gear]; else { if(d->hasflat) d->maxspeed = d->gears[0] * 0.5; else { if(lastmillis > d->lastnosmillis+NOSTIME) d->onnos = false; else d->maxspeed = d->gears[GEAR_FIFTH]*1.5f; } } } } void updateorientation(krschar *d) { if(!d->isinvehicle) return; if(d->timeinair) { d->pitch -= curtime / 20.0f; d->pitch = max(-90, d->pitch); } else if(!d->floor.iszero()) { if(d==player1) { vec dir = vec(d->floor).rotate(PI / 2.0f, vec((d->yaw + 90) * RAD, 0)); float yaw, newpitch; vectoyawpitch(dir, yaw, newpitch); yaw = min(1, curtime / 2000.0f + curtime * d->vel.magnitude() / 40000.0f); d->pitch = (d->pitch + 90) * (1 - yaw) + (newpitch + 90) * (yaw) - 90; } } } void updateplayer() { if(editmode) { player1->maxspeed = 100; moveplayer(player1, 10, true); return; } updatedamage(player1); updategears(player1); updatespeed(player1); checkitems(player1); moveplayer(player1, 10, true); if(!(player1->k_up ^ player1->k_down)) player1->move = 0; else if(player1->k_up) player1->move = 1; else player1->move = -1; if(player1->k_left ^ player1->k_right) { player1->yaw += (player1->k_left ? -1 : 1) * curtime / 500.0f * min(60.0f, player1->vel.magnitude()); } updateorientation(player1); } void updateworld() //main game update loop { if(!curtime) return; physicsframe(); updateplayer(); bots::updatebots(); ai::trydrop(); if(editmode) intermission = false; else disablezoom(); } bool mousemove(int &dx, int &dy, float &cursens) { if(editmode || !player1->isinvehicle) return false; return true; } bool recomputecamera(physent *&camera1, physent &tempcamera, bool &detachedcamera, float &thirdpersondistance) { if(player1->state == CS_DEAD || editmode || !thirdperson || !player1->isinvehicle) return false; detachedcamera = true; camera1 = &tempcamera; float mult = min(1, 2 * curtime / 200.0f); vec pos = vec(0, 0, thirdpersondistance * .4).add(player1->o).sub(vec(player1->yaw * RAD, -15 * RAD).mul(thirdpersondistance)); tempcamera.o.mul(1 - mult).add(pos.mul(mult)); tempcamera.yaw = player1->yaw; tempcamera.pitch = -15; return true; } ///vehicle oriented stuff void assignvehicle(krschar *d, vehicle &car) { if(debug) { conoutf( "DEBUG: assigned vehicle: \"%s\", using vehicle model: \"packages/models/vehicles/%s\"", car.name, car.mdl ); } d->vehiclechanged = true; d->jumpvel = car.jumpvel; updategears(d); } ///engine specific void setwindowcaption() { defformatstring(capt)("SandBox %s: Vehicle Simulator - %s", version, getclientmap()[0] ? getclientmap() : "[new map]"); SDL_WM_SetCaption(capt, NULL); } void startmap(const char *name) { lastpickupmillis = -30000; copystring(clientmap, name ? name : ""); intermission = false; findplayerspawn(player1, -1); ai::clearwaypoints(); ai::loadwaypoints(name); bots::setupbots(); if(identexists("mapstart")) execute("mapstart"); } void edittoggled(bool on) { if(!on) { bots.deletecontents(); bots::setupbots(); } } void physicstrigger(physent *d, bool local, int floorlevel, int waterlevel, int material) { if(d->state!=CS_ALIVE||d->type==ENT_INANIMATE) return; switch(material) { case MAT_LAVA: if (waterlevel==0) break; playsound(S_BURN, d==player1 ? NULL : &d->o); loopi(60) { vec o = d->o; o.z -= d->eyeheight *i/60.0f; regular_particle_flame(PART_FLAME, o, 6, 2, 0x903020, 3, 2.0f); regular_particle_flame(PART_SMOKE, vec(o.x, o.y, o.z + 8.0f), 6, 2, 0x303020, 1, 4.0f, 100.0f, 2000.0f, -20); } if(d==player1) respawnself(); else { krsai *pl = (krsai *)d; pl->state = CS_DEAD; } break; case MAT_WATER: if (waterlevel==0) break; playsound(waterlevel > 0 ? S_SPLASH_IN : S_SPLASH_OUT , d==player1 ? NULL : &d->o); particle_splash(PART_WATER, 200, 200, d->o, (watercolor.x<<16) | (watercolor.y<<8) | watercolor.z, 0.5); d->maxspeed = 0; break; default: if (floorlevel==0) break; playsound(floorlevel > 0 ? S_JUMP : S_LAND, local ? NULL : &d->o); break; } } void openworld(const char *name, bool fall = false) { assignvehicle(player1, *vehicles[player1->vehicleindex]); if(!connected) localconnect(); if(name && *name && load_world(name)) return; //else if(fall && load_world(DEFAULTMAP)) // return; else emptymap(10, true, (name && *name) ? name : NULL); } ICOMMAND(map, "s", (char *s), openworld(s)) ICOMMAND(changevehicle, "i", (int *index), { vehicle *vehiclelookup = vehicles[*index]; if(vehiclelookup && player1->hasvehicle[*index]) { assignvehicle(player1, *vehiclelookup); player1->vehicleindex = *index; } }); void initclient() { if(!player1->name) player1->name = name; clientmap[0] = 0; } int numdynents(){ return 1+bots.length();} dynent *iterdynents(int i) { if(!i) return player1; i--; if(i waypoints; waypoint *prev = NULL; VARF(dropwaypoints, 0, 0, 1, prev = NULL); VAR(waypointdoublelink, 0, 1, 1); void clearwaypoints() { if(game::bots.length()) game::bots.deletecontents(); waypoints.setsize(0); prev=NULL; } COMMAND(clearwaypoints, ""); waypoint *closestwaypoint(const vec &o) { waypoint *result = NULL; float dist = 1e16; loopv(waypoints) { float newdist = waypoints[i].o.dist(o); if(newdist < dist) { result = &waypoints[i]; dist = newdist; } } return result; } void dropwaypoint(const vec &o) { waypoint *closest = closestwaypoint(o); if(!prev) { prev = &waypoints.add(waypoint(o)); return; } float distp = prev->o.dist(o); float distc = closest->o.dist(o); float distn = closest->o.dist(prev->o); if(distp > 15 && distc > 15) { waypoint *next = &waypoints.add(waypoint(o)); prev->links.add(next - waypoints.getbuf()); prev = next; } else if(distn > 31) //the spot is overshot, but the target was somewhere between the nodes, so we add one at an intermediary { vec pos = vec(prev->o).add(closest->o).div(2.0f); //just in case buffer position changes ushort close = closest - waypoints.getbuf(), prior = prev - waypoints.getbuf(), n; waypoint *next = &waypoints.add(waypoint(pos)); n = next - waypoints.getbuf(); if(waypointdoublelink) next->links.add(close); next->links.add(prior); prev->links.add(n); if(waypointdoublelink) closest->links.add(n); prev = next; } else //if(distp > distn * 0.6f && distc < distn * 0.6f) { int ind = closest - waypoints.getbuf(); if(prev->links.find(ind) == -1) prev->links.add(ind); ind = prev - waypoints.getbuf(); if(waypointdoublelink && game::player1->timeinair < 25 && closest->links.find(ind) == -1) closest->links.add(ind); prev = closest; } } void trydrop() { if(!dropwaypoints || editmode || game::player1->state == CS_DEAD || game::player1->timeinair > 250) return; if(!waypoints.length()) { prev = &waypoints.add(waypoint(game::player1->feetpos())); return; } else if (!prev) prev = closestwaypoint(game::player1->feetpos()); vec feet = game::player1->feetpos(); float dist = prev->o.dist(feet); if(dist > 75) { prev = NULL; dropwaypoint(feet); } else if(dist >= 20) { vec delta = feet.sub(prev->o).normalize().mul(24); feet = prev->o; while(dist > 20) { dist -= 24; feet.add(delta); dropwaypoint(feet); } } else dropwaypoint(feet); //link :D } FVAR(waypointmergedist, 1, 8, 128); FVAR(waypointlinkmaxdist, 1, 32, 128); VAR(waypointmergepasses, 1, 4, 128); VAR(waypointmaxlinks, 3, 10, 255); void removewaypoint(int ind) { if(!waypoints.inrange(ind)) { conoutf("ERROR: Waypoint %i not inrange", ind); return; } loopv(waypoints) { waypoint &w = waypoints[i]; loopvj(w.links) { if(w.links[j] == ind) { w.links.remove(j); j--; } else if(w.links[j] > ind) w.links[j]--; } } waypoints.remove(ind); } ICOMMAND(removewaypoint, "i", (int *ind), removewaypoint(*ind)) void removelink(int a, int b) { if(!waypoints.inrange(a) || !waypoints.inrange(b)) { conoutf("ERROR: %i or %i is not inrange", a, b); return; } waypoint &first = waypoints[a], &second = waypoints[b]; int ind; if((ind = first.links.find(b)) >= 0) first.links.remove(ind); if((ind = second.links.find(a)) >= 0) second.links.remove(ind); } ICOMMAND(removewaypointlink, "ii", (int *a, int *b), removelink(*a, *b)) void mergewaypoints(int first, int second) { waypoint &f = waypoints[first]; waypoint &s = waypoints[second]; int tmp; while((tmp = s.links.find(first)) != -1) s.links.remove(tmp); loopv(s.links) { if(f.links.find(s.links[i]) == -1) f.links.add(s.links[i]); } loopv(waypoints) { int tmp; if(i !=first && (tmp = waypoints[i].links.find(second)) >= 0) waypoints[i].links[tmp] = first; } f.o.add(s.o).div(2.0f); removewaypoint(second); } static inline bool sortlinks(ushort a, ushort b) { waypoint &first = waypoints[a], &second = waypoints[b]; return first.score < second.score; } void optimisewaypoints() { loopi(waypointmergepasses) { loopvj(waypoints) { loopvk(waypoints) { if(j == k) continue; waypoint &f = waypoints[j]; waypoint &s = waypoints[k]; if(f.o.dist(s.o) <= waypointmergedist) { conoutf("merging points %i and %i", j, k); mergewaypoints(j, k); } } if(waypoints[j].links.length() > waypointmaxlinks) { //we remove the longest ones above the limit. //this requires sorting first waypoint &point = waypoints[j]; loopvk(point.links) { waypoint &link = waypoints[point.links[k]]; link.score = link.o.dist(point.o); } point.links.sort(sortlinks); while(point.links.length() > waypointmaxlinks) { waypoint &tmp = waypoints[point.links.last()]; conoutf("removing link from %i to %i with distance %i", i, point.links.last(), tmp.score); point.links.pop(); } } } } loopv(waypoints) { if(!waypoints[i].links.length()) { conoutf("removing node %i (no links!)", i); removewaypoint(i); i--; } loopvj(waypoints[i].links) { waypoint &w = waypoints[i], &l = waypoints[waypoints[i].links[j]]; if(w.o.dist(l.o) > waypointlinkmaxdist) { conoutf("removing link from %i to %i (too far)", i, waypoints[i].links[j]); w.links.remove(j); j--; } } } } COMMAND(optimisewaypoints, ""); void loadwaypoints(const char *name, bool msg) { if(name && *name) getmapfilenames(name); defformatstring(wptname)("packages/%s/%s.wpt", mpath, mname); path(wptname); stream *f = opengzfile(wptname, "rb"); if(!f) { if(msg) conoutf("ERROR: failed to load waypoints"); return; } char magic[4]; if(f->read(magic, 4) < 4 || memcmp(magic, "OWPT", 4)) { conoutf("ERROR: magic mismatch (expected OWPT, got %4.4s)", magic); delete f; return; } clearwaypoints(); ushort numwp = f->getlil(); loopi(numwp) { waypoint &w = waypoints.add(); w.o.x = f->getlil(); w.o.y = f->getlil(); w.o.z = f->getlil(); int numlinks = f->getchar(); if(numlinks > 10) conoutf("WARNING: links for waypoint #%i are exorbitant (%i)", i, numlinks); loopj(numlinks) w.links.add(f->getlil() - 1); //FPS game uses 0 to denote dummy waypoint, and use 1+ to denote real waypoints - we don't } conoutf("successfully loaded %i waypoints", waypoints.length()); delete f; } ICOMMAND(loadwaypoints, "s", (const char *s), loadwaypoints(s, true)); void savewaypoints(const char *name) { if(waypoints.length() <= 1) return; if(name && *name) getmapfilenames(name); defformatstring(wptname)("packages/%s/%s.wpt", mpath, mname); path(wptname); stream *f = opengzfile(wptname, "wb"); if(!f) { conoutf("failed to save waypoints"); return; } f->write("OWPT", 4); f->putlil(waypoints.length()); for(int i = 0; i < waypoints.length(); i++) { waypoint &w = waypoints[i]; f->putlil(w.o.x); f->putlil(w.o.y); f->putlil(w.o.z); f->putchar(w.links.length()); loopvj(w.links) f->putlil(w.links[j] + 1); //FPS game uses 0 to denote dummy waypoint, and use 1+ to denote real waypoints - we don't } conoutf("successfully saved %i waypoints", waypoints.length()); delete f; } COMMAND(savewaypoints, "s"); //this is an attempt at an A-STAR search algorithm //note that waypoints are considered equidistant for the most part void findroute(int from, int to, vector &route) { route.setsize(0); if(!waypoints.length() || !waypoints.inrange(from) || !waypoints.inrange(to) || from == to) return; //determine scores loopv(waypoints) { waypoints[i].score = waypoints[i].o.dist(waypoints[to].o); waypoints[i].parent = NULL; } //recurse waypoint *cur = &waypoints[from], *first = cur; while(true) { int lowest = -1; //try the "series of low scores" method loopv(cur->links) { waypoint &l = waypoints[cur->links[i]]; if(cur->links[i] == to || ( !l.parent && &l != first && (lowest < 0 || l.score < waypoints[lowest].score) && (l.links.length() > 1 || (l.links.length() && !waypoints[l.links[0]].parent)) ) ) { lowest = cur->links[i]; } } if(lowest == -1 && cur == first) return; else if (lowest == -1) { cur = cur->parent; } else { waypoints[lowest].parent = cur; cur = &waypoints[lowest]; } if(lowest == to) break; } //cur should still be the destination while(true) { route.add(cur - waypoints.getbuf()); if(cur == first) break; cur = cur->parent; } route.reverse(); } vector testroute; ICOMMAND(waypointtest, "ii", (int *f, int *t), findroute(*f, *t, testroute);) void renderwaypoints() { loopv(waypoints) { waypoint &w = waypoints[i]; defformatstring(ds)("%i", i); particle_textcopy(vec(0, 0, 6).add(w.o), ds, PART_TEXT, 1, 0xFF00FF, 3); loopvj(w.links) { waypoint &l = waypoints[w.links[j]]; particle_flare(w.o, l.o, 1, PART_STREAK, 0x0000FF, .5); } } for(int i = 1; i < testroute.length(); i++) { waypoint &prev = waypoints[testroute[i-1]]; waypoint &cur = waypoints[testroute[i ]]; particle_flare(vec(0, 0, 1).add(prev.o), vec(0, 0, 1).add(cur.o), 1, PART_STREAK, 0xFF0000, .5); } } } sandboxgamemaker-2.7.1+dfsg/src/krsgame/PSEUDO-CODE0000664000175000017500000001116211442705012021521 0ustar showardshoward/* A simple bit of sample code for the vehicle simulation project this will contain: much more complicated physics then this engine can possibly ever offer. This is non-workable code, that will be tied into the vehicle simulation project, when done. While it may contain many other non working, or unrelated bits of text it will be there for refrence, to allow a better understanding of the complicated side of things. */ /// Vehicle Physics Explained... [SlowDown_On_Steering] { coefficients = abs(sin(theta))I - abs(cos(theta))J; /* I and J are unit vectors aligned with and perpendicular to the long axis of the vehicle,respectively, and theta is the angle of the tires while steering relitive to the vehicle's body. */ } [Accelerating_Force] { /* The vehicles acceleration force, can be determined by the radius, R, of a circle that would be made if that vehicle continued to turn in it's current direction. */ return (M * V^2/R); /* Where V represnets the vehicles linear speed. For eg when you're vehicle is moving on a strightaway, that vehicle has a net friction of zero at the front tires when you turn into a curve you get a negitive component from cos(theta), best viewed as -cos(theta), which is the decelerating force. */ } [Vehicle_Friction] { /* Vehcile friction will be kenetic, friction is simply explained as (C * W), where C will be the vehicles coefficient of friction between the tire and surface of which the vehicle is on. Where W will be the weight of the vehcile. */ return (C * W); /* For non-sliding friction, the total magnitude of the I and J components in the SlowDown_On_Steering stub MUST BE NO MORE then the maximal force of static friction, for example. */ return (sqrt((A . FA)^2 + (B . FA)^2) <= C * W); /* where FA is the total of accelerating force. If that's not the case, the vehicle will get into a sliding type friction. */ } /* Other bits and pieces */ /* Okay lets consider this, lets say we have a vehicle moving in a straight line. What forces are at play here? Some would think none, I thought of non at first, it only took me awhile to think that something as simple as a moving vehicle in line is quite more complicated as one would suspect. First and foremost there is the tractive force, this is the force deliverd by the engine via the rear wheels, or the front wheels depending on the type of vehicle, but for the sake of simplicity lets just talk about the rear wheels. Some would think the engine turns the wheels forward, when in theory it actually applies a torque on the wheel, the wheel push backwards on the surface of which is underneath and in reaction, that same surface pushes back in a forward direction. the tractive force is thus equivalent in magnitude to a variable engine force, which is controleld by the user. Ffraction = u * engineforce; where u is a unit vector in the direction the vehicle is heading. If this where the only force, the vehicle would accelerate to ifinite speeds. This is clearly not the case in real life, people and children, Hirato and all who are reading this welcome to the world of resistance forces. On a vehicle the first and most important one is air resistance, a.k.a aerodynamic drag. This force is so important because it is proportional to the square of the velocity. When we're driving a vehicle FAST this becomes the most important resistance force. drag = -Cdrag * v * |v| where Cdrag is a constant and v is the velocity vector, and the notation |v| referes to the magnitude of vector v. The magnitude of the velocity vector is more commonly know as the speed. Then we have yet another resistance, this is the rolling resistance, this resistance is caused by friction between the material on the vehicles tires and the surface on which thoes wheels roll along, including the friciton in the axels. Frr = -Crr * v where Crr is a constant and v is the velocity vector. At low speeds the rolling resistance is the main resistance force, however at high speeds the drag resistance takes over in magnitude. At approximently 100km/h(60 mph, 30 m/s) This means Crr MUST BE EXACTLY 30 times the value of Cdrag. The total longtitudinal force is the vector sum of all of all forces Flong = Ffraction + Fdrag + Frr BUT REMEBER if you're driving in a stright line then the drag and rolling resitance forces will be in the opposite direction from the traction force. So in terms of magnitude, we have to subtract the resistance force from the traction force. When the vehicle is moving at a constant speed the forces are in equilibrium and Flong is zero. */ sandboxgamemaker-2.7.1+dfsg/src/krsgame/krsrender.cpp0000664000175000017500000000620611411625374022605 0ustar showardshoward#include "krsgame.h" namespace game { VARP(shownames, 0, 1, 1); const char *playermodels(int mdl) { const char *mdls[] = { "rc", "ogre" }; return mdls[mdl]; }; const char *getvehiclemodel(krschar *d) { vehicle *vehiclelookup = vehicles[d->vehicleindex]; if(vehiclelookup) return vehiclelookup->mdl; return NULL; } void renderplayer(krschar *d) { if(d->isinvehicle) { defformatstring(mdl)("vehicles/%s", getvehiclemodel(d)); setbbfrommodel(d, mdl); renderclient(d, mdl, NULL, ANIM_HOLD1|ANIM_LOOP, ANIM_ATTACK1, 0, 0, 0, 1, false); } else renderclient(d, playermodels(d->playerindex), NULL, ANIM_HOLD1|ANIM_LOOP, ANIM_ATTACK1, 0, 0, 0, 1, false); } void rendersmoke(krschar *d) { vec o = d->o; o.z -= d->eyeheight / 2.5f; regular_particle_flame(PART_SMOKE, vec(o.x, o.y, o.z), 6, 2, 0x303020, 1, 4.0f, 100.0f, 2000.0f, -20); } void renderflame(krschar *d) { vec o = d->o; o.z -= d->eyeheight /2.5f; regular_particle_flame(PART_FLAME, vec(o.x, o.y, o.z), 6, 2, 0x903020, 3, 2.0f); } void rendergame(bool mainpass) { startmodelbatches(); if(isthirdperson()) renderplayer(game::player1); entities::renderentities(); endmodelbatches(); if(mainpass) { if(debug) { //draw player vecors if(!editmode && thirdperson) { if(player1->isinvehicle) { vec origin = player1->o; origin.z -= player1->eyeheight / 2.0f; particle_flare(origin, vec(player1->floor).mul(24).add(origin), 1, PART_STREAK, 0x0000FF); particle_flare(origin, vec(player1->yaw * RAD, 0).mul(24).add(origin), 1, PART_STREAK, 0xFF0000); particle_flare(origin, vec(player1->floor).rotate(PI / 2.0f, vec((player1->yaw + 90) * RAD, 0)).mul(24).add(origin), 1, PART_STREAK, 0x00FF00); } } loopv(game::bots) { krsai *d = bots[i]; if(d->isinvehicle) { vec origin = d->o; origin.z -= d->eyeheight / 2.0f; particle_flare(origin, vec(d->floor).mul(24).add(origin), 1, PART_STREAK, 0x0000FF); particle_flare(origin, vec(d->yaw * RAD, 0).mul(24).add(origin), 1, PART_STREAK, 0xFF0000); particle_flare(origin, vec(d->floor).rotate(PI / 2.0f, vec((d->yaw + 90) * RAD, 0)).mul(24).add(origin), 1, PART_STREAK, 0x00FF00); } } ai::renderwaypoints(); } if(shownames) { loopv(game::bots) { krsai *d = bots[i]; if(d->hasname) particle_textcopy(d->abovehead(), d->name, PART_TEXT, 1, 0xFFFFFF, 4); } particle_textcopy(player1->abovehead(), player1->name, PART_TEXT, 1, 0xFFFFFF, 4); } loopv(game::bots) { krsai *d = bots[i]; if(d->isinvehicle && d->onnos && d->move) { vec origin = d->o; origin.z -= d->eyeheight / 4.4f; particle_splash(PART_WATER, 500, 500, origin, 0xC0C0C0, 4.221); } } if(!editmode && player1->isinvehicle && player1->onnos && player1->move) { vec origin = player1->o; origin.z -= player1->eyeheight / 4.4f; particle_splash(PART_WATER, 500, 500, origin, 0xC0C0C0, 4.221); } } } } sandboxgamemaker-2.7.1+dfsg/src/krsgame/krsents.cpp0000664000175000017500000001111211421064622022261 0ustar showardshoward#include "krsgame.h" namespace entities { int lastpickupmillis; vector ents; vector &getents() { return ents; } extentity *newentity() { return new krsentity();} void deleteentity(extentity *e) { delete (krsentity *)e;} void fixentity(entity &e){} const char *entmodel(const entity &e) { const char *mdl[] = { NULL, //NOTUSED - ET_EMPTY = 0 NULL, //LIGHT - ET_LIGHT = 1 NULL, //MAPMODEL - ET_MAPMODEL = 2 NULL, //PLAYERSTART - ET_NULL = 3 NULL, //ENVMAP - ET_ENVMAP = 4 NULL, //PARTICLES - ET_PARTICLES = 5 NULL, //MAPSOUND - ET_SOUND = 6 NULL, //SPOTLIGHT - ET_SPOTLIGHT = 7 NULL, //PLAYERFINISH, = 8 "rpg/objects/coin", //MONEY = 9 "hirato/box/standard",//NOS = 10 NULL, //SPIKESTRIP = 11 NULL, //VEHICLE = 12 NULL //BOT = 13 }; return mdl[e.type]; } void renderent(extentity &e, const char *mdlname, float z, float yaw, int anim = ANIM_MAPMODEL) { if(!mdlname) return; rendermodel(&e.light, mdlname, anim|ANIM_LOOP, vec(e.o).add(vec(0, 0, z)), yaw, 0, MDL_SHADOW|MDL_CULL_VFC|MDL_CULL_DIST|MDL_CULL_OCCLUDED ); } void renderentities() { loopv(ents) { extentity &e = *ents[i]; switch(e.type) { case MONEY: { if(e.spawned) renderent(e, entmodel(e), (float)(1+sin(lastmillis/100.0+e.o.x+e.o.y)/20), lastmillis/10.0f); continue; } case NOS: { if(e.spawned) renderent(e, entmodel(e), 0, e.attr[0], ANIM_IDLE); continue; } case SPIKESTRIP: { renderent(e, entmodel(e), 0, e.attr[0], ANIM_IDLE); continue; } case VEHICLE: { if(e.spawned) { if(game::vehicles.inrange(e.attr[0])) { defformatstring(mdl)("vehicles/%s", game::vehicles[e.attr[0]]->mdl); renderent(e, mdl, 0, 0, ANIM_IDLE); } } continue; } case BOT: { if(e.spawned) { loopv(game::bots) { krsai *bot = game::bots[i]; game::renderplayer(bot); } } } default: continue; } } } void animatemapmodel(const extentity &e, int &anim, int &basetime) { anim = ANIM_MAPMODEL|ANIM_LOOP; } void trypickup(int n, krschar *d) { extentity &e = *ents[n]; switch(e.type) { case PLAYERFINISH: { conoutf("game finished"); playsound(S_GAMEFINISHED); game::spawnplayer(d); break; } case MONEY: { d->money += e.attr[0]; playsound(S_RECICVEMONEY, &ents[n]->o); lastpickupmillis = lastmillis; e.spawned = false; break; } case NOS: { if((!d->hasnos || !d->onnos) && d->isinvehicle) { d->hasnos = true; lastpickupmillis = lastmillis; e.spawned = false; } break; } case SPIKESTRIP: { if(!d->hasflat && d->isinvehicle) { playsound(S_TIREPOP, &ents[n]->o); d->hasflat = true; } break; } case VEHICLE: { if(!d->isinvehicle && game::vehicles.inrange(e.attr[0])) { d->vehiclechanged = true; d->vehicleindex = e.attr[0]; d->isinvehicle = true; e.spawned = false; } break; } } } const char *entname(int i) { static const char *entnames[] = { "none?", "light", "mapmodel", "playerstart", "envmap", "particles", "sound", "spotlight", "playerfinish", "money", "nos", "spikestrip", "vehicle", "bot" }; return i>=0 && size_t(i)o; o.z -= d->eyeheight; loopv(ents) { extentity &e = *ents[i]; if(e.type==NOTUSED) continue; float dist = e.o.dist(o); if(lastmillis > lastpickupmillis + ENTTIME && !e.spawned) e.spawned = true; if((e.spawned || e.type == PLAYERFINISH || e.type == SPIKESTRIP) && dist<=15) trypickup(i, d); } } const int numattrs(int type) { static const int num[] = { 0, //playerfinish 8 1, //money 9 1, //nos 10 1, //spikestrip 11 1, //vehicle 13 1 //bot 14 }; type -= ET_GAMESPECIFIC; return type >= 0 && size_t(type) < sizeof(num)/sizeof(num[0]) ? num[type] : 0; } float dropheight(entity &e) { if(e.type==MAPMODEL) return 0.0f; return 4.0f; } void clearents() { while(ents.length()) deleteentity(ents.pop()); } }; sandboxgamemaker-2.7.1+dfsg/src/rpggame/0000775000175000017500000000000011660234754020073 5ustar showardshowardsandboxgamemaker-2.7.1+dfsg/src/rpggame/rpgconfig.cpp0000664000175000017500000006465511654260372022573 0ustar showardshoward#include "rpggame.h" /* This file is configures the following items * scripts * particle effects * status effect groups * item bases * item uses * recipes * ammotypes * character bases * factions * obstacles * containers * platforms * triggers * mapscripts This file is also used to declare the following items (but disallows subsequent changes) * Global Variables */ namespace game { #define CHECK(x, c, vec, select) \ x *loading ## x = NULL; \ static x *check ## x () \ { \ if(! loading ## x) \ conoutf(CON_ERROR, "ERROR: " #c " not defined or being loaded"); \ return loading ## x; \ } \ ICOMMAND(r_select_ ## c, "se", (const char *ref, uint *contents), \ x *old = loading ## x; \ loading ## x = NULL; \ \ reference *obj = rpgscript::searchstack(ref, false); \ if(obj) \ { \ loading ## x = select; \ if(loading ## x && DEBUG_VCONF) \ conoutf("DEBUG: successfully selected \"" #c "\" from reference %s", ref); \ } \ \ if(!loading ##x) \ { \ int idx = parseint(ref); \ if(vec.inrange(idx)) \ { \ if(DEBUG_VCONF) \ conoutf("DEBUG: successfully selected \"" #c "\" using index %i", idx); \ loading ## x = vec[idx]; \ } \ } \ if(loading ## x) \ execute(contents); \ else \ conoutf(CON_ERROR, "ERROR: unable to select reference %s as type " #c, ref); \ loading ## x = old; \ ) \ ICOMMAND(r_num_ ## c, "", (), \ if(DEBUG_VCONF) \ conoutf("DEBUG: r_num_" #c " requested, returning %i", vec.length()); \ intret(vec.length()); \ ) CHECK(script, script, scripts, NULL) CHECK(effect, effect, effects, NULL) CHECK(statusgroup, status, statuses, obj->getveffect() ? statuses[obj->getveffect()->group] : obj->getaeffect() ? statuses[obj->getaeffect()->group] : NULL ) CHECK(item_base, item, items, obj->getinv() ? items[obj->getinv()->base] : obj->getequip() ? items[obj->getequip()->base] : NULL ) CHECK(recipe, recipe, recipes, NULL) CHECK(ammotype, ammo, ammotypes, NULL) CHECK(char_base, char, chars, obj->getchar()) CHECK(faction, faction, factions, obj->getchar() ? factions[obj->getchar()->faction] : NULL ) CHECK(obstacle_base, obstacle, obstacles, obj->getobstacle()) CHECK(container_base, container, containers, obj->getcontainer()) CHECK(platform_base, platform, platforms, obj->getplatform()) CHECK(trigger_base, trigger, triggers, obj->gettrigger()) CHECK(mapscript, mapscript, mapscripts, NULL) #undef CHECK use *loadinguse = NULL; static use *checkuse(int type) { if(!loadinguse) conoutf(CON_ERROR, "ERROR: use not defined or being loaded"); else if(loadinguse->type < type) conoutf(CON_ERROR, "ERROR: trying to set an unavailable use property"); else return loadinguse; return NULL; } ICOMMAND(r_select_item_use, "se", (const char *ref, uint *contents), use *old = loadinguse; loadinguse = NULL; reference *obj = rpgscript::searchstack(ref, false); if(obj && obj->getequip()) { if(DEBUG_VCONF) conoutf("DEBUG: successfully selected \"use\" from reference %s", ref); loadinguse = items[obj->getequip()->base]->uses[obj->getequip()->use]; } else if(loadingitem_base) { int idx = parseint(ref); if(loadingitem_base->uses.inrange(idx)) { if(DEBUG_VCONF) conoutf("DEBUG: successfully selected \"use\" using index %i", idx); loadinguse = loadingitem_base->uses[idx]; } } if(loadinguse) execute(contents); else conoutf(CON_ERROR, "ERROR: unable to select reference %s as type use", ref); loadinguse = old; ) ICOMMAND(r_num_item_use, "", (), if(loadingitem_base) intret(loadingitem_base->uses.length()); else intret(0); ) /// examples /// NOTE: the following variable names are reserved: i, f, s, x, y, z /// #define START(n, f, a, b) ICOMMAND(r_script ## n, f, a, b) /// #define INIT script *e = checkscript() parent variable must always be named e, e->var is modified (see below for var) /// #define DEBUG "scripts[%i]" /// #define DEBUG_IND scripts.length() - 1 #define INTN(name, var, min, max) \ START(name, "i", (int *i), \ INIT \ if(!e) return; \ e->var = clamp((int) max, (int) min, *i); \ if(e->var != *i) \ conoutf("WARNING: value provided for " DEBUG "->" #var " exceeded limits", DEBUG_IND); \ if(DEBUG_CONF || e->var != *i) \ conoutf(DEBUG "->" #var " = %i (%.8X)", DEBUG_IND, e->var, e->var); \ ) \ START(name ## _get, "", (), \ INIT \ if(!e) return; \ if(DEBUG_VCONF) \ conoutf("DEBUG: request for " #name " on %p, returning %i", e, e->var); \ intret(e->var); \ ) #define INT(var, min, max) INTN(var, var, min, max) #define FLOATN(name, var, min, max) \ START(name, "f", (float *f), \ INIT \ if(!e) return; \ e->var = clamp((float) max, (float) min, *f); \ if(e->var != *f) \ conoutf("WARNING: value provided for " DEBUG "->" #var " exceeded limits", DEBUG_IND); \ if(DEBUG_CONF || e->var != *f) \ conoutf(DEBUG "->" #var " = %g", DEBUG_IND, e->var); \ ) \ START(name ## _get, "", (), \ INIT \ if(!e) return; \ if(DEBUG_VCONF) \ conoutf("DEBUG: request for " #name " on %p, returning %f", e, e->var); \ floatret(e->var); \ ) #define FLOAT(var, min, max) FLOATN(var, var, min, max) #define STRINGN(name, var) \ START(name, "C", (const char *s), \ INIT \ if(!e) return; \ if(e->var) delete[] e->var; \ e->var = newstring(s); \ if(DEBUG_CONF) \ conoutf(CON_DEBUG, DEBUG "->" #var " = %s", DEBUG_IND, e->var); \ ) \ START(name ## _get, "", (), \ INIT \ if(!e) return; \ if(DEBUG_VCONF) \ conoutf("DEBUG: request for " #name " on %p, returning %s", e, e->var); \ result(e->var ? e->var : ""); \ ) #define STRING(var) STRINGN(var, var) #define VECN(name, var, l1, l2, l3, h1, h2, h3) \ START(name, "fff", (float *x, float *y, float *z), \ INIT \ if(!e) return; \ e->var.x = clamp((float)h1, (float)l1, *x); \ e->var.y = clamp((float)h2, (float)l2, *y); \ e->var.z = clamp((float)h3, (float)l3, *z); \ if(e->var.x != *x || e->var.y != *y || e->var.z != *z) \ conoutf("WARNING: value provided for " DEBUG "->" #var " exceeded limits", DEBUG_IND); \ if(DEBUG_CONF || e->var.x != *x || e->var.y != *y || e->var.z != *z) \ conoutf(DEBUG "->" #var " = (%g, %g, %g)", DEBUG_IND, e->var.x, e->var.y, e->var.z); \ ) \ START(name ## _get, "", (), \ INIT \ if(!e) return; \ defformatstring(res)("%g %g %g", e->var.x, e->var.y, e->var.z); \ if(DEBUG_VCONF) \ conoutf("DEBUG: request for " #name " on %p, returning %s", e, res); \ result(res); \ ) #define VEC(var, l1, l2, l3, h1, h2, h3) VECN(var, var, l1, l2, l3, h1, h2, h3) #define BOOLN(name, var) \ START(name, "i", (int *i), \ INIT \ if(!e) return; \ e->var = *i != 0; \ if(DEBUG_CONF) \ conoutf(CON_DEBUG, DEBUG "->" #var " = %i", DEBUG_IND, e->var); \ )\ START(name ## _get, "", (), \ INIT \ if(!e) return; \ if(DEBUG_VCONF) \ conoutf("DEBUG: request for " #name " on %p, returning %i", e, e->var); \ intret(e->var); \ ) #define BOOL(var) BOOLN(var, var) #define STATREQ(var) \ INTN(var ## _strength, var.attrs[STAT_STRENGTH], 1, 100) \ INTN(var ## _endurance, var.attrs[STAT_ENDURANCE], 1, 100) \ INTN(var ## _agility, var.attrs[STAT_AGILITY], 1, 100) \ INTN(var ## _charisma, var.attrs[STAT_CHARISMA], 1, 100) \ INTN(var ## _wisdom, var.attrs[STAT_WISDOM], 1, 100) \ INTN(var ## _intelligence, var.attrs[STAT_INTELLIGENCE], 1, 100) \ INTN(var ## _luck, var.attrs[STAT_LUCK], 1, 100) \ \ INTN(var ## _armour, var.skills[SKILL_ARMOUR], 0, 100) \ INTN(var ## _diplomacy, var.skills[SKILL_DIPLOMACY], 0, 100) \ INTN(var ## _magic, var.skills[SKILL_MAGIC], 0, 100) \ INTN(var ## _marksman, var.skills[SKILL_MARKSMAN], 0, 100) \ INTN(var ## _melee, var.skills[SKILL_MELEE], 0, 100) \ INTN(var ## _stealth, var.skills[SKILL_STEALTH], 0, 100) \ INTN(var ## _craft, var.skills[SKILL_CRAFT], 0, 100) #define STATS(var) \ INTN(var ## _level, var.level, 1, 1000) \ INTN(var ## _experience, var.experience, 0, 0x7FFFFFFF) \ INTN(var ## _points, var.points, 0, 500) \ INTN(var ## _strength, var.baseattrs[STAT_STRENGTH], 1, 100) \ INTN(var ## _endurance, var.baseattrs[STAT_ENDURANCE], 1, 100) \ INTN(var ## _agility, var.baseattrs[STAT_AGILITY], 1, 100) \ INTN(var ## _charisma, var.baseattrs[STAT_CHARISMA], 1, 100) \ INTN(var ## _wisdom, var.baseattrs[STAT_WISDOM], 1, 100) \ INTN(var ## _intelligence, var.baseattrs[STAT_INTELLIGENCE], 1, 100) \ INTN(var ## _luck, var.baseattrs[STAT_LUCK], 1, 100) \ \ INTN(var ## _armour, var.baseskills[SKILL_ARMOUR], 0, 100) \ INTN(var ## _diplomacy, var.baseskills[SKILL_DIPLOMACY], 0, 100) \ INTN(var ## _magic, var.baseskills[SKILL_MAGIC], 0, 100) \ INTN(var ## _marksman, var.baseskills[SKILL_MARKSMAN], 0, 100) \ INTN(var ## _melee, var.baseskills[SKILL_MELEE], 0, 100) \ INTN(var ## _stealth, var.baseskills[SKILL_STEALTH], 0, 100) \ INTN(var ## _craft, var.baseskills[SKILL_CRAFT], 0, 100) \ \ INTN(var ## _fire_thresh, var.bonusthresh[ATTACK_FIRE], -500, 500) \ INTN(var ## _water_thresh, var.bonusthresh[ATTACK_WATER], -500, 500) \ INTN(var ## _air_thresh, var.bonusthresh[ATTACK_AIR], -500, 500) \ INTN(var ## _earth_thresh, var.bonusthresh[ATTACK_EARTH], -500, 500) \ INTN(var ## _magic_thresh, var.bonusthresh[ATTACK_MAGIC], -500, 500) \ INTN(var ## _slash_thresh, var.bonusthresh[ATTACK_SLASH], -500, 500) \ INTN(var ## _blunt_thresh, var.bonusthresh[ATTACK_BLUNT], -500, 500) \ INTN(var ## _pierce_thresh, var.bonusthresh[ATTACK_PIERCE], -500, 500) \ \ INTN(var ## _fire_resist, var.bonusresist[ATTACK_FIRE], -200, 100) \ INTN(var ## _water_resist, var.bonusresist[ATTACK_WATER], -200, 100) \ INTN(var ## _air_resist, var.bonusresist[ATTACK_AIR], -200, 100) \ INTN(var ## _earth_resist, var.bonusresist[ATTACK_EARTH], -200, 100) \ INTN(var ## _magic_resist, var.bonusresist[ATTACK_MAGIC], -200, 100) \ INTN(var ## _slash_resist, var.bonusresist[ATTACK_SLASH], -200, 100) \ INTN(var ## _blunt_resist, var.bonusresist[ATTACK_BLUNT], -200, 100) \ INTN(var ## _pierce_resist, var.bonusresist[ATTACK_PIERCE], -200, 100) \ \ INTN(var ## _maxspeed, var.bonusmovespeed, 0, 100) \ INTN(var ## _jumpvel, var.bonusjumpvel, 0, 100) \ INTN(var ## _maxhealth, var.bonushealth, 0, 100000) \ INTN(var ## _maxmana, var.bonusmana, 0, 100000) \ INTN(var ## _crit, var.bonuscrit, -100, 100) \ FLOATN(var ## _healthregen, var.bonushregen, 0, 1000) \ FLOATN(var ## _manaregen, var.bonusmregen, 0, 1000) \ ICOMMAND(r_script_say, "ss", (char *t, char *s), script *scr = checkscript(); if(!scr) return; scr->dialogue.add(new rpgchat(newstring(t), compilecode(s))); if(DEBUG_CONF) { conoutf(CON_DEBUG, "script[%i]->dialogue[%i]->talk = \"%s\"", scripts.length() - 1, scr->dialogue.length() - 1, t); conoutf(CON_DEBUG, "script[%i]->dialogue[%i]->script = \"%s\"", scripts.length() - 1, scr->dialogue.length() - 1, s); } ) ICOMMAND(r_script_signal, "ss", (const char *sig, const char *code), script *scr = checkscript(); if(!scr) return; signal *listen = scr->listeners.access(sig); if(!listen) { const char *name = newstring(sig); listen = &scr->listeners.access(name, signal()); listen->name = name; if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: scripts[%i], creating signal slot %p (%s)", scripts.find(scr), listen, sig); } else if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: scripts[%i], reusing signal slot %p (%s)", scripts.find(scr), listen, sig); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: scripts[%i] = [\n%s\n]", scripts.find(scr), code); delete[] listen->code; listen->code = compilecode(code); ) ICOMMAND(r_mapscript_signal, "ss", (const char *sig, const char *code), mapscript *scr = checkmapscript(); if(!scr) return; signal *listen = scr->listeners.access(sig); if(!listen) { const char *name = newstring(sig); listen = &scr->listeners.access(name, signal()); listen->name = name; if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: mapscripts[%i], creating signal slot %p (%s)", mapscripts.find(scr), listen, sig); } else if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: mapscripts[%i], reusing signal slot %p (%s)", mapscripts.find(scr), listen, sig); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: mapscripts[%i] = [\n%s\n]", mapscripts.find(scr), code); delete[] listen->code; listen->code = compilecode(code); ) #define START(n, f, a, b) ICOMMAND(r_effect_ ##n, f, a, b) #define INIT effect *e = checkeffect(); #define DEBUG "effect[%i]" #define DEBUG_IND effects.find(e) INT(flags, 0, FX_MAX - 1) INT(decal, -1, DECAL_MAX - 1) STRING(mdl) INT(particle, 0, PART_LENS_FLARE - 1) INT(colour, 0, 0xFFFFFF) INT(fade, 1, 120000) INT(gravity, -10000, 100000) FLOAT(size, 0.01f, 100.0f) INT(lightflags, 0, 7) INT(lightfade, 0, 120000) INT(lightradius, 16, 2048) INT(lightinitradius, 16, 2048) VEC(lightcol, -1, -1, -1, 1, 1, 1) VEC(lightinitcol, -1, -1, -1, 1, 1, 1) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_status_ ##n, f, a, b) #define INIT statusgroup *e = checkstatusgroup(); #define DEBUG "statusgroup[%i]" #define DEBUG_IND statuses.find(e) ICOMMAND(r_status_addgeneric, "iiif", (int *t, int *s, int *d, float *v), statusgroup *e = checkstatusgroup(); if(!e) return; status_generic *g = new status_generic(); e->effects.add(g); g->type = *t; g->duration = *d; g->strength = *s; g->variance = clamp(1.f, 0.f, *v); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: adding generic effect (%i %i %i), to statusgroup %i", *t, *d, *s, DEBUG_IND); ) ICOMMAND(r_status_addpolymorph, "siif", (char *m, int *st, int *d, float *v), statusgroup *e = checkstatusgroup(); if(!e) return; status_polymorph *p = new status_polymorph(); e->effects.add(p); p->type = STATUS_POLYMORPH; p->strength = *st; p->duration = *d; p->mdl = newstring(m); p->variance = clamp(1.f, 0.f, *v); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: adding polymorph effect (%s), to statusgroup %i", m, DEBUG_IND); ) ICOMMAND(r_status_addlight, "fffiif", (float *r, float *g, float *b, int *str, int *d, float *v), statusgroup *e = checkstatusgroup(); if(!e) return; status_light *l = new status_light(); e->effects.add(l); l->type = STATUS_LIGHT; l->colour.x = clamp((float) 1, (float) -1, *r); l->colour.y = clamp((float) 1, (float) -1, *g); l->colour.z = clamp((float) 1, (float) -1, *b); l->strength = clamp((int) 512, (int) 8, *str); l->duration = *d; l->variance = clamp(1.f, 0.f, *v); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: adding light effect (%f %f %f --> %i), to statusgroup %i", l->colour.x, l->colour.y, l->colour.z, l->strength, DEBUG_IND); ) ICOMMAND(r_status_addsignal, "siif", (char *s, int *str, int *d, float *v), INIT if(!e) return; status_signal *sig = new status_signal(); e->effects.add(sig); sig->type = STATUS_SIGNAL; sig->strength = *str; sig->variance = clamp(1.f, 0.f, *v); sig->signal = newstring(s); sig->duration = *d; ) ICOMMAND(r_status_addscript, "siif", (char *s, int *str, int *d, float *v), INIT if(!e) return; status_script *scr = new status_script(); e->effects.add(scr); scr->type = STATUS_SCRIPT; scr->script = newstring(s); scr->strength = *str; scr->duration = *d; scr->variance = clamp(1.f, 0.f, *v); ) ICOMMAND(r_status_get_effect, "i", (int *idx), statusgroup *e = checkstatusgroup(); if(!e && e->effects.inrange(*idx)) return; status *s = e->effects[*idx]; string str; switch(s->type) { case STATUS_LIGHT: { status_light *ls = (status_light *) s; formatstring(str)("%i %i %i %f %f %f %f", STATUS_LIGHT, s->strength, s->duration, s->variance, ls->colour.x, ls->colour.y, ls->colour.z); break; } case STATUS_POLYMORPH: { status_polymorph *ps = (status_polymorph *) s; formatstring(str)("%i %i %i %f \"%s\"", STATUS_POLYMORPH, s->strength, s->duration, s->variance, ps->mdl); break; } case STATUS_SIGNAL: { status_signal *ss = (status_signal *) s; formatstring(str)("%i %i %i %f \"%s\"", s->type, s->strength, s->duration, s->variance, ss->signal); break; } case STATUS_SCRIPT: //return script? default: formatstring(str)("%i %i %i %f", s->type, s->strength, s->duration, s->variance); break; } result(str); ) ICOMMAND(r_status_num_effect, "", (), INIT if(!e) return; intret(e->effects.length()); ) BOOL(friendly) STRING(icon) STRING(name) STRING(description) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_item_ ##n, f, a, b) #define INIT item_base *e = checkitem_base(); #define DEBUG "item_base[%i]" #define DEBUG_IND items.find(e) ICOMMAND(r_item_use_new_consumable, "", (), item_base *e = checkitem_base(); if(!e) return; loadinguse = (e->uses.add(new use(e->script))); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: created new consumable use (%i) for item %i", e->uses.length() - 1, DEBUG_IND); ) ICOMMAND(r_item_use_new_armour, "", (), item_base *e = checkitem_base(); if(!e) return; loadinguse = (e->uses.add(new use_armour(e->script))); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: created new armour use (%i) for item %i", e->uses.length() - 1, DEBUG_IND); ) ICOMMAND(r_item_use_new_weapon, "", (), item_base *e = checkitem_base(); if(!e) return; loadinguse = (e->uses.add(new use_weapon(e->script))); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: created new weapon use (%i) for item %i", e->uses.length() - 1, DEBUG_IND); ) STRING(name) STRING(icon) STRING(description) STRING(mdl) INT(script, 0, 0xFFFF) INT(type, 0, ITEM_MAX - 1) INT(flags, 0, item_base::F_MAX - 1) INT(worth, 0, 0xFFFFFF) FLOAT(weight, 0, 0xFFFF) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_item_use_ ##n, f, a, b) #define INIT CAST *e = (CAST *) checkuse(TYPE); #define DEBUG "item_base[%i]->uses[%i]" #define DEBUG_IND items.find(loadingitem_base), loadingitem_base->uses.find(loadinguse) #define CAST use #define TYPE USE_CONSUME START(type_get, "", (), INIT intret(e ? e->type : -1); ) STRING(name) STRING(description) INT(script, 0, 0xFFFF) INT(cooldown, 0, 0xFFFF) INT(chargeflags, 0, CHARGE_MAX - 1) START(new_status, "iif", (int *st, int *el, float *m), INIT if(!e) return; e->effects.add(new inflict(*st, *el, *m)); ) #undef CAST #undef TYPE #define CAST use_armour #define TYPE USE_ARMOUR STRING(vwepmdl) STRING(hudmdl) INT(idlefx, -1, 0xFFFF) STATREQ(reqs) INT(slots, 0, SLOT_MAX - 1) INT(skill, -1, SKILL_MAX - 1) #undef CAST #undef TYPE #define CAST use_weapon #define TYPE USE_WEAPON INT(range, 0, 1024) INT(angle, 0, 360) INT(lifetime, 0, 0xFFFF) INT(gravity, -1000, 1000) INT(projeffect, -1, 0xFFFF) INT(traileffect, -1, 0xFFFF) INT(deatheffect, -1, 0xFFFF) INT(cost, 0, 0xFFFF) INT(pflags, 0, P_MAX - 1) INT(ammo, -3, 0xFFFF) INT(target, 0, T_MAX - 1) INT(radius, 0, 0xFFFF) INT(kickback, -0xFFFF, 0xFFFF) INT(recoil, -0xFFFF, 0xFFFF) INT(charge, 0, 0xFFFF) FLOAT(basecharge, 0, 100) FLOAT(mincharge, 0, 100) FLOAT(maxcharge, 0, 100) FLOAT(elasticity, 0, 1) FLOAT(speed, 0, 100) #undef CAST #undef TYPE #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_recipe_ ##n, f, a, b) #define INIT recipe *e = checkrecipe(); #define DEBUG "recipe[%i]" #define DEBUG_IND recipes.find(e) ICOMMAND(r_recipe_add_ingredient, "ii", (int *base, int *qty), recipe *e = checkrecipe(); if(!e) return; if(*qty <= 0) {conoutf(CON_ERROR, "ERROR: can't add an ingredient with a quantity of <= 0"); return;} if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: added ingredient %i (%i) to recipe %i (%p)", *base, *qty, DEBUG_IND, e); e->ingredients.add(invstack(*base, *qty)); e->optimise() ) ICOMMAND(r_recipe_add_catalyst, "ii", (int *base, int *qty), recipe *e = checkrecipe(); if(!e) return; if(*qty <= 0) {conoutf(CON_ERROR, "ERROR: can't add an ingredient with a quantity of <= 0"); return;} if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: added catalyst %i (%i) to recipe %i (%p)", *base, *qty, DEBUG_IND, e); e->catalysts.add(invstack(*base, *qty)); e->optimise() ) ICOMMAND(r_recipe_add_product, "ii", (int *base, int *qty), recipe *e = checkrecipe(); if(!e) return; if(*qty <= 0) {conoutf(CON_ERROR, "ERROR: can't add an ingredient with a quantity of <= 0"); return;} if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: added product %i (%i) to recipe %i (%p)", *base, *qty, DEBUG_IND, e); e->products.add(invstack(*base, *qty)); e->optimise() ) ICOMMAND(r_recipe_get_ingredient, "i", (int *idx), recipe *e = checkrecipe(); if(!e || !e->ingredients.inrange(*idx)) { result("-1 0"); return; } defformatstring(str)("%i %i", e->ingredients[*idx].base, e->ingredients[*idx].quantity); result(str); ) ICOMMAND(r_recipe_get_catalyst, "i", (int *idx), recipe *e = checkrecipe(); if(!e || !e->catalysts.inrange(*idx)) { result("-1 0"); return; } defformatstring(str)("%i %i", e->catalysts[*idx].base, e->catalysts[*idx].quantity); result(str); ) ICOMMAND(r_recipe_get_product, "i", (int *idx), recipe *e = checkrecipe(); if(!e || !e->products.inrange(*idx)) { result("-1 0"); return; } defformatstring(str)("%i %i", e->products[*idx].base, e->products[*idx].quantity); result(str); ) ICOMMAND(r_recipe_num_ingredient, "", (), recipe *e = checkrecipe(); if(!e) { intret(0); return; } intret(e->ingredients.length()); ) ICOMMAND(r_recipe_num_catalyst, "", (), recipe *e = checkrecipe(); if(!e) { intret(0); return; } intret(e->catalysts.length()); ) ICOMMAND(r_recipe_num_product, "", (), recipe *e = checkrecipe(); if(!e) { intret(0); return; } intret(e->products.length()); ) INT(flags, 0, recipe::MAX - 1) STATREQ(reqs) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_ammo_ ##n, f, a, b) #define INIT ammotype *e = checkammotype(); #define DEBUG "ammotype[%i]" #define DEBUG_IND ammotypes.find(e) ICOMMAND(r_ammo_add_item, "i", (int *i), INIT if(!e) return; e->items.add(*i); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: Classified item %i as member of ammo %i (%s)", *i, DEBUG_IND, e->name ? e->name : "unnamed"); ) ICOMMAND(r_ammo_num_item, "", (), INIT if(!e) {intret(0); return;} intret(e->items.length()); ) ICOMMAND(r_ammo_get_item, "i", (int *idx), INIT if(!e && !e->items.inrange(*idx)) {intret(-1); return;} intret(e->items[*idx]); ) STRING(name) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_char_ ##n, f, a, b) #define INIT char_base *e = checkchar_base(); #define DEBUG "char_base[%i]" #define DEBUG_IND chars.find(e) //ICOMMAND(r_char_additem, "ii", (int *i, int *q) STRING(name) STRING(mdl) INT(script, 0, 0xFFFF) INT(faction, 0, 0xFFFF) STATS(base) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_faction_ ##n, f, a, b) #define INIT faction *e = checkfaction(); #define DEBUG "faction[%i]" #define DEBUG_IND factions.find(e) ICOMMAND(r_faction_set_relation, "ii", (int *o, int *f), INIT if(!e) return; e->setrelation(*o, *f); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: faction %i's liking of faction %i is now %i", DEBUG_IND, *o, *f); ) ICOMMAND(r_faction_get_relation, "i", (int *o), INIT if (!e) return; intret(e->getrelation(*o)); ) STRING(name) STRING(logo) INT(base, 0, 100) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_obstacle_ ##n, f, a, b) #define INIT obstacle_base *e = checkobstacle_base(); #define DEBUG "obstacle_base[%i]" #define DEBUG_IND obstacles.find(e) STRING(mdl) INT(weight, 0, 0xFFFF) INT(script, 0, 0xFFFF) INT(flags, 0, rpgobstacle::F_MAX - 1) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_container_ ##n, f, a, b) #define INIT container_base *e = checkcontainer_base(); #define DEBUG "container_base[%i]" #define DEBUG_IND containers.find(e) //ICOMMAND(r_container_additem, "ii", (int *i, int *q) STRING(mdl) STRING(name) INT(capacity, 0, 0xFFFF) INT(script, 0, 0xFFFF) INT(lock, 0, 101) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_platform_ ##n, f, a, b) #define INIT platform_base *e = checkplatform_base(); #define DEBUG "platform_base[%i]" #define DEBUG_IND platforms.find(e) STRING(mdl) INT(speed, 1, 1000) INT(flags, 0, rpgplatform::F_MAX - 1) INT(script, 0, 0xFFFF) START(addroute, "ii", (int *from, int *to), INIT vector &detours = e->routes.access(*from, vector()); if(detours.find(*to) == -1) { detours.add(*to); if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: registered detour; " DEBUG "->routes[%i].add(%i)", DEBUG_IND, *from, *to); } else if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: route from %i to %i already registred for " DEBUG, *from, *to, DEBUG_IND); ) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND #define START(n, f, a, b) ICOMMAND(r_trigger_ ##n, f, a, b) #define INIT trigger_base *e = checktrigger_base(); #define DEBUG "trigger_base[%i]" #define DEBUG_IND triggers.find(e) STRING(mdl) STRING(name) INT(flags, 0, rpgtrigger::F_MAX - 1) INT(script, 0, 0xFFFF) #undef START #undef INIT #undef DEBUG #undef DEBUG_IND ICOMMAND(r_global_new, "i", (int *v), if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: created new global variable - variables[%i] = %i", variables.length(), *v); variables.add(*v); intret(variables.length() - 1); ) ICOMMAND(r_tip_new, "s", (const char *s), if(DEBUG_CONF) conoutf(CON_DEBUG, "DEBUG: added tip...\n%s", s); tips.add(newstring(s)); ) } sandboxgamemaker-2.7.1+dfsg/src/rpggame/rpgplatform.cpp0000664000175000017500000000431411637730516023137 0ustar showardshoward#include "rpggame.h" void rpgplatform::update() { resetmdl(); temp.light = vec4(0, 0, 0, 0); temp.alpha = 1; if(!entities::ents.inrange(target) || entities::ents[target]->type != PLATFORMROUTE) { target = -1; float closest; loopv(entities::ents) { extentity &e = *entities::ents[i]; if(e.type == PLATFORMROUTE && routes.access(e.attr[0]) && (target < 0 || e.o.dist(o) < closest)) { target = i; closest = e.o.dist(o); } } } if(flags & F_ACTIVE) { float delta = speed * curtime / 1000.f; while(target >= 0 && delta > 0) { float dist = min(delta, entities::ents[target]->o.dist(o)); if(dist > 0) //avoid divide by 0 for normalisation { delta -= dist; vec move = vec(entities::ents[target]->o).sub(o).normalize().mul(dist); o.add(move); loopv(stack) {stack[i]->o.add(move); stack[i]->resetinterp();} } if(delta <= 0) break; vector &detours = *routes.access(entities::ents[target]->attr[0]); target = -1; //we pick a random one; we test up to n times if we fail to get a destination loopi(detours.length()) { int tag = detours[rnd(detours.length())]; loopvj(entities::ents) { extentity &e = *entities::ents[j]; if(e.type == PLATFORMROUTE && e.attr[0] == tag) { target = j; break; } } if(target >= 0) break; } } } stack.setsize(0); } void rpgplatform::render(bool mainpass) { rendermodel(&light, temp.mdl, ANIM_MAPMODEL|ANIM_LOOP, vec(o).sub(vec(0, 0, eyeheight)), yaw, pitch, 0, MDL_SHADOW|MDL_CULL_DIST|MDL_CULL_OCCLUDED|MDL_LIGHT|MDL_DYNLIGHT, NULL, NULL, 0, 0, temp.alpha); } void rpgplatform::hit(rpgent *attacker, use_weapon *weapon, use_weapon *ammo, float mul, int flags, vec dir) { loopv(weapon->effects) { if(!game::statuses.inrange(weapon->effects[i]->status)) continue; seffects.add(new victimeffect(attacker, weapon->effects[i], weapon->chargeflags, mul)); } if(ammo) loopv(ammo->effects) { if(!game::statuses.inrange(ammo->effects[i]->status)) continue; seffects.add(new victimeffect(attacker, ammo->effects[i], weapon->chargeflags, mul)); } getsignal("hit", false, attacker); } sandboxgamemaker-2.7.1+dfsg/src/rpggame/rpgio.cpp0000664000175000017500000007530111655776732021740 0ustar showardshoward#include "rpggame.h" extern bool reloadtexture(const char *name); //texture.cpp namespace rpgio { #define GAME_VERSION 27 #define GAME_MAGIC "RPGS" /** SAVING STUFF STRINGS - use writestring(stream *, char *) VECTORS - write an int corresponding to the number of elements, then write the elements POINTERS - convert to reference, if this is not possible don't save it VEC - use writevec macro, you need to write all 3 coordinates independantly LOADING STUFF STRINGS - use readstring(stream *) VECTORS - read the next int, and use that as the basis of knowing how many elements to load POINTERS - read the reference and convert it back to a pointer of the intended object. If this can't be done reliably don't save it VEC - use readvec macro, you need to read all 3 coordinates independantly REMINDERS HOW MANY - don't forget to indicate how many times you need to repeat the loop; there should be a amcro that helps with this ORDER - you must read and write items in the same order LITTLE ENDIAN - pullil add getlil for single values and lilswap for arrays and objects are going to be your bestest friends POINTERS - they change each run, remember that, for convention, use -1 for players ARGUMENTS - as a argument to a function, ORDER IS NOT RESPECTED, use with extreme care TIME - the difference of lastmillis is taken and applied on save and load - use countdown timers instead if possible. ORDER they are to coincide with the order of the item structs, and before the map functions, the order in which crap is stored there */ #define readvec(v) \ v.x = f->getlil(); \ v.y = f->getlil(); \ v.z = f->getlil(); \ if(DEBUG_IO) \ conoutf("DEBUG: Read vec (%f, %f, %f) from file", v.x, v.y, v.z); #define writevec(v) \ f->putlil(v.x); \ f->putlil(v.y); \ f->putlil(v.z); \ if(DEBUG_IO) \ conoutf("DEBUG: Wrote vec (%f, %f, %f) to file", v.x, v.y, v.z); struct saveheader { char magic[4]; int sversion; //save int gversion; //game }; bool abort = false; mapinfo *lastmap = NULL; rpgent *entfromnum(int num) { if(num == -2) return NULL; if(num == -1) return game::player1; else if(num >= lastmap->objs.length()) { conoutf("WARNING: invalid entity num (%i), possible corruption", num); return NULL; } return lastmap->objs[num]; } int enttonum(rpgent *ent) { if(ent == NULL) return -2; if(ent == game::player1) return -1; int i = lastmap->objs.find(game::player1); if(i != -1) { int num = lastmap->objs.find(ent); if(num > i) num--; return num; } else return lastmap->objs.find(ent); } struct reference { int ind; mapinfo *map; rpgent *&ref; reference(int i, mapinfo *m, rpgent *&r) : ind(i), map(m), ref(r) {} ~reference() {} }; vector updates; const char *readstring(stream *f) { int len = f->getlil(); char *s = NULL; if(len) { s = new char[len]; f->read(s, len); if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: Read \"%s\" from file (%i)", s, len); } return s; } void writestring(stream *f, const char *s) { int len = s ? strlen(s) + 1 : 0; f->putlil(len); if(!len) return; f->write(s, len); if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: Wrote \"%s\" to file (%i)", s, len); } void readfaction(stream *f, faction *fact) { int num = f->getlil(); loopi(num) { int val = f->getlil(); if(!fact->relations.inrange(num)) fact->relations.add(val); else fact->relations[num] = val; } } void writefaction(stream *f, faction *fact) { f->putlil(fact->relations.length()); loopv(fact->relations) f->putlil(fact->relations[i]); } void readrecipe(stream *f, recipe *rec) { rec->flags |= f->getlil(); } void writerecipe(stream *f, recipe *rec) { f->putlil( rec->flags & recipe::SAVE); } rpgent *readent(stream *f, rpgent *ent = NULL) { int type = f->getlil(); if(ent) type = ent->type(); switch(type) { case ENT_CHAR: { if(!ent) ent = new rpgchar(); rpgchar *loading = (rpgchar *) ent; delete[] loading->name; delete[] loading->mdl; loading->name = readstring(f); loading->mdl = readstring(f); #define x(var, type) loading->base.var = f->getlil(); x(experience, int) x(level, int) x(points, int) loopi(STAT_MAX) x(baseattrs[i], short) loopi(SKILL_MAX) x(baseskills[i], short) loopi(STAT_MAX) x(deltaattrs[i], short) loopi(SKILL_MAX) x(deltaskills[i], short) loopi(ATTACK_MAX) x(bonusthresh[i], short) loopi(ATTACK_MAX) x(bonusresist[i], short) x(bonushealth, int) x(bonusmana, int) x(bonusmovespeed, int) x(bonusjumpvel, int) x(bonuscarry, int) x(bonuscrit, int) x(bonushregen, float) x(bonusmregen, float) loopi(ATTACK_MAX) x(deltathresh[i], short) loopi(ATTACK_MAX) x(deltaresist[i], short) x(deltahealth, int) x(deltamana, int) x(deltamovespeed, int) x(deltajumpvel, int) x(deltacarry, int) x(deltacrit, int) x(deltahregen, float) x(deltamregen, float) #undef x int items = f->getlil(); loopi(items) { int b = f->getlil(); int q = f->getlil(); if(q) loading->modinv(b, q, false); //technically this facilitates dupes, but cleans out empty entries } loading->script = f->getlil(); loading->faction = f->getlil(); int equiplen = f->getlil(); loopi(equiplen) { int base = f->getlil(); int use = f->getlil(); loading->modinv(base, 1, false); loading->equip(base, use); //validate equips } loading->health = f->getlil(); loading->mana = f->getlil(); loading->lastaction = f->getlil() + lastmillis; int num = f->getlil(); loopi(num) loading->route.add(f->getlil()); break; } case ENT_ITEM: { if(!ent) ent = new rpgitem(); rpgitem *loading = (rpgitem *) ent; loading->base = f->getlil(); loading->quantity = f->getlil(); break; } case ENT_OBSTACLE: { if(!ent) ent = new rpgobstacle(); rpgobstacle *loading = (rpgobstacle *) ent; delete loading->mdl; loading->mdl = readstring(f); loading->weight = f->getlil(); loading->script = f->getlil(); loading->flags = f->getlil(); break; } case ENT_CONTAINER: { if(!ent) ent = new rpgcontainer(); rpgcontainer *loading = (rpgcontainer *) ent; delete[] loading->mdl; delete[] loading->name; loading->mdl = readstring(f); loading->name = readstring(f); int items = f->getlil(); loopi(items) { int b = f->getlil(); int q = f->getlil(); if(q) loading->modinv(b, q, false); //technically this facilitates dupes, but cleans out empty entries } loading->capacity = f->getlil(); loading->script = f->getlil(); loading->lock = f->getlil(); break; } case ENT_PLATFORM: { if(!ent) ent = new rpgplatform(); rpgplatform *loading = (rpgplatform *) ent; delete[] loading->mdl; loading->mdl = readstring(f); loading->speed = f->getlil(); loading->script = f->getlil(); loading->flags = f->getlil(); int steps = f->getlil(); loopi(steps) { vector &detours = loading->routes.access(f->getlil(), vector()); int routes = f->getlil(); loopj(routes) detours.add(f->getlil()); } loading->target = f->getlil(); break; } case ENT_TRIGGER: { if(!ent) ent = new rpgtrigger(); rpgtrigger *loading = (rpgtrigger *) ent; delete[] loading->mdl; delete[] loading->name; loading->mdl = readstring(f); loading->name = readstring(f); loading->script = f->getlil(); loading->flags = f->getlil(); loading->lasttrigger = f->getlil(); break; } default: conoutf(CON_ERROR, "ERROR: unknown entity type %i", type); abort = true; return NULL; } int numeffs = f->getlil(); loopi(numeffs) { victimeffect *eff = new victimeffect(); ent->seffects.add(eff); updates.add(reference(f->getlil(), lastmap, eff->owner)); eff->group = f->getlil(); eff->elem = f->getlil(); int numstat = f->getlil(); loopj(numstat) { int type = f->getlil(); status *st = NULL; switch(type) { case STATUS_POLYMORPH: { status_polymorph *poly = new status_polymorph(); st = poly; poly->mdl = readstring(f); break; } case STATUS_LIGHT: { status_light *light = new status_light(); st = light; readvec(light->colour); break; } case STATUS_SCRIPT: { status_script *scr = new status_script(); st = scr; scr->script = readstring(f); break; } case STATUS_SIGNAL: { status_signal *sig = new status_signal(); st = sig; sig->signal = readstring(f); break; } default: st = new status_generic(); break; } st->type = type; st->duration = f->getlil(); st->remain = f->getlil(); st->strength = f->getlil(); st->variance = f->getlil(); eff->effects.add(st); } } ent->eyeheight = f->getlil(); readvec(ent->o); ent->newpos = ent->o; readvec(ent->vel); readvec(ent->falling); ent->yaw = f->getlil(); ent->pitch = f->getlil(); ent->roll = f->getlil(); ent->timeinair = f->getlil(); ent->state = f->getchar(); ent->editstate = f->getchar(); ent->lastjump = f->getlil() + lastmillis; return ent; } void writeent(stream *f, rpgent *d) { f->putlil(d->type()); switch(d->type()) { case ENT_CHAR: { rpgchar *saving = (rpgchar *) d; writestring(f, saving->name); writestring(f, saving->mdl); #define x(var) f->putlil(saving->base.var); x(experience) x(level) x(points) loopi(STAT_MAX) x(baseattrs[i]) loopi(SKILL_MAX) x(baseskills[i]) loopi(STAT_MAX) x(deltaattrs[i]) loopi(SKILL_MAX) x(deltaskills[i]) loopi(ATTACK_MAX) x(bonusthresh[i]) loopi(ATTACK_MAX) x(bonusresist[i]) x(bonushealth) x(bonusmana) x(bonusmovespeed) x(bonusjumpvel) x(bonuscarry) x(bonuscrit) x(bonushregen) x(bonusmregen) loopi(ATTACK_MAX) x(deltathresh[i]) loopi(ATTACK_MAX) x(deltaresist[i]) x(deltahealth) x(deltamana) x(deltamovespeed) x(deltajumpvel) x(deltacarry) x(deltacrit) x(deltahregen) x(deltamregen) #undef x f->putlil(saving->inventory.length()); loopv(saving->inventory) { f->putlil(saving->inventory[i]->base); f->putlil(saving->inventory[i]->quantity); } f->putlil(saving->script); f->putlil(saving->faction); f->putlil(saving->equipped.length()); loopv(saving->equipped) { f->putlil(saving->equipped[i]->base); f->putlil(saving->equipped[i]->use); } f->putlil(saving->health); f->putlil(saving->mana); f->putlil(saving->lastaction - lastmillis); f->putlil(saving->route.length()); loopv(saving->route) f->putlil(saving->route[i]); break; } case ENT_ITEM: { rpgitem *saving = (rpgitem *) d; f->putlil(saving->base); f->putlil(saving->quantity); break; } case ENT_OBSTACLE: { rpgobstacle *saving = (rpgobstacle *) d; writestring(f, saving->mdl); f->putlil(saving->weight); f->putlil(saving->script); f->putlil(saving->flags); break; } case ENT_CONTAINER: { rpgcontainer *saving = (rpgcontainer *) d; writestring(f, saving->mdl); writestring(f, saving->name); f->putlil(saving->inventory.length()); loopv(saving->inventory) { f->putlil(saving->inventory[i]->base); f->putlil(saving->inventory[i]->quantity); } f->putlil(saving->capacity); f->putlil(saving->script); f->putlil(saving->lock); break; } case ENT_PLATFORM: { rpgplatform *saving = (rpgplatform *) d; writestring(f, saving->mdl); f->putlil(saving->speed); f->putlil(saving->script); f->putlil(saving->flags); int num = 0; enumerate(saving->routes, vector, tmp, num++); f->putlil(num); enumeratekt(saving->routes, int, stop, vector, routes, f->putlil(stop); f->putlil(routes.length()); loopvj(routes) f->putlil(routes[j]); ); f->putlil(saving->target); break; } case ENT_TRIGGER: { rpgtrigger *saving = (rpgtrigger *) d; writestring(f, saving->mdl); writestring(f, saving->name); f->putlil(saving->script); f->putlil(saving->flags); f->putlil(saving->lasttrigger); break; } default: conoutf(CON_ERROR, "ERROR: unsupported ent type %i, aborting", d->type()); return; } f->putlil(d->seffects.length()); loopv(d->seffects) { f->putlil(enttonum(d->seffects[i]->owner)); f->putlil(d->seffects[i]->group); f->putlil(d->seffects[i]->elem); f->putlil(d->seffects[i]->effects.length()); loopvj(d->seffects[i]->effects) { status *st = d->seffects[i]->effects[j]; f->putlil(st->type); switch(st->type) { case STATUS_POLYMORPH: { status_polymorph *poly = (status_polymorph *) st; writestring(f, poly->mdl); break; } case STATUS_LIGHT: { status_light *light = (status_light *) st; writevec(light->colour); break; } case STATUS_SCRIPT: { status_script *scr = (status_script *) st; writestring(f, scr->script); break; } case STATUS_SIGNAL: { status_signal *sig = (status_signal *) st; writestring(f, sig->signal); break; } } f->putlil(st->duration); f->putlil(st->remain); f->putlil(st->strength); f->putlil(st->variance); } } f->putlil(d->eyeheight); writevec(d->o); writevec(d->vel); writevec(d->falling); f->putlil(d->yaw); f->putlil(d->pitch); f->putlil(d->roll); f->putlil(d->timeinair); f->putchar(d->state); f->putchar(d->editstate); f->putlil(d->lastjump - lastmillis); } mapinfo *readmap(stream *f) { const char *name = readstring(f); mapinfo *loading = game::accessmap(name); lastmap = loading; loading->name = name; loading->script = f->getlil(); loading->flags = f->getlil(); loading->loaded = f->getchar(); int numobjs = f->getlil(), numactions = f->getlil(), numprojs = f->getlil(), numaeffects = f->getlil(), numblips = f->getlil(); loopi(numobjs) loading->objs.add(readent(f)); loopvrev(updates) { if(updates[i].map == lastmap) updates[i].ref = entfromnum(updates[i].ind); } loopi(numactions) { action *act = NULL; int type = f->getlil(); switch(type) { case ACTION_TELEPORT: { int ent = f->getlil(); if(!entfromnum(ent)) {//how'd that happen? conoutf("WARNING: loaded teleport loadaction for invalid ent? ignoring"); f->getlil(); continue; } act = new action_teleport(entfromnum(ent), f->getlil()); break; } case ACTION_SPAWN: { int tag = f->getlil(), ent = f->getlil(), id = f->getlil(), amount = f->getlil(), qty = f->getlil(); act = new action_spawn(tag, ent, id, amount, qty); break; } case ACTION_SCRIPT: { act = new action_script(readstring(f)); break; } } loading->loadactions.add(act); } loopi(numprojs) { projectile *p = new projectile(); p->owner = (rpgchar *) entfromnum(f->getlil()); if(p->owner->type() != ENT_CHAR) p->owner = NULL; p->item = f->getlil(); p->use = f->getlil(); p->ammo = f->getlil(); p->ause = f->getlil(); readvec(p->o); readvec(p->dir); readvec(p->emitpos); p->lastemit = 0; //should emit immediately p->gravity = f->getlil(); p->deleted = f->getchar(); p->pflags = f->getlil(); p->time = f->getlil(); p->dist = f->getlil(); p->projfx = f->getlil(); p->trailfx = f->getlil(); p->deathfx = f->getlil(); p->radius = f->getlil(); p->elasticity = f->getlil(); p->charge = f->getlil(); p->chargeflags = f->getlil(); loading->projs.add(p); } loopi(numaeffects) { areaeffect *aeff = new areaeffect(); loading->aeffects.add(aeff); readvec(aeff->o); aeff->owner = entfromnum(f->getlil()); aeff->lastemit = 0; //should emit immediately aeff->group = f->getlil(); aeff->elem = f->getlil(); aeff->radius = f->getlil(); aeff->fx = f->getlil(); int numstat = f->getlil(); loopj(numstat) { int type = f->getlil(); status *st = NULL; switch(type) { case STATUS_POLYMORPH: { status_polymorph *poly = new status_polymorph(); st = poly; poly->mdl = readstring(f); break; } case STATUS_LIGHT: { status_light *light = new status_light(); st = light; readvec(light->colour); break; } case STATUS_SCRIPT: { status_script *scr = new status_script(); st = scr; scr->script = readstring(f); break; } case STATUS_SIGNAL: { status_signal *sig = new status_signal(); st = sig; sig->signal = readstring(f); break; } default: st = new status_generic(); break; } st->type = type; st->duration = f->getlil(); st->remain = f->getlil(); st->strength = f->getlil(); st->variance = f->getlil(); aeff->effects.add(st); } } loopi(numblips) { ///FIXME finalize blip structure and write me } lastmap = NULL; return loading; } void writemap(stream *f, mapinfo *saving) { lastmap = saving; writestring(f, saving->name); f->putlil(saving->script); f->putlil(saving->flags); f->putchar(saving->loaded); f->putlil(saving->objs.length()); f->putlil(saving->loadactions.length()); f->putlil(saving->projs.length()); f->putlil(saving->aeffects.length()); f->putlil(saving->blips.length()); loopv(saving->objs) { writeent(f, saving->objs[i]); } loopv(saving->loadactions) { f->putlil(saving->loadactions[i]->type()); switch(saving->loadactions[i]->type()) { case ACTION_TELEPORT: { action_teleport *act = (action_teleport *) saving->loadactions[i]; f->putlil(enttonum(act->ent)); f->putlil(act->dest); break; } case ACTION_SPAWN: { action_spawn *spw = (action_spawn *) saving->loadactions[i]; f->putlil(spw->tag); f->putlil(spw->ent); f->putlil(spw->id); f->putlil(spw->amount); f->putlil(spw->qty); break; } case ACTION_SCRIPT: writestring(f, ((action_script *) saving->loadactions[i])->script); break; } } loopv(saving->projs) { projectile *p = saving->projs[i]; f->putlil(enttonum(p->owner)); f->putlil(p->item); f->putlil(p->use); f->putlil(p->ammo); f->putlil(p->ause); writevec(p->o); writevec(p->dir); writevec(p->emitpos); //f->putlil(p->lastemit); f->putlil(p->gravity); f->putchar(p->deleted); f->putlil(p->pflags); f->putlil(p->time); f->putlil(p->dist); f->putlil(p->projfx); f->putlil(p->trailfx); f->putlil(p->deathfx); f->putlil(p->radius); f->putlil(p->elasticity); f->putlil(p->charge); f->putlil(p->chargeflags); } loopv(saving->aeffects) { areaeffect *aeff = saving->aeffects[i]; f->putlil(enttonum(aeff->owner)); writevec(aeff->o); f->putlil(aeff->group); f->putlil(aeff->elem); f->putlil(aeff->radius); f->putlil(aeff->fx); f->putlil(aeff->effects.length()); loopvj(aeff->effects) { status *st = aeff->effects[i]; f->putlil(st->type); switch(st->type) { case STATUS_POLYMORPH: { status_polymorph *poly = (status_polymorph *) st; writestring(f, poly->mdl); break; } case STATUS_LIGHT: { status_light *light = (status_light *) st; writevec(light->colour); break; } case STATUS_SCRIPT: { status_script *scr = (status_script *) st; writestring(f, scr->script); break; } case STATUS_SIGNAL: { status_signal *sig = (status_signal *) st; writestring(f, sig->signal); break; } } f->putlil(st->duration); f->putlil(st->remain); f->putlil(st->strength); f->putlil(st->variance); } } loopv(saving->blips) { ///FIXME finalize blip structure and write me } lastmap = NULL; } //don't mind the ::blah, just a namespace collision with rpgio:: when we want it from :: void writereferences(stream *f, vector &maps, hashtable &stack) { int num = 0; enumerate(stack, ::reference , saving, num++; if(!saving.ref) saving.type = ::reference::T_INVALID; ); f->putlil(num); enumerate(stack, ::reference, saving, writestring(f, saving.name); char type = saving.type; switch(type) { case ::reference::T_CHAR: case ::reference::T_ITEM: case ::reference::T_OBSTACLE: case ::reference::T_CONTAINER: case ::reference::T_PLATFORM: case ::reference::T_TRIGGER: { int map = -1; int ent = -1; if(saving.ref == game::player1) { map = ent = -1; } else loopvj(maps) { ent = maps[j]->objs.find(saving.ref); if(ent >= 0) {map = j; break;} else ent--; } if(map == -1 && ent == -1 && saving.ref != game::player1) { conoutf(CON_ERROR, "WARNING: char/item/object reference \"%s\" points to non-player entity that does not exist"); f->putchar(::reference::T_INVALID); continue; } if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: writing reference %s as rpgent reference: %i %i", saving.name, map, ent); f->putchar(type); f->putlil(map); f->putlil(ent); break; } case ::reference::T_MAP: { f->putchar(type); int map = maps.find(saving.ref); f->putlil(map); if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: writing reference %s as map reference: %i", saving.name, map); break; } default: conoutf(CON_ERROR, "ERROR: unsupported reference type %i for reference %s, saving as NULL", saving.type, saving.name); case ::reference::T_INV: case ::reference::T_EQUIP: type = ::reference::T_INVALID; case ::reference::T_INVALID: if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: writing null reference %s", saving.name); f->putchar(type); break; } ) } void readreferences(stream *f, vector &maps, hashtable &stack) { static ::reference dummy(""); int num = f->getlil(); loopi(num) { const char *name = readstring(f); ::reference *loading = &stack.access(name, dummy); if(dummy.name != loading->name) delete[] name; else loading->name = name; char type = f->getchar(); switch(type) { case ::reference::T_CHAR: case ::reference::T_ITEM: case ::reference::T_OBSTACLE: case ::reference::T_CONTAINER: case ::reference::T_PLATFORM: case ::reference::T_TRIGGER: { int map = f->getlil(); int ent = f->getlil(); if(map == -1 && ent == -1) { if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: reading player char reference %s", loading->name); loading->setref(game::player1); } else if(maps.inrange(map) && maps[map]->objs.inrange(ent)) { if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: reading valid rpgent reference %s: %i %i", loading->name, map, ent); loading->setref(maps[map]->objs[ent]); } else if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: reading in valid rpgent reference %s: %i %i", loading->name, map, ent); break; } case ::reference::T_MAP: { int map = f->getlil(); if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: reading map reference %s: %i", loading->name, map); if(maps.inrange(map)) loading->setref(maps[map]); break; } case ::reference::T_INV: case ::reference::T_EQUIP: case ::reference::T_INVALID: if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: reading null referene %s", loading->name); loading->setnull(); break; default: conoutf(CON_ERROR, "ERROR: unsupported reference type %i for reference %s, this will cause issues; aborting", type, loading->name); abort = true; return; } } } void readdelayscript(stream *f, vector &maps, delayscript *loading) { readreferences(f, maps, loading->refs); loading->script = readstring(f); loading->remaining = f->getlil(); } void writedelayscript(stream *f, vector &maps, delayscript *saving) { writereferences(f, maps, saving->refs); writestring(f, saving->script); f->putlil(saving->remaining); } void loadgame(const char *name) { defformatstring(file)("data/rpg/saves/%s.sgz", name); stream *f = opengzfile(file, "rb"); if(!f) { conoutf(CON_ERROR, "ERROR: unable to read file: %s", file); return; } saveheader hdr; f->read(&hdr, sizeof(saveheader)); lilswap(&hdr.sversion, 2); if(hdr.sversion != GAME_VERSION || strncmp(hdr.magic, GAME_MAGIC, 4)) { conoutf(CON_ERROR, "ERROR: Unsupported version or corrupt save: %i (%i) - %4.4s (%s)", hdr.sversion, GAME_VERSION, hdr.magic, GAME_MAGIC); delete f; return; } if(DEBUG_IO) conoutf(CON_DEBUG, "DEBUG: supported save: %i %4.4s", hdr.sversion, hdr.magic); const char *data = readstring(f); game::newgame(data, true); delete[] data; abort = false; if(game::compatversion > hdr.gversion) { conoutf(CON_ERROR, "ERROR: saved game is of game version %i, last compatible version is %i; aborting", hdr.gversion, game::compatversion); delete f; localdisconnect(); return; } const char *curmap = readstring(f); if(!curmap) { delete f; conoutf(CON_ERROR, "ERROR: no game/map in progress? aborting"); localdisconnect(); return; } lastmap = game::accessmap(curmap); readent(f, game::player1); int num; #define READ(m, b) \ num = f->getlil(); \ loopi(num) \ { \ if(abort) break; \ if(f->end()) \ { \ conoutf(CON_ERROR, "ERROR: unexpected EoF, aborting"); \ abort = true; break; \ } \ if(DEBUG_IO) \ conoutf(CON_DEBUG, "DEBUG: reading " #m " %i of %i", i + 1, num); \ b; \ } READ(hotkey, int b = f->getlil(); int u = f->getlil(); game::hotkeys.add(equipment(b, u)); ) READ(faction, if(!game::factions.inrange(i)) game::factions.add(new faction()); readfaction(f, game::factions[i]); ); READ(recipe, if(!game::recipes.inrange(i)) game::recipes.add(new recipe()); readrecipe(f, game::recipes[i]); ); READ(variable, if(!game::variables.inrange(i)) game::variables.add(0); game::variables[i] = f->getlil(); ); vector maps; READ(mapinfo, maps.add(readmap(f))); READ(reference stack, if(!rpgscript::stack.inrange(i)) rpgscript::pushstack(); readreferences(f, maps, *rpgscript::stack[i]); ) READ(delayscript stack, rpgscript::delaystack.add(new delayscript()); readdelayscript(f, maps, rpgscript::delaystack[i]); ) #undef READ delete f; updates.shrink(0); if(abort) { conoutf(CON_ERROR, "ERROR: aborted - something went seriously wrong"); localdisconnect(); } game::transfer = true; game::openworld(curmap); delete[] curmap; } COMMAND(loadgame, "s"); void savegame(const char *name) { if(!game::mapdata || !game::curmap) { conoutf(CON_ERROR, "ERROR: No game in progress, can't save"); return; } else if(!game::cansave()) { conoutf("You may not save at this time"); return; } defformatstring(file)("data/rpg/saves/%s.sgz.tmp", name); stream *f = opengzfile(path(file), "wb"); if(!f) { conoutf(CON_ERROR, "ERROR: failed to create savegame"); return; } saveheader hdr; hdr.sversion = GAME_VERSION; hdr.gversion = game::gameversion; memcpy(hdr.magic, GAME_MAGIC, 4); lilswap(&hdr.sversion, 2); f->write(&hdr, sizeof(saveheader)); writestring(f, game::data); writestring(f, game::curmap->name); writeent(f, game::player1); game::curmap->objs.removeobj(game::player1); #define WRITE(m, v, b) \ f->putlil(v.length()); \ loopv(v) \ { \ if(DEBUG_IO) \ conoutf(CON_DEBUG, "DEBUG: Writing " #m " %i of %i", i + 1, v.length()); \ b; \ } WRITE(hotkey, game::hotkeys, f->putlil(game::hotkeys[i].base); f->putlil(game::hotkeys[i].use); ) WRITE(faction, game::factions, writefaction(f, game::factions[i]); ) WRITE(recipe, game::recipes, writerecipe(f, game::recipes[i]); ) WRITE(variable, game::variables, f->putlil(game::variables[i]); ) vector maps; enumerate(*game::mapdata, mapinfo, map, maps.add(&map);); WRITE(map, maps, writemap(f, maps[i])); WRITE(reference stack, rpgscript::stack, writereferences(f, maps, *rpgscript::stack[i]); ) WRITE(delayscript stack, rpgscript::delaystack, writedelayscript(f, maps, rpgscript::delaystack[i]); ) game::curmap->objs.add(game::player1); DELETEP(f); string actual, final; formatstring(actual)("%s", findfile(file, "wb")); copystring(final, actual, strlen(actual) - 3); rename(actual, final); conoutf("Game saved successfully to data/rpg/%s.sgz", name); copystring(file + strlen(file) - 8, ".png", 5); scaledscreenshot(file, 2, 256, 256); copystring(file + strlen(file) - 4, "", 1); reloadtexture(file); } COMMAND(savegame, "s"); }sandboxgamemaker-2.7.1+dfsg/src/rpggame/rpgstats.cpp0000664000175000017500000000677311655776732022476 0ustar showardshoward#include "rpggame.h" void stats::givexp(int xp) { experience = max(0, experience + xp); while(experience >= neededexp(level)) { level++; points += 5; } } int stats::getmaxhp() { int amnt = bonushealth + deltahealth + (getattr(STAT_ENDURANCE) * 4 + getattr(STAT_STRENGTH) * 2) * (25 + level) / 40.0f; return amnt; } float stats::gethpregen() { return bonushregen + deltahregen + getattr(STAT_ENDURANCE) * 0.0025 + getattr(STAT_STRENGTH) * 0.00125; } int stats::getmaxmp() { int amnt = bonusmana + deltamana + (getattr(STAT_INTELLIGENCE) * 2 + getattr(STAT_WISDOM) * 4) * (25 + level) / 40.0f; return max(0, amnt); } float stats::getmpregen() { return bonusmregen + deltamregen + getattr(STAT_WISDOM) * 0.05 + getattr(STAT_INTELLIGENCE) * 0.025; } int stats::getmaxcarry() { int amnt = bonuscarry + deltacarry + getattr(STAT_STRENGTH) * 5; return max(0, amnt); } int stats::getthreshold(int n) { if(n == ATTACK_NONE) return 0; return bonusthresh[n] + deltathresh[n]; } int stats::getresistance(int n) { float amnt = 0; switch(n) { case ATTACK_NONE: return 0; case ATTACK_FIRE: case ATTACK_WATER: amnt += getattr(STAT_AGILITY) / 10.0f; break; case ATTACK_AIR: case ATTACK_EARTH: amnt += getattr(STAT_STRENGTH) / 10.0f; break; case ATTACK_MAGIC: amnt += (getattr(STAT_WISDOM) + getattr(STAT_INTELLIGENCE)) / 20.0f; break; case ATTACK_SLASH: amnt += getattr(STAT_AGILITY) / 20.0f; break; case ATTACK_BLUNT: amnt += getattr(STAT_STRENGTH) / 20.0f; break; case ATTACK_PIERCE: amnt += getattr(STAT_ENDURANCE) / 20.0f; break; } amnt += bonusresist[n] + deltaresist[n] + getattr(STAT_LUCK) / 15.0f; return min(95, amnt); } void stats::skillpotency(int n, float &amnt, float &extra) { amnt = .25; switch(n) { case -1: amnt = 1; extra = rnd(50) / 100.0f; return; //special NO MODIFIERs case case SKILL_ARMOUR: amnt += (getattr(STAT_STRENGTH) + getattr(STAT_ENDURANCE) * 2 + getskill(SKILL_ARMOUR) * 5) / 100.0f; break; case SKILL_DIPLOMACY: amnt += (getattr(STAT_CHARISMA) * 3 + getskill(SKILL_DIPLOMACY) * 5) / 100.0f; break; case SKILL_MAGIC: amnt += (getattr(STAT_WISDOM) * 1.75 + getattr(STAT_INTELLIGENCE) * 1.25 + getskill(SKILL_MAGIC) * 5) / 100.0f; break; case SKILL_MARKSMAN: amnt += (getattr(STAT_STRENGTH) * .5 + getattr(STAT_AGILITY) * 2.5 + getskill(SKILL_MARKSMAN) * 5) / 100.0f; break; case SKILL_MELEE: amnt += (getattr(STAT_AGILITY) * .5 + getattr(STAT_STRENGTH) * 2.5 + getskill(SKILL_MELEE) * 5) / 100.0f; break; case SKILL_STEALTH: amnt += (getattr(STAT_LUCK) * 1 + getattr(STAT_AGILITY) * 2 + getskill(SKILL_STEALTH) * 5) / 100.0f; break; } amnt += logf(1 + (amnt / 5)); extra = amnt * (50 + rnd(101)) / 100.0f; if(rnd(100) < critchance()) extra = extra * (1.10 + (rnd(191) / 100.0f)) + (rnd(150) / 100.0f) * (rnd(150) / 100.0f); extra -= amnt; } void stats::setspeeds(float &maxspeed, float &jumpvel) { float mul = min(1, max(2 - parent->getweight() / getmaxcarry(), 0.01)); maxspeed = (40 + bonusmovespeed + deltamovespeed + getattr(STAT_AGILITY) / 4.f) * mul; jumpvel = (80 + bonusjumpvel + deltajumpvel + getattr(STAT_AGILITY) / 2.f) * mul; } void stats::resetdeltas() { loopi(STAT_MAX) deltaattrs[i] = 0; loopi(SKILL_MAX) deltaskills[i] = 0; loopi(ATTACK_MAX) { deltathresh[i] = 0; deltaresist[i] = 0; } deltahealth = deltamana = deltamovespeed = deltajumpvel = deltacarry = deltacrit = 0; deltahregen = deltamregen = 0; }sandboxgamemaker-2.7.1+dfsg/src/rpggame/rpgstatus.cpp0000664000175000017500000001640111655776732022650 0ustar showardshoward#include "rpggame.h" victimeffect::victimeffect(rpgent *o, inflict *inf, int chargeflags, float mul) : owner(o) { group = inf->status; elem = game::statuses[group]->friendly ? ATTACK_NONE : inf->element; mul *= inf->mul; statusgroup *sg = game::statuses[inf->status]; loopv(sg->effects) { status *st = effects.add(sg->effects[i]->dup()); st->remain = st->duration; if(chargeflags & CHARGE_MAG) st->strength *= mul; if(chargeflags & CHARGE_DURATION) st->remain *= mul; } } bool victimeffect::update(rpgent *victim) { int resist = 0; int thresh = 0; if(victim->type() == ENT_CHAR) { rpgchar *d = (rpgchar *) victim; resist = d->base.getresistance(elem); thresh = d->base.getthreshold(elem); } loopvrev(effects) { effects[i]->update(victim, owner, resist, thresh); if(effects[i]->duration >= 0 && (effects[i]->remain -= curtime) <= 0) { delete effects.remove(i); } } return effects.length(); } bool areaeffect::update() { loopvj(game::curmap->objs) { //checking the head and the feet should be sufficiently accurate for gaming purposes rpgent *victim = game::curmap->objs[j]; if(victim->o.dist(o) <= radius || victim->feetpos().dist(o) <= radius) { int resist = 0; int thresh = 0; if(victim->type() == ENT_CHAR) { rpgchar *d = (rpgchar *) victim; resist = d->base.getresistance(elem); thresh = d->base.getthreshold(elem); } loopvrev(effects) effects[i]->update(victim, owner, resist, thresh); } } loopvrev(effects) { if(effects[i]->duration >= 0 && (effects[i]->remain -= curtime) <= 0) { delete effects.remove(i); } } return effects.length(); } void areaeffect::render() { if(!game::effects.inrange(fx)) return; effect *e = game::effects[fx]; switch(e->particle) { default: if((lastmillis - lastemit) >= emitmillis) { e->drawsphere(o, radius, e->size, effect::DEATH_PROLONG, lastmillis - lastemit); lastemit = lastmillis; } break; case PART_EXPLOSION: case PART_EXPLOSION_BLUE: e->drawsphere(o, radius, e->size, effect::DEATH_PROLONG, 0); break; } } void status_generic::update(rpgent *victim, rpgent *owner, int resist, int thresh, float mul, float extra) { //time based multiplier, dwindles on last 20% of duration int strength = this->strength < 0 ? min(0, this->strength + thresh) : max(0, this->strength - thresh); float mult = (mul + extra * variance) * (100 - resist) / 100.f; if(duration > 0) mult *= clamp(1, 0, 5.f * remain/duration); switch(victim->type()) { case ENT_CHAR: { rpgchar *ent = (rpgchar *) victim; //instant applicable types switch(type) { case STATUS_HEALTH: ent->health += strength * mult * (duration != 0 ? curtime / 1000.f : 1); if(strength < 0 && ent->health < 0) ent->die(owner); return; case STATUS_MANA: ent->mana += strength * mult * (duration != 0 ? curtime / 1000.f : 1); ent->mana = max(ent->mana, 0); return; case STATUS_DOOM: //either instant death, or to cater to duration == -1 a gradual percentage wise drain of health if(duration == 0 || (ent->health -= ent->base.getmaxhp() * strength * mult * curtime / 100000.f) < 0) ent->die(owner); return; } if(duration == 0) break; //the rest switch(type) { case STATUS_MOVE: ent->base.deltamovespeed += strength * mult; ent->base.deltajumpvel += strength * mult; return; case STATUS_CRIT: ent->base.deltacrit += strength * mult; return; case STATUS_HREGEN: ent->base.deltahregen += strength * mult; return; case STATUS_MREGEN: ent->base.deltamregen += strength * mult; return; case STATUS_STRENGTH: case STATUS_ENDURANCE: case STATUS_AGILITY: case STATUS_CHARISMA: case STATUS_WISDOM: case STATUS_INTELLIGENCE: case STATUS_LUCK: ent->base.deltaattrs[type - STATUS_STRENGTH] += strength * mult; return; case STATUS_ARMOUR: case STATUS_DIPLOMANCY: case STATUS_MAGIC: case STATUS_MARKSMAN: case STATUS_MELEE: case STATUS_STEALTH: case STATUS_CRAFT: ent->base.deltaskills[type - STATUS_ARMOUR] += strength * mult; return; case STATUS_FIRE_T: case STATUS_WATER_T: case STATUS_AIR_T: case STATUS_EARTH_T: case STATUS_MAGIC_T: case STATUS_SLASH_T: case STATUS_BLUNT_T: case STATUS_PIERCE_T: ent->base.deltathresh[type - STATUS_FIRE_T] += strength * mult; return; case STATUS_FIRE_R: case STATUS_WATER_R: case STATUS_AIR_R: case STATUS_EARTH_R: case STATUS_MAGIC_R: case STATUS_SLASH_R: case STATUS_BLUNT_R: case STATUS_PIERCE_R: ent->base.deltaresist[type - STATUS_FIRE_R] += strength * mult; return; case STATUS_STUN: ///WRITE ME, immobilise; don't allow movement or attacks with somatic components case STATUS_SILENCE: ///WRITE ME, prevent attacks with a vocal component, special speech path for talking to NPCs too? return; } } case ENT_CONTAINER: { rpgcontainer *ent = (rpgcontainer *) victim; switch(type) { case STATUS_LOCK: if(ent->lock == 101) return; //special case, no unlocking if(-strength * mult > ent->lock) ent->lock = 0; //unlock! else if(strength * mult > ent->lock) ent->lock = min(100, strength * mult); //lock! return; case STATUS_MAGELOCK: //magelock if(!duration != 0) ent->magelock += strength * mult; return; } } } //generic types, note that unhandled types are a) specialise or b) not handled by that entiy switch(type) { case STATUS_DISPEL: ///WRITE ME; select a random status effect every update and weaken it return; case STATUS_REFLECT: ///WRITE ME; what do? return; case STATUS_INVIS: victim->temp.alpha -= strength * mult / 100.f; victim->temp.alpha = clamp(1, 0, victim->temp.alpha); break; } } void status_polymorph::update(rpgent *victim, rpgent *owner, int resist, int thresh, float mul, float extra) { if(duration == 0) return; victim->temp.mdl = mdl; } void status_light::update(rpgent *victim, rpgent *owner, int resist, int thresh, float mul, float extra) { if(duration == 0) return; int strength = this->strength < 0 ? min(0, this->strength + thresh) : max(0, this->strength - thresh); float mult = (mul + extra * variance) * (100 - resist) / 100.f; if(duration > 0) mult *= clamp(1, 0, 5.f * remain/duration); victim->temp.light.add(vec4(colour, strength * mult)); } VAR(eff_strength, 1, -1, -1); VAR(eff_remain, 1, -1, -1); VAR(eff_mult, 1, -1, -1); VAR(eff_duration, 1, -1, -1); void status_signal::update(rpgent *victim, rpgent *owner, int resist, int thresh, float mul, float extra) { eff_strength = strength < 0 ? min(0, strength + thresh) : max(0, strength - thresh); eff_remain = remain; eff_duration = duration; eff_mult = (mul + extra * variance) * (100 - resist) / 100.f; victim->getsignal(signal, true, owner); } void status_script::update(rpgent *victim, rpgent *owner, int resist, int thresh, float mul, float extra) { if(!script) return; if(!code) code = compilecode(script); eff_strength = strength < 0 ? min(0, strength + thresh) : max(0, strength - thresh); eff_remain = remain; eff_duration = duration; eff_mult = (mul + extra * variance) * (100 - resist) / 100.f; rpgscript::doentscript(victim, owner, code); }sandboxgamemaker-2.7.1+dfsg/src/rpggame/rpg.cpp0000664000175000017500000005012611655776732021406 0ustar showardshoward#include "rpggame.h" namespace game { VARP(debug, 0, 0, DEBUG_MAX); rpgchar *player1 = new rpgchar(); // GAME DEFINITIONS vector