sandboxgamemaker-2.8.2+dfsg/0000755000175000017500000000000012363765331014721 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/Platinum Arts Sandbox Forum - Ask Questions Here!.url0000644000175000017500000000013112047201140026225 0ustar bofh80bofh80[InternetShortcut] URL=http://forum.sandboxgamemaker.com/ Modified=804ADB6B0F45CA012F sandboxgamemaker-2.8.2+dfsg/server-init.cfg0000644000175000017500000000345112047201140017632 0ustar bofh80bofh80// optional specific IP for server to use // serverip N.N.N.N // optional specific port for server to use // serverport 28785 // maximum number of allowed clients maxclients 8 // Whether to automatically balance team matches with additional bots if one is missing players. // defauts to on // serverbotbalance 1 // maximum number of bots a master can add - admins are unaffected by this limit // set to 0 to disallow bots serverbotlimit 8 // controls whether or not the server is intended for "public" use // when set to 0, allows "setmaster 1" and locked/private mastermodes (for coop-editing and such) // when set to 1, can only gain master by "auth" or admin, and doesn't allow locked/private mastermodes // when set to 2, allows "setmaster 1" but disallows private mastermode (for public coop-editing) publicserver 0 // description server shows for the server browser serverdesc "2.8 Official Development Server" // password required to connect to the server // generally unnecessary unless you really don't want anyone connecting to your server serverpass "" // password that allows you to gain admin by "setmaster password_here" adminpass "zebra" // controls whether or not the server reports to the masterserver updatemaster 1 // optional message of the day to send to players on connect // servermotd "..." servermotd "Welcome :D" // controls whether admin privs are necessary to record a demo // when 1 requires admin (default) // when 0 only requires master // restrictdemos 1 // maximum number of demos the server will store // maxdemos 5 // maximum size a demo is allowed to grow to in megabytes // maxdemosize 16 // if the flag holder is killed by a team mate // said team mate will be unable to pick up the flag // defaults to on // ctftkpenalty 1 sandboxgamemaker-2.8.2+dfsg/linux/0000755000175000017500000000000012076771532016061 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/linux/sandbox_moviecube.png0000644000175000017500000005131312047201140022243 0ustar bofh80bofh80PNG  IHDR>agAMA asRGB cHRMz&u0`:pQ< pHYsgRbKGDQIDATxw,U]{Wu<}s;A%I$!l0q`m`H` l0Y8,4 09N*O(Ԝknj6ٱb$"Mcmӱk捱 ",w~٫?_-;WE~{}TU ;,׬5ϻ[:1;lnm[cƘkkzƘ5vXhY.k1 Ƙyc\xcZ֘UUNW[!U~YΎsO1/1<~!b"X#&645tcz؞f-Zk%1MX6ƴ1 cLd1X1#-ZPPU>3xj^? Ev}4ʸM?C145FDFLlicfL̹ ֘cͲ1fXW m[*fv1;L }#c1VGDUV 4$3 _?s߻r:OkKx-<#McM5vӚ%c̒ ^,%ӳt1m aXcNpDa!-ϚEbUP/8qνg8 o7O=W9q5bN;8>lrXh!BK[14B*#c9&z"1,%-8ȳ$Mﱳ6[[loo,Mh|s.㛾ů|8>hmǯ5|TDʒ$Ι,M((Z;uBaĔYb?V}Bj5XY M wy)I0   c0 $IBYJe%_h| Yl{n7S=U1:7Hd96SLPck)e^# l!D6B$?#8&cQ Fޓh`09b @(.I$!2,#8=ZC-pIc?~[\_`hcTnK;FR~OI!Zΰfzks E( +8 <#Id4b80  }I)ZN>K9W:jITE!@`kGa?Foy>!@Ys?5MYz  QuGUɲ,jOk5k @,MԺ/_7'ާƙ8x;>a32k^ZbιΒdիΖD^2@?v 4MF!2*'kkPy,P91Bk!L_#zLAQX\YXkc̘-z_{c 5Af^UDiǃͷB]C > Pc+sߕEJ{ %ы*/f8zAl0uX%?c &F&ɬח*+Bd-҈,qd 1SO1iyOf-SropM9 ALFW eEq"~P>!`c Q͛LYwƄ=zN+QbUOd Vn^ FD+605`mW!0pn. F"HA쒉)AE~x-~Wǧukq֥y~G RNH{x\r]5 ?ISEh]B>X-qzǑ6s͈5X#` bLoS~>Bž3a= r{)MA jJgkwk_$P""fYs&ЫI—~-F[o󮈢 Z^J.{Z KKitsQP|% tE)т\ Ɂe358IfO f_0c6{@c> k̰˵+WPc .wIp4cedI|3swjmVBSIb-=-Ym͜ bG%Axe'#Q7ƀT<33ͯ_T ϔ4Mri`Ź<ر´T5Ây1 iYgWyUZDFcb։l4i:$ e9r?︫cyh<c3k\d&૾ϲ<{m5/GUrUvwv0]APzJqU A!ypw/gb+hhhIw 8MxijD/\M5`(u1 RcF+wIठoBy(~@ b@D(IP7?(Y^DPɈLZU/#zy_ЉĉR=.4z)@7t|a㕩: =7ky' bĩ{ "c_1@yLe>/_90Z+Z .ͲM3⾓|]TۄqU4Of@8>G 3SԗеVq1$d")BFw/3\c,#{eGq8:&+/1 0Ƅ],wޱR|]+"hhX7+5-+4` 2 v{lJ|R}C,fn!N.W{X*7 _eFEtj|,!aa04n( M C棟L`[ 8V:k?: ۈ-_V]p*AWȿLgRA <ʟx>&:$e8A&rb:3=NjY R&]oJA>L``ծ1f&ꯈ@ )(cYh4ʥya8\^!g?%HU5./޳©!D7A$ rT ڟV =upbʣ (<91H.m S?rB%^ʕK'dTTk juzSq2߰Lqndc}9>W1,1 Y=E4 ^{> 6&HL$u>Ư5Äꮝ2x` Yf=(sr3P@'>N 1r/M@& C-_-;;;\z]| P ?G&w-'Li"]xd8Qn(/LP^IKg GNsuHg |~6W)ѪG匪~VSе7iN~۞s 航FE1qc B+BzMDn Ԏ U3=n7F٦X V!t|,f]qXPgwN EȪC4f kR戦Jkm7*:·W$IC>J׮W4qܼLp%]o"&"3c"WvY4G(~;d|-d)oecq1< t7AbL/ R?.b=l)ц;642L$*G1'N:*<|N вEyf(yu6&FF8LJ/WD- 4 VQ18cqK&Ē[̳4`3 ?4M'dMh Ol0g9Tp^:-/^eK <6D*sJg,hsjդI=mtSt~. 0@C$a#K7SO>O?}n^wn\GjmB'0%ciDP#zQi l'D9M> #O.Wl6{'5m?ճ>;#?$Γf1d4MAeU>%)tb N|Su 7g~ ypX__#0Y& 7]%*_nO(S߻f9ĒK3ȋK.\ Än [Y'#kƩfs+ݵWIdd-3$SVie? jnid)|0hDxNʉs.fQȳcMvwUDZl?H+7iZ'L# R.W/_!!DM7$4{orhpأUG9;k(!ւal"g bO݆$h"".h7g\ +@\4@E62lny;U4tz-[p_+A _X=nVEL4FR.a@}8[O&k}f?|`@nqj^Ѿ੘sK7J!3e,1 @UƆ![ h+L0d~渙[wcVNbGd-0:H, 4V&VGyG~h͛VU h<44wtZYIզН177iDPI`e6##o q>}Q.p/thoor&h6j%hC<ogQTA,oD6Hd+HtHi<"mkVBjPld1W._mp^T,(ޣJ6Ͽ?kmK _?b!j6@2hL b03(엽Y9@Z jZd 蔔zפ@,oXAgY?%ۚC1"6CfQpϨ,ـ&Fݸ3p'us A2ue7F;佔na89%NHGV Iws?ظ;y}Wzm =_=yjŽ2Ɵ94I !QXWSuR'UD 1v&.S/$.IdN-2h3IL܌9r]d\fiZz!G 46BEbwl8$ddv&bF8ē9&x`6C|Ũb!u(B'y~>u)wm%oϲ쁟ɟzOău_s67۝No ~ƥUׯ]+$IR-CHIp8-D(Ax)̔x%לN&h:saq KFLdcp `P1rotP<>$!6 1.,p n T3;G 6ѹ6!n: dKVkoTA 7yǭai+vu}u'Exzp47|_ͼ]D^isHc8~$pRQ/3 ؟j*Z0Q=q \\D EGF;)bu:2Ȓf1ul%п,u\:`cЃ mNÄ1K =:\9j nO+ !HmP/sK{ DHnGp"tXp}! Lsf]i;RyHUiIF2i*%L\u;ά8skf*fu}2nle'H ;>nчlq1n:.{{2 ,{Y/K18z/z~|;vv* Peqi{Μ=GSqxy8X/.{QLelae+@B*)#2kGAѤA7sEM*5sb9GK 2=QLcN]aqesΔ 2_v5ބC.aNiBDֲĩӧ9q$6X_[֭l$I7牑WDQ]tRrG6"svq΅ Pdf.[XO7ٳa2\XKF&zqHÊ'Jtf0 nwvW_JBEc5@4Kruso"` iw:u ^Oy31:ɟۗ[f{%hBPx#GYY]enW=EK[7qc~aFAc4z8ƍ+WdW^)&yxU󜕕UVX=8A'͛8nݏ׊@2q5Tf̎g݆(6QB8 ca~~1qGTi smsam7rJ)AGSš|J#01"wq7B^{Cd\|2ɧe(J<*ۘ6jw8ѝVwENUN.nF(IE""Ts&Ճ]H"Pbyr1اLKޝdEc/Mi~V Դ QurЛ\*ڤuOo'{+'pAUډ1xt(HGnǠ\lI6fasm`H] zd 9VWW8v(KKt1:x^sEts|wwl^1 娖Ǽgww$I8q F#\#ưJ;ŧP4:]$:=Jp_ hw'9'+c"Y[6r8SD f4\`}:fJmYTɽ31.k-< TS5x)ú lbL/[`%COQjSf\"ҹ6xQcQ"Ӱs(/tXZZ jŎ039G=.Kz-ꖪ bkE2 irӬ9Sg8C{OA^ٟE$=4hQ:틌bT1A޻q(EE5Ř }}8Y9uhDz ߫FB0 _R_p@f"bwHlL"RfAۡכ 1n X.HR_;. P{9zdu;c?ۑ5f(U FL!"1 }y!Nv'NbT,`+^syq|p8>-zAn޸ѣGiZaH1M˽4XU0GRWi(۸ w#ﳴi Azm+:C / .~ (bd$Q41Jʈnv;um8*T}.rصexGc۽xo3MW )JQK&KF(4#/]6gΞe~~~a8XX\Gfscc;(\v+Z-vw8Tp"AwSs >+JYLV9vzҽf pny1%br)zjqK%b$  8&nN!9v+ V=E@:ڠjF!)ZsmDb&{)ߨlj@b ey n#G1q ("F#^ZU .+ZzY/yL?C |"w"8.gbrswG)]s"ۗqǖ WRR ƐbperMNMwnv͍M>{㏣^;ϱ6֖kLgZDCdz&+Ѽsꜿ"[DYS4Z.^ #T3=W\awg'Nh6CA=Nyݝ|KO?͙sh4dHxP:cƃ/& /e+eGPE)v,%_4$@8pqxԔu|B%QCLØbf3Hyףj ~!q\&A4My}/x__cGpaNqj!s*5~AWOW(TpZkh"y'Y^YeqqH*y>{{!n\V:})TըzɱG?м)S+utIgxFYN{R7/x1[A*]~in\Ѩؕ*'/4`)P5*j΅B[j;Nk vmVڗj'װEAy;׾6T%PE+'yatzcK zˤe,"ycyt T}=y> Fz-ԭ)%f[9yxxɧhwyqΜ9a֠$i"Nclr=i jF]+9yW*VM-{SUPjlh4Z"حK ϡ0 eS \Ⴐh8do#GB1w"7]ŋ67H~'p"3#n4 y{\P>(["Uqjt: _b)<< iU?'8v 4bɈ]~g$_%l4I+4%I@lACL_UI r`KyY{\Ai΢TuJuɟ~l-Hjkb$0B1,KFJ( dqi9 G#ki aX 1ŹBш`p8"*$҈K[ޥ^[*WA=(ȳ!pI}AcquF Qqe~o3yn[ Î%CTۥ$KJ0ES8|y﯊JRvn"z+JY;_)oA̚'k 7Zb PR&(>ٵ`cB0Bİ<;oQ<-0(Ν#+$|00r"Z&n}шk|Q5p_h S(wꃩ"Trz=Ξ;&ˡ(I&J)Q9I]F';^0m0!\QWv4%pYV%P[ N:#H9iBxވA}jBTD8]>u!Gcee`8Iכ?0O/Cs-T{GiZ9xћK\*ჺ՗(X;v--C&Fwp̙jn:pT-_.`MU3jK q/cPy 5 @ǮL8Kp#G0֒Fm$\z=D;>!gss<˙D1aea~GףqˈlVkZU[5V8=RDtDqDύ7 ZfR*QB#Hbϒx̓y2(/^GU^ir罿%l(j唪FO3A\[5PH𛓄FzFQa= >lovuYΟ={;mȎPV8n`LIt_ѴOBYxNe676y׮];χ -PgNgU4/*󢕮jbJfTKP TU ?QCY7)iץWGݿzTu c/*!O yRR_iO먜T& F`{{$whD&edvs5^O… cƄVv`eSms '1-c F#ǎ2 y'>ɓ' S^cǎq(G |4e4J 3!Z-f|f6Yh,pܑZsTa`KTJ!( zXjҀ/ɵrkkť^w5hbxr1*Ykɳ~b\HÌ0Bh]/ly٬6 {ƌb.5W_\Zh`mNfyG{”2}Q̋))OS ~݃"B͚"7Z*.py5UgD%PUՒ18Z QC Nn鞼EdQTX h4"R6YV>9q$Ǐc~W){CtPu:QkW*KKa.2Cnj9(IKGԋ3pF$Jcu_ȁ88EPzDQD1pb]}cdEh;2ZˮLx=0{ljZ 5b%2eWѸcSцpOɷp tbU.^r{V1eSh *6(R&z S :cl6/Y{v}5Kįfuwj Pgگ a0\7 .)8P+ܾ,+RH,@xR(-+y,V p+Vu #6޼{.8nr.1SDH3c8u$.bJz|k>ڔ :)3v XW=wՀkce\nFUzbnҮWh}~GN^o[_׿0%|}!Dל_6ǍhznR\h$S/m|&F6jrkczleugj'ˋܾj|Em V.SԈ_7(!caIe(ֶK*&1N7L @,Ȳ|y?c3>}?1Oy:nOt0OCْ(*xcJ*8YRI-ɷY2\PFƫdʠ>TYVU˯ZZ]BUQ R ^o.M-͆f'h8~Fꉯ½#TͤMT]_TIfg2q!Tu./ZtNJ|~XԎ _T੮+8F/YXX,.ufӺGeb?)D1zj &%$IZQ5N;RڈrK[Y+SKEݿw+{UK|{{/__k}lvڝ{q1f,,:@hpЄ;v /SjQ\cȏቂn1]ҞOF cLܽG |4,O;h"9߁_՛ܸW͟h)<4WǍ4H rgA "5aDyѣqFR2lP>L6wL#B;y^I|15FMeoP%}HGDȾO}kG5?fy$;מEXk &( MIdt̶)P8q"E\r29` υ س.t9p8(uɷen9( _?%"+OQ}#HvnqƘs ~V^}k6Ԟ?} vr$p2Q2u8f/!eK8&V;%fL4vUy W~sH5CGQEkͷX}LPYփbV4)'Np"bSUğ$ `{P,B_Uag`]᷀_Dyld >?в'?*-ckEwȹpp:.49|-D[WVW9}LEҵs:H? e8h'ׁL 3|zVjJ Q {__6PU+"_("ߧ_:ArR233iq587~]O*5?>I\h;iƏU9R85aگq{.f'?㡷?U58t]N>ڤki 6ѵ|&ee8Aq"!* GF7~_y?c cN Uk,ODmUYU)_0A,L3LF(;f:Lh*SD v^a >+xK s"|*OUdgP5Ll*[>L=rFHqNefћI@LU{gT;k7dcXDB7Ϩ'T̎8eT0d{6;0y_lk"x+oBoO?n c͈> TtUm=f1EiЛj18gRSZb2ɛ0*?A*ioK|?of{>TOj4A 0hѺƘCx &sz$M_ކ~0 M>-aDӠWϫj UAu`V}8lMO2ä%3a.ݤdO:"< _,"Ɔ|? ?"*g0(FDnZC${ʥGf'~"|m"M? 7D}?oCnLY(Q^zV'\UO={dYZ13efaq &yo"\k|"'P~1}EѸkR 4 PQHg?6s7EE {%"a' "tǿQ}nS.<`j޳n&urS|:gly9`yF9vE""Vmc̦o|2?/rf񧛭V#}(˲ܨ`i?@(H.'"QDg/\COO*-oAzXVn,񚬨w'vk<˪12!u}2N0v k"qnD~ SE"|۷} n>7Q9k_m;gaaxXo/ q:ѨJQa#~""?}6S$EWt:]ZZ)*eh0r5q25"07o*tDv`6"*~ǷG&*'Soi,3q9NWWV_ћ P?\vjB&5{Ѡ# 5UOO9|_F~_ ;9򺅅̓O=ͥK ældg&a݈{8לs&j' qÒN_7뵍,.sM.]}"r]/yyge;֛|*ԏ\of ȳun޼'O;ny FŘ1wi>jw}*OV$?s-uTO4fU *H&£"_E?c>yz >5@/ϑagAMA asRGB cHRMz&u0`:pQ< pHYsgRbKGDSIDATx}eWYާ-3d2IHB1yO =@y((RDE"(0B !ާߙen瞶*{sΝRAd画>{}8=5ERcTP*JX(.QEрlq4Zi: 4K[/}"b7"Ά错aޤ5}J}RZaes=A j Z!, JDŽdZbbAh$fb`'@̸es$sg)GqY,>#wU  0ONxfmAg7[p Q)LpPo &IgdߞP:{fP&kjՍ1S7oNӖ͛}\LgW\fgffS1!PqQ#&6ddZ FPQIt33:1Z[!s qǹCv0 1A[/ݳO~+ެSXŅoqvdSR4R($y@Pv`8ŝQLeRAԮ 38wa3@C(i&2hRVjJK4eOoׁo|ӛRH{icMNzT!\ezण^'0%yEMTy`.en&AqMs ܡQS$֩V%ިSmFkkUZ]]ZY^K?翯 ZQFZmCٹoxUObOWg7SmnnUqFCqy+l<2NyPUmY!0?CeSum dױ~Co=*ޫ6n|:33`'?)İ!Zh*gK}TF Ԕsw'Y&\ 4<3cew΄Rk,FZEjAl#L5[ٲmf;bʵagm=J`*fXIК4NS5-nOxSV7N51&ػ8񄈭ʼn@du7HEyI4z+ UcLPM!HՄ=Xɬ ek*!(vig s7"ھc' >*5ġD?[N{-3C=JAeo_oz헮}"s2W?O?F6'չ#8* i}[ޏo;|OYMN[=&&GFGi|FVLFx#۟>g_'T~>>wO{ 7u |#ۥ1AHj lQRQlӁ563 TjFЬިo. 3f0\ f 0oٺKLhZ#jt˫{>_g%]{fQ6UloRp&խY Fk^zv*:K}풯`30Q6(oaH夓:Jmי*יAJ+4TzT %&s?ff15Ԩ:UF+) 6 SDF;h0J S8fP -[n>v|ֳIsiwR$q D[gWΛ S&(ԨkeCuF%9^>UY4/N'!@ 63LΣA0NG0a&"JuZWlL i, 50joy4+rՁVSh0p l}mFxC5ES̔!6a_V9Zk/25o5nФrRm#hv@J;!r >sLr\?hB P+iљtδi ha74T}qZG18C?֚8j?icbZDPK! vWZeBНj^ x=Iq/7[պ%p3Oy+f!1O*F>)@'ZZl !* 3a3>F(I $xNu~>I8}B|D*mNܕ ŌLͧKp(mx+]m} RU!t&U2O$PZwj6&^Y ?9p%5}eܵv/'3klsQ^g~&ß|r&2ʘ-x!e*/y{9߃7?ydHm<cӶ9F"N`՞>usBluI8H8ӡFQ8 sԨ{m`Gw2 aXYpϞȎI raj^>*,T[T3!ڌk#r/~K ~$Pja~~H"С%Ί 4}B|΁X9#W%ua7Y? PjG:osv_e*;ݑ չn]AHM:bqMI9}(Lqsf2@!\QG7ϩǏ$ǭiӒP2Es d^# <2A(=x ct03)gVP:xR_ma5 A+6_^-^3pI4-b )XiLTP3?wZ@XޝW/I|/*?2IyxfZU}'YAZ,T9ϫ|E"_O!x+NpaCFY{j wٔ|C 粅1 *z =q-->'9Lm 9s1z H>x^ Kxzx^툶'\Dm+VD쨝J V9?{7qz.z>J+w[`!1snrڙ9 N-o ?ыWc{U-[|Brs'//dߩu>;.^9{㠀UH7BY<)T֑-t+i8'I^ub@޸̐u5 ]4O[t`5<JC ,j#ۚ|ܟ>\8~5)qI3>.,ӾD)2WU9$MYWm~֔+ YXVgTm][rqR!E+4B(\z3LKSZ]XVwЉ1U{(:P]y1ngq H2Vx%I'y k\Jbiq^ b_XOn0G#6Xa8sB*xXՓY k ژ%Q,&w~5G*E=`WFhTO$s ښ%@(8r(] oi=!m&ߏ?Q,so?\&4S`?8/?3|G ˛&h݆Y!t@ұ0ѯqcsjQ)KXDz0c- ktŞ*笻*W4^ Q^[>u B ?G4m;[} N\.Jr~ΞoJ3;'4Slh-.M8ە|~PR nBc$kR-̑89[lTw QXMqoKЦtl2=ZujQTRҠ PQ VZZx6gR[>јU4Mӆ p[jZďJx {jn!7hD/½ptI[G'OP)D _};8'OO$kƖ4{ #ӘI7]5}AJ4!CGYAAC(WPf KuK,`멥=F'&!<|vbJ3gzhYQ wA򹀑&- w=Z߰F4YV .AV{JM7 {-?ɠxo&rh?3Y{Stq)8g j'|[ RzTzt9*fpaW)LK,ّ/N.8|:z LZ+s ~CF` mb $tM* %➗d9-ssW.ZXuvC,Q1=t._GQ4G^oXc=qi`@f0oN=R)3 aFǏl*~u7ж]CE#AX Eg(*klO-Vqh}tAe0RoLLv7 4>?3uؼ)>FH#?U< pu Nq>v6-엒v6c;ħw{w?oC4s3z>}w]?*_3Uz;4>/aNE'B{FY߄&֖lg(]J9Iؠ~ rZe v}RY 2+tu/mL'od'}O©1L 5jY+YgQiJ̍:yTWir0 hy cj?Vf帳2CȌLIMi8{N[%/WǺ ^E d&YE EִxRJ2GS *Pn5].ZLྒྷKGw+y M7oRi%`"͝s 684@`cM-Kg{ی@? U/l?vT0X1ZF62y`z>9ZI=C)n6>^Z5zȧ̮ TdۊS MZnKyۻ*Slh/qf~gO4~_PKLfQSKRi3j'M+By1dxaTX~L r2JH؞z3Êv뭒cg4>>l\̍D3{Zi^C#Ab 3'08M_SwAV ѵ12 -henZo6~7|eiKV9gsp 0#6@2?l2T:8v?Pe)`tn]?Ԥ#;ALmi=pZٳh~jfOX03l4 =OAp-)ݷKm9E31ԭDe3ZRUR;;NbX+Ŵ"E;71F9o2xQXof葐Nۓ0,nO qr1DEzL==?MEVoW(ڲ@Qs4n=AۆfGi6 >f+)=&ʤufA-D ji:5D,vC46V+2$t(H4 f/{=*}fdpj[j߫y,C^oBg:ǒ77|g_k4|j^SPep i4<: %7N$$'>?v? #_ hZ~9\BDh 8B8G`D9sEe--Q!wIHl,ŗ-S:E4;d|mDt.f&POE'k]'盶} D Wž0Dy'8_bW+iPb` izQz?fx|GW3yN; QNm`>_\bIB/ "&| ;OKs0MkJtP T֢-Xx,0İ MC0lDZ>;W]=4|?~ ~$Xt(.9ff7سI#8rl60<%hCD "`(xT̾}Ra#E3P%JKe0VFuLڴk,BnwGy{ZJN4*iT:K!\TVsghsKrШs: 8W9|^O)j5ih.NeĤUh;44BwZO)JmFv՟LuHWBߛM˶sv]dLO`_"JBOe ]ӈ ,} ds#;0G*}0 =,8h}Yjrg IW`r/;RvbJo?+$Z…DK @4CDP!,רUip4"M.lZRcC&hÌ8@\dlhT*_QA!\8rhxF{γcnAtbHѹbA$YxhY]v)k_]12r}; RpRp @9?@plp}hu; !<cnSH+1 DUںNk@8{24 Dr ΍JGxgV+4n,hd<2I("{JnZ XHV]g'a[;جxW /K&*\Z"\h^ Xޔ~/oj}U>{+b .:}u lZBk? 0 }tE8;DfaN hf]mbbB\j m077 G^HMp[$!38K _ D2~(U!3Nirf ͯ܄CGve @sk5h նN#!jeo:C[MĽ}0*]ظcRЎY/N;>K|G$Sn\RymA Y ?EUaH w\bHc3@K0v|ONٓXo|VFI} &e/TQ/5: c7QhytVGbUq6C4k*_rB#{X]&̞:4, bn;^ Gq"\s:..aRdgd`e::BX=z8j@Jk4A3EKק{޶kNjhdā[)#&`D6Vhi89vcGLቄƛvbi @@|m"VA0|Sj[Rʺ(m暘R]wb!v7n]v } /k?\x1(yŇ-[ԇ>apXY`  O=}n{zrj9ٺA1vmBP^_0gj:NRMXIO$=~VI xY`}hʶ[J]9$[u͘Nٓ, Ԧw!`#7G2*Zr8TDțv7+JAqjP߻J%blKGdc#0Ur9a_8}@$jQ*F0'Pv޽{|{3 yGSytPYgo(*pƨ`AO$(柚BS6l5#_ccSgwb`DQAf*zȥ~1-6j? B;֒x!60}ôܪ =%u$PE#*GAPcr`X\ա6 љ/gs8_h&SO88y$/Q |P/&]db&i<&FPKڝ΍}{̑''MiOI"!|L^ 4c7&֜}z2\NDz7d }ci M| Xx8p"sE fgzY cS':@{9VZnF&i6=pa!N]͞4 >~e@BD=H1ܲy3A˜nE{ޘZwp.` ?X !2xLD)m8}aDYC݀kNzVKqkrg *ת'igcRQȻ.ERuQW2Ϟy"R H|,>yc~h<=Hyh>Շ 1*wb:pΰ9kљ@ߥ6$R\UTJSRj48.rq\; 3[6QL^ ֍'n6&viSx87kfAUlC9`eg]D{]tVd݅ :# F3j)BťyvC̏=ywwbVYPL6`O![w;zk68uפGh`(vO9Du#|bbmj#(2[B;mW#޽*j M?/`PB܀(sWBk20hcc {p{I ڔ/]|%1o,(zYzڮh* { |Щm; C'歔-{\QEC@`Z-z/?nm w+ZFL}A`~s(_8⻕0eRϖ27Pvc#bmT, }Bt&8Ko,"J=m椻(ʠr-rsœ~eЖY| t/:ti b^x(A_11|Yyͫk+;M" ݉.Ʌy-2BKkS4jёw% Z6␢ hJo?ҭof>'j%2(^2 4'TLqx6057r\/|n& [5+Us,ۘ}R2v*(',R%ZI:\[о~i%6ʨ4MxSm2#`.2"gT.肃Nq ķB=rv܉ڵ6ŋQ{<mZ9[6ԋAY80>Tcj'iYV*,?3>[4l`r9|V\4t/xM6bŁ+=Qcs WXs_ / Ѵ5iVU;[jt"_͝5>nbW_ {WT+{"i62Bp{ pvvY@wI fQy|=9dG0cEJKАM4l#/ m@~B?~SqKK#T8Ow% '0>6p|&p k7pu㷢iOX9eIggk* {'1xf#w߆NB__g"w29ʯb v침|<:x>?5! `g gދP0/7|!RHʗu}H%]^ :)]^A$h%#"#K4fF4" \J $:jM.)ljޱ"Fi qLa=->mXH-*X9Vڏc#O2|9 ߅hj|M6Gjzzv9E;9v9'Q`[s}*7~ Y4Wez>N@G+GJMe&mvchMӮ .C"? ;nIiYGz@OjR"  C(O4yue}+m}a@5ժraM9}~ WGBW0QeZ1۷o= vA툼iJ]oe@Jbq2'}b)s wwy2"g9IR*i #u>ld6n``Tb}~Q_ |'`=w82YߛFysNM%fn!Hȏ7sXeuI'N"= f9'RC[ٿop 6vv>`jm|$el?}8lE0poҡ@iWrVLٖ1B(pXQ Zpyv⚨>,Cq1{‡.XN_җl Xyz+ meCNb R p 5Ȧ"ZJߙ<ǠP 5:}0LKu% x kN8QB>A@qAOOů*s _4H52s1R~uLV+ 2lif8'/~`Jmm=iaky r)Fݹ< 17Pu3=cmEs;Iu0%պ H^g:h 1#&M ",.M F l:x2"OL_0D?6 ej8bQWp0VߧՌOf|/gMQD ѕ:V95N{|Cz LAC` 01 6.HXI7w7Zqdu )\\5#3zl7_ࡕj߶$ѐOAc"pެDv/}#4>HvtcuW/ |j+LʭО<iHA'qgjZۆ*ۧ^L4Dfh#ɏ7q,kckLY䘗Y_R&")V![ ЂDTqs8XEZd-9fFܸ 8g7/\yY׳tI0Rׄ|}uDmv`&crܭ[f؅"(['ljy!7PcکtvVM@hS q5%';VfN1"&؆ hQCW9M&2?[WɳꆑVWMbr ,r1Φp{ioª@N;:ۏ 3CQ9k9Efk{S/Z@k{©vcӭ4R2 ֲE FjVAd`IL/Id2hH"*]mY?OOT0$]93H r|AHz:̾{3fR{ a 0Y,Mo;;)rC/{$/ ꝡT(5w&7Rr!Ki}Iw ʈ^znڋh ղRYt]1yeo@5168+4l4dTp9a@몶k< &9 ~72ި6`PRDiɶB+tl?9 begqbf` K:CRJijr ^.R0r*V{pQ:fpvNy.1go Aa8A\n'QkHeڠMl~,=F BU>Eu,pny6,mBt!\$#q0 \k[tA-mdoWk{ U6QL Sn@0̪h/nI[^w}daE`q66 hi1;l-+YaTuhи-ra F/܊l؆IvVks ٿҶ%t0-FG߭I|+ќ_Qá}6nr%4LR-SVL L2 f*.w0aFBqBqLbo, M]XˮWivn:<>vd78ӨEsNN+S!WR/LjѾ,]&;Pp}Y`@;}cAx~ף"1L`]B~LmΜ`Z|AY`~PMv0$W*^ <M(#N!vw^@xâmO~8# @[&4B~]32&@*zBq #xdN 13"'G%s4Òo!/Ѭݢ]*F:LDVD>d( ŇN;Mr#\Y~wc"!>Oh*/ŚtGY‡m D']L)a)elb;ԭDzWUW]%R'B[W)C\fm#B6m@A63n04ՕU! 0}N|Qw4a6+R[gSզVM@TF4Z=1/RҌ-3&AxG11~ΐQyAeD+IsI&֨(C]ld|T.CGq6݄$ULܬu&9&dY0ȟ8C7~ujTO4/( $7G%kf*"v?OlgΥ!gǎG&NRꉏIlΆB(:M NytрU۳,Id={ϧ+X\=ƹ`@aJFeyrVPA9N}u`n;Z̤8>ikE;$rLTS))(3aJ.%nmcF~6y,`Dy@&ZY=v,ã[}#+IZ!tҬ;r . :$MgO!%\i^|n*AHw. S ˫}?sp:"d`t ,zЎ5ΫCRvNiV"v=5b @ <Q,W<]}~upNpN% &ڗDK S"j;>Hl5éOiʰY9X;  "IC g+jDMlm@ txrg]z7,C>h^ g_{wXifaeP =OÉ$ЯŌB Kgµ"QDz\Bީ:vg  ϑB]I)HuЭ) azM;֏XsT͆Vš];87&:QAŗ5ςs~~ V{.~QW+Dk`|<T\ B_L{89lA|,6 ];L(β15(X܂. [w u 0iNVSm˩caж?+`YI)Fʄ(B}gY#ؾ Et=Y?p7~m|r}P]/s+=MfЦxR&Ӵc(9RgV3ꉴ}~,y{uw%y)4z2ֹ@|V2>C2u+ R94$~g̮ھϗO8^cUQ%^|M_Mnh{oc!!Zo߄M&p[ !\G=1dIYY<y/<d778- JsoZ/6p2ם!:Kp֭[$䢎vm!<PUN4L.IUnqD[&紭?Cqߗl{>cGLw'<J\Ыqңs a72\bi#gmo̬|OT 3Br(4Ein5 \ps4oVT>stnX_<0=oioj_{=i9|Y:a碓2a%m[l͇Yz [& rsbPӴ F6W RQ{||˃1n3pļtUBC`}56j 7rks¥꣨]he7UM J۫Ănܦ z!rQxQ|J_qeeF/zx<&N8b, PWcRyG ں[9E&TUwI嗻@ނJTw&r%=99o7=:@'a~o񇛱|lmyJ/}CPߗeU pӞ͑Z:5مU5ݷHꊭ. @a/_./nyPYa{|v>kċ~z0w=  pm/ KuB!Xp25JR] h='0^hAiyQt=7ӸGq/̃;-Xqԗ_m\oN$0 x8"Xԁ07H?]Gڣ9sWA'PN!!)&Mt-544S/qz>;H3Ԛ7y$0 $ @1Mn*J]=\UzurTRT켫i?>l`ח'~z{#@0=z xlj};ߙN^82 |g>lUtꮹU0Qv96?Ļa㯬. У>=_2& %'J; =r3:vU*ͨsryi_׆NBˇEx|3n_Sh{I;Z!\Hr2j6!UGs]”s]f7=-٢:ȎֱVXgg>CGC=?ed< ς#>G0[;$$ nt:MA+=es2"4cɿOѷC=\?w5\ ~=u:ry5 5nfd^ sBU߱/U<ñSjfiW?xڤ_/v1YJ7ʙ|aI@yfl8g/_y;zrcS QdH-/E;?OuLx.:~k䦊b(3Γ[U|};?#6{p#߈W_iW mگsaaZ5  pWT'o[{@z~} $v~%/CcEs))uu,nzj^ |1^Wwv_@?s8>Oks?P }c0F|K6d{HQ2+3|JdYF\uu,u ^#_WwC=N^0߄ڶ/9dprTrPlzE 'vU >ID$G~^Mh9ccà%T+YYa8)Yh?_8vXO$?OUt2&x^ fC`7cg$qc0IGرcrO"Gz?Hπ?_(Tyk~ szd^1o0v3`~`ΡyN:GT.k5DUxRc.(7 #U0 BS<=x9^sfTG"?pmV$==GIA?Ðȷ/,L"5}1^" QY:nT:Nop3Xj(~ŋxkGA,LIx3ClfF7b.yPYkMoRxݽɶh%tEXtdate:create2011-10-13T18:23:38+08:00.J%tEXtdate:modify2011-10-13T18:23:38+08:00ۆIENDB`sandboxgamemaker-2.8.2+dfsg/linux/sandbox_fps.png0000644000175000017500000005242212047201140021057 0ustar bofh80bofh80PNG  IHDR>agAMA asRGB cHRMz&u0`:pQ< pHYsgRbKGDTIDATx$gy&~U'2XHHIs H8mlcc0NgL8t|d|'$Vgwr\yT_UE0-VwMwuuy'G4rYZYY%""a! z#)(ꏚP3f_D2"Eu),?͒aFgyƓ[;1o+i}q1 ز b7 ځ ={7 >cx' 3Y0Ew2$ d$ Nn:޷ ۗp9=}ϏT^"F) 4`bABHB&"ho _3 {aϓ1P{ {LawwUV2)Cf$}LU5ڻg?}nX U3wZ2;-1fk^w-2*I&` 6M\CP"#pao|,T{*F@` a-Q[މ<9E[0^җE]$fgfB6EjP&dnPD̆LPUmQS$ b Fhzی) Ck9{C_EhjFh6lll={v7YW>g\NQIa>Ӂ03ˎžB؟z3lOF9663Ttf%3dU+DJc boBDўD4 ~K0Lj3RjF Z[[ZZ\ElKKQV|6NwwW|/o~ƥa |)~܅[хji6R&lVoa&0HILX!6:<"B;U!jk4 n**2Aic}D^5Zyϯq|cc* [>S9UV+J| ˯`% 7гX R)&i'jF2adg/à-m8XU#1O ;꽙lF3)4aFkImA#ں:һQ.}/BV dMLQfC3HH9_g&;kF޻07MsO gƽ Oށl( h$%0 ͖R?BIIFh )4n8~ -M<4[^I "lRfuM\KT>;TPu[blD(W7ʸ{ qx:1Mh}ebsH,,VZsB܁Y8-ղ"( 7Ҫ:^WYWؗtZ% F` el8Nd|][ǨWQ}JuDXOއt8P#F7~',;%\%bg M K;{ Cx-I,+ urSq!0ɲ jQ{fz]WتXCP&T4H!pFnu,%#aC)˦f&AZ&0P%F0o_BCMy{TwV!jRCex<3$tI'5,MsH״ >Ԥ,4!,;Ar!|fB#;;I & h#HQ3E׬A4CB#h')01!#P[o:ݣ$a0Mx3{2/ oHSQKO5^3Qȓ$]e 6PF]ʕE^+tS^W(_Fq ѠuQհNAт 5Ԭ,30qQ??5E/z11҈+bU6_1AJ3iɸoǐtYQ&EE0Zr뉻tHp&:)˦gC[i{  xP~i(Wּ2!a4h1lPgd 34,'mL\ܽ3<6OEx+nQPh""1qNLM̴&6(aRض+X7*Y JT/b^>}c>,X2 o{U ~XN@ivLԯu _D{Gɤ$KIT~t7[+[N_u6{l' 8f3pܮC?k6{i?qcG*HVnj Q1F ĉ%ܚ/ٲ~gӹcT&M{[.Z/[u}@Ed~# h"qcxdtcΛ^O.T0iOm~VlLP; B'TiX Lx1,/-R\kv>&ݚxA$oo 0Cdх#"~.&d kì$<"RPϷ{ށw$0s{/+6E -..d&%T=~+AT)_n6֣-bom> YŅBA xts$:LM [-S[ھ'S&\H{d'ϼB-)Ӏ?n 7*z1sVDOJ G|2q H/?bz>Hu8{Fbc!=^3"5 $AS Ww/`rUj.HN"j?J&0c >S1q>v"sd^x=ޓ{fٍ=6] cCRWkaH8t@v$Bx'ޗs~[~ q`up/9R/S'1e~A=UE "FcPWs-B^{vWȔ&bFf!p m 1f%CN"883[6Kx=3'٤6f[ D/֕6洄DPh! W_D}aA?K(ED%NnH+F`#vϦt d!ǔ+xߛq}w\ǗUs$y`J*$ Wwǒ!K=MzBRKh%PNqsmkF/L"@5*()&$Hzu̐$Yf aUpR˪Z D Dm" S5>YçOdE|YP '|Z0 SH!T/KTM W mgٓKӃioaKTL8i^YO}uډE$ D X$7 &rqsط,MDo934rfs_[]Յ)Oi{6=( tUn8%M8oӳR^3)I L p AHZ@w$8AZS1~[[ؿL6K ;&غeT6l3Y;;քN$r-1H8?I$j[m]IIg0 'SR_r uU25Uoh( -`{8 y[;-!_֪l&A|8ܛS\d2)oCDV։Ҩ\.Oԅh: q8/3(|ǪfHg2tLW"K WH<ԫt:Ck#3p؁*-LOaxS|DGu8Ts u_~1 0!b=[߶qeQaUeEUh5HB&]]]T(,O]I m BifMC_ |Tsm?A8ʰt苂4Dld)Z;FD6>g5:mPpBКLpS^A:>Fa ڶ &?IH>sl u}hfTQ v#[\*Wܷ2*- /Kx \ݗbsAMxUf<s\_R,HHTT#ԭ$zO f*^j2^ 4B4}dTYoΔ.5TIKuFO3j<ܣ~QB G5,%0DDaK}t ``7d^Ǫ}~ׁo6ݟA3Av,?8fbۤ:J4$ 4$ 3i뽰 y%aV Įg+jThR {R !{#4yBw /WB˗rћb7V {\o)ҵwFC8u07#,(Sw>t8*CQ0Qac~l56n[Y򹽉K/l~vV; Lu֤hmW-OiDY_gG4mYݾVzc"AٺR*w wH R721ǤO;{CQ2uH6~H'mT]6~uU: 3W̸n\pмiL㸿꿔uSd"a cL: jbV*+ l7+ ,- uPgؚ_;{^xv8Grk@ nc83 k~E hgų~IYh㎒ dlj֍uQmRurW,inC>=ɲfHt$5f= ~tDl#wRuoؠuj].D\̮y-:E9C6&! 7_PL˖-%>Ea)ZͷD8W[= G[=~]ɰ,e>|gginn֤tC7 R/T Vyןҩ/Wf텀scUpo=lx9^xGh%tD/7;)irIB* =ًk}젩2ޠhbؖ,cp%p'5M\gn9IC{izLӻJ45YXusO"TJ-C)b+0U]Ԑ aHI琏`O/:0@$_z?KmEDHĭWB@kr duoF7#{y/MgF)3ӧWƔ&H`}$yaãW:\'6@IO,QⅪ)x+±,Yi` %ZZ+T;sD1Q~_V5hdӇtKy9c1r .=Z;PaN^z&hGGtV+YǏQ=._}uH=/^Tm"'t,Brrz۩ o_|v=AQiV(*x,(A2rTՠ".\g=#hqUkڜޝq=mk?t;(O)@CBh#횧t|8C&NB:p>s{^?Z1QISOP}݇9s-ܦ?M|[fRT[Po(оӶS0w穧Gc=i y@VocMНHTtFoC23+tajNuҹv@7q92ԄKR9Z9q۔ ɩ@S'zzzTQN,H)4Z j7OR^e rC%=0 )&nWkvrHva݃5\hĹ,@:-Tս3._0N[ܬI6PЉ{2٤ދ2 Ey;k:MU橾e*+k}. Tj41&*dY?5}st([Iyra'`zܢFӛg3Èc #c7ɋ"i^B;u@Rk<'(6Z!?s42 H7Kk<ԓο(g&ct(_ʹL, GZ[gm;?+.4!6ŒJT rM̬K<)ïGqY 2Y̯lBʸ+~Nx+9TVMTYB#ϯמos&&ξIMFa_ FbB H?!Ӟ~=gv:: jQ'l;Jp;fZE$r<+ OK!h Pcn|EV<* ;d|A3juWI5aTr $Yvjn2 aJ.c޳-+"nD<=q)32 z瑡 %;P}#}'/X;g?np7q ׍9l ͆9NQ0g.秬K][zZm=N{.龛Դ=g;xz&ÆOLE!Yz 2[oc[AṴgb T=vܻY~ M1iyyrXR<00xLF$b<>W`맵¾,m TjolÐgg?D#C}@Kp&ڀ /-9T)-)hƧfSNT*ϗو Ovg>*u^Cm DzR'rcX*vD!~Veuxh3nP|-AEf'|:LS"VRL>Al{y@3e` \53U^s?h54v/DSVDI+-xLl^\t%1$Y#ZtĒ19GMB_i GwB%T\+@zNE;]zbxNafz+݈DfhǾeZWQ %G]@aUA%q6-QTI ;d|3оŤDOX&(1qYFU}PP@ _褾&x 1 4qREhijݏtӝ[k[ԟF7-cY \K]wB-Ynx\9wɋG?/;{B{c;C ML&ݲJm.I !׳fV眂3(gBJ' !:9"n_"ARVe{p,KYKV6j ًP0?Dee֖qvL~S짨\09EHT6EzO،fgDf#2-$CjOaOeO6ܸ|xO%-vHz+~[n+Ď{ۑ/ЖPF'wf=ӄ80UYIRu3ULþ)? mչ7- TRG*'tYխWa5_gV:)"jP(?>I9.ސjPABtj^2)旮&r {mNV`Fqڬ tvKjg7+[?=>88!W!2xu=&T:q8@GU"iVB G͚3v.L9T-ʋa3one.*WZ뤞 |@4 ~7֐i(iǪ;lb  d4c8"A:jA> ŴWCA٦ Mt2oRapPCqQ^`;0G7 P@GX8߬B|\ Q=}ߝ8>~ :sv'& IYo/`lYj#\|,5=צARNŠsK7C͈@EHDGnU;;P9#i'!> +fhc 2/{ BjaH?Jp=nXw]mJ1\4NQw9O0pQ#1xZV5_zf2]}ퟻrv_筷T{WVx*-[.dDl >٧@iurPNסPtnbʒ*9! L(⪞_z/ 1Stzr4VK!su8$^MbLJv҃4q.em XS:o bh2X|98V_W 0ů@Ak&*~ډ1.ӿ{><2J;wR8`Ez~{G%70{r߾r||L|שO!ܥ#f\(~imЎ-z|+j xF<#tm]d%0?LNvR*I~?kũe#tHE«n1?Y="&IC@rv]Kx#" 2M>ykB-YAtW)C4v۷2˔.UgZ'NLfm*װ3'q.u`'pY j=|Ch-̀ͦ QJ:;Ǩ&ԁz u-A W8=[I 3qAOM&ŻvxQuDD@`i{'qQCeP zDo:l;z*07,6 ?Oiy*rhMFycccceTB=_p Eh1|ǎ+ =X^Y:bcUQ l|`;p*eb[v"~FBgпWԏ>Us?c&Dhx8E跞ymm|Ѩk= Ȩ뜴G֫ӪxީsA oX Q[K5 u "ۭz5-х`fnU\Y]gtر9x\I-{?|0-46>aϒV 8LХm\ O)hWż#&0u1+`e0?.:ʙ #:k%^H @EˑcҨ 9 /:(y)Zr9 7vA)?!2/G3%`*܂Zpҭ3}KcϺQ;ZDrN;;$hḥ,<,J!sRh|iN;MuWWV6@ yB1B^ O/ HRj{9{jk=R摇sp1J50JݽjX|Dv:>65q[h<)&& g%LpnY :\ోPWVEddS]v}K㸸 E>'^ oawCH5~f!g\tX 䕜 r7_P;'؊L?p ["c}Fȣ=.c$J$_;|V }U{Z]:ٮ2Ʈ>psuW0 S;evm-+6OXǩ笚&06%0 =@ţ:f=a. ^ @>t} HDГ H܄\dՒtcl+԰4¦0OEL [@|ȑiFjiYqv *ߩA^T^*-8v|j(Ʃ0H.[%L3-9,j( wI!pӳ)'y6+yJ@l%4fvsW6\FI-Bdz_뵌'P`"-A$ ɵGF7ဍ"[ 42dΦKnhwC6T GXқ.jN\.N3q񸅘]9>V$FFL0GWzJiOPQ[@pFjަ}ꕕ ߽G\n߱CF@u 0)2jxc<!t9I)rlkj(@: CFGRfĿSal8\Jp-hN[sΡǵ$juI]AԕN껖<i&@D)ИSsduI 3-ߤ;&|/뺈jŬJe JFsy?TA%`l&tջzpcL`'y 1fB\2|Kɂp B*d5&It&4gQT{+fcy]!T^uEKFPor/x];i6%*!a* 튪Ժtoҩ?1ЅcNU@K$ƭ# s/b`Hqlo=‹/ U*[o. ,C6fmǑiF8Ɇ%:Œ/H] 6%ᅾT9BfM|49 vXeFAڊ;T'/rm;ZFFTT(-ƿE$mbN{đpk.le=o nC !,W⭵mbF0υ[08|!J,0xKbq8,e.Ձ̍A <91֓>Icc0њ&a)'dj].h̾V( T0reC?a.0F<̚Y.X,Y0A3t& o=}öjlj/"zl4#b'eY8f#b"m8h2-b?k{ 3(KRHiIq<#h3*̕g'g>'X#u]pCopMߢTVptQQ0 5Z,L 1juBe鄑@vnU73V`g-^14M$w4n; 6Lf3Z,=Mm XUÉXLZJb?8pхH󝳱q8^5d&9MܠhnL|@D)H-k8LDRu֊h9'4z}{/㝿Ϲ&']E!Oi E0!4@gSfRg[M5"ǰ)L&矯n[1*dkN)ke@sDg ެi֖0:ϕ~VDxVL9Rƒi3DBʭT^pX[ ,& ;) s82nn>S]=NZ-iG(w P N8yƑ6 D Gz\P5LL 8Sh.+J 0ķ׾%hע&Cߪ C9>/~83B$MRΪry PjKTZI,&/$kG 7VX8 ޯ`{?PKx;/ ni |h&n^:M7_IYx WqŦrّ]U6)ѐp\H1hTJO:AryDjĿDy^ZeFYuh_Ŭ r7a&HG~X>CvCb8Ig03ik >+!-_rg_n=N '^B A P1& F);dl5gpvuMOJvUַ G0IH[z B9%=6dRX;Jp}w"$-sh>q n=hK͢1A5SI&Yj#i3Ppv$mЮqU \ GF@29Ib]GFqVzp%~H3a D%/iRw5dV؂ۙ$Ej̬$5}sқ%OmE. +U WASb҃ݵֱW$Ek mi&d\KWz&Sl`w^-KCs?_)?88PdWۉF K9:͵A+^wܛc"o:i ߅1fbھdPKM2dz2?Ɇ"zSRz?x3T*/8|m"gǣYnO{q2FT\eۛ9pmu)J:~| 0@2*H g dZ봹8'bg9ʾ pѻ|ŽFQ+s &8bѱc͊QZ 5^}^[I/($Hkq^3D=cq?OPon#bGЮrfJHjj!o ҮV{s+הb݆oX#zCky=XLJy b"o~'yj^#Jd)밥ٸRVJ Y6#O;JnEZpZ׾Ud=c}Ճ/wߛXMf/è=z =&HmRs6h>:/79ϋZГIL gxO&Z-D\_K_ PdkX:-%al#˗\ G5ċ/3q-7t*x=讞s8L~D̴S!$s<`@ hJU$hsDʟ a88r;eY Zz=y|c8`7fO$ TLn+n2)O oxMyv/wCS!/g?Flo1[:5(1pU LRLmjR&_vH~S܉q/CFPyFTի )9 kN"pIj/Eb;|+{8\~Xpl@$eHn_o{z9\u ǰ0#p'O;̋Ds;L(<-o~#?SB>O+䧡3XWIN3gpFD{_ .8 dȴ(j7x*]?O'AVƤ͌Z|&a`KV(h-%+>}3refO >DMw!jh"=:55V ]SC|џ-JKke>S>7à7b::U+0L|^*#ѭ#j{]^{^-+z#KJEU?O/ }'ưl=dۿ_yv}!{@wǨn;^sGu0{5<fa33j *%b2rQx`C?QO_G뢫i`á+)iE\o(;~GTAg~|ӟEE0V5{ccX#pľ 8\jDMw?T T" XkX*5awh7IAy%tEXtdate:create2011-10-13T18:23:37+08:00\^%tEXtdate:modify2011-10-13T18:23:37+08:00-IENDB`sandboxgamemaker-2.8.2+dfsg/linux/Sandbox_FPS.desktop0000644000175000017500000000027512047201140021543 0ustar bofh80bofh80[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.8.2+dfsg/linux/sandbox_SSP.desktop0000644000175000017500000000030112047201140021606 0ustar bofh80bofh80[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.8.2+dfsg/linux/Sandbox_FPS_server.desktop0000644000175000017500000000037412047201140023131 0ustar bofh80bofh80[Desktop Entry] Comment=Dedicated server for the First Person Shooter GenericName=Sandbox FPS server Name=Sandbox FPS server Icon=sandbox_fps Exec=sandbox -gfps --server Type=Application Categories=Applications;Game; StartupNotify=false Terminal=true sandboxgamemaker-2.8.2+dfsg/linux/sandbox_rpg.png0000644000175000017500000005233312047201140021060 0ustar bofh80bofh80PNG  IHDR>agAMA asRGB cHRMz&u0`:pQ< pHYsgRbKGDSIDATx}%gY)^w&4R@z@AAEE"(( ($lؾ޽{;s '=my)=ZST.iai9 B( Rel0z[ A}Rʁ$I8x_q2(/N$R6~:I= /cfќƱg\a' 7L2-., P+ ,% vu7 b>|և 5]xN[Apܐ Ah"kH̃n>fƱWw.bn3 *L$ -db}jb}H7=3 ( ~}*}#3۰_O>V 3Uڿ~xopu5 ),D]&f&dЫ1  QȂ%XS[1d /LPB̦?O709bP7-ߪƶo ڶu)O&]z%bff:Ąq:! zH'Yl>+©ڠR^k%x NOL5+<4OeBCHfI/P7Vްw/~ _'Lj& L$fIZkUZ^YE_yZXXHoK7_2@]N*V+ʓqC] CZN:(*36VaF E6v#"$WϭdFC#&Cuו6YA:v|mmVWWiueVVV-ʲ~joh*977JVYlxܬ_GW}w,IHRnDlodFFSL4mK%ih?ȿ H}[a+2jh2KYVp= _$w_Wױ:ALEFߠ{cJc~kf&¹uxt􎹩):53`+y^ z)gC0㤶ͼf~v~oZNwKTۚ/\*nΙ05UI+fҺ3'/ֱ1T`8m9?d~_,dx> W__sG>ફO%ܻPC|. MKy*B=`)AXxL<AXZkqDOPMhרZMKfm]f31yߎ,M-RSggyI==&joT$n_O$Ig8ݝ|_ydO|8e\ a1u BF!9UZ@K"7y>fbݝvSM %0#]mvV?#5 (G`B=ڠhA:6Dpb03X_mٴ#gDF:n/yp-Gxލs1~-//}5O2UR? #2\Nac/ľn!z(5e 1B#<Ү Hc* %uRXA&<^3J@5K]TXmPiJ5Vs*$gNA9#QxDq?Uk6bQ{{Qyo#XZZRτM U&0T"Kz^~2uuu`Vy FaC) GmF;$-N+|̉ fb}4T{煾6wVJR,c ^[ AFm Jxgvڪ]q|m5S\ img75Iּ:T>\p|?ᇕ28 ~E|F@_^\|ڹQketK^)tb0jm*nl09B .~|غf` &#YGϨ}_;&DIT ׭ᰈ4JL^綴0Ou茧_D#]~U yR[FP|Z ?tm CŴH%mZMWx(]\Xo|3L*~ofz=x0Bװr?߾ 'o9& ӱЖBv|0Oxieegrd;Yu:&mx}5IPw/b)~4r*?hgmC8~\I.X+L?yÙ<2Iθ|CMBq?0D <1^v]qE9P 7B}K<&@%}$KAYu_ȨC%0Oӧ. Χ9uq~*vD;B!PMg$L0*;k\׭^{ոY,|7ݜP2|Fl:0ImY*򶾅Vh%|ACg"Hsb Zve|֠E`regϡb͎Pecg3DŽ2 '"Cd!49 G|؉ EoF'?^ SD7L``<~nV`ob|aUe)uBW-k '`]R$PH7į&/>tځ5 In3Z;?&PPo0ӝiIOxé_I6p1Н8vT'bL(ibKpY\_͉FhSP`E_,wf QdZ%6x"#A|3i60mL01ԃJ؁<*?U-1:Cq]S]]S?pZ"+^rg]7֗y 3aY硋c&wyF#u"u:"i8zN޶/g4jrnحhCP([4;;;l=}/ ןwLPQt_Fq;_r \vS|QL@uշ*wtPT*拶PdT`B(AwX-W1UCy3A9i+>G8C./ )41#u+4QVI"t"IW*T(yaH:l\K{f_zL.b|l!݊_Ig3"ws]ԻטI"g3ϫ1Tyij3>!T"*By),,5j iY< ?1][O1/ 5Nl6;{:On2SLL4*Ts=d C|iPIv Q ;171%hJS4$r\Xx2#< 2jVf_6P@>7Oi*v6&ݍZC64_:v^vaU 15 =8`W>'P* m],-jkJAEN˶>/D"տ$}m[yWW7L;zd3r>Ckcj-c6 h{2HiZ_CS `F Z,ߧW馩E+oѹ:8Ho=?w<&)r'wvQo㘟{?fN-Q߳պE]M1iC3VԵ63]h$s8WQ,L 7^#ƗeT*M%=B ΋FēdBOG p~z!^RO*zx48>; (^L0R+:ml[(i=ujRa`ffJ<7I <bZ` 7iP4c fȕ.Si=\BlxbMAj4ұ@ʐn]rg]ƽ}th'Vis8O۷wFΖiZVLhuo_O|`7.+zL]Q*GUmyF+33A |ktm!I܁b_ү/ZrCҤAdz+0SBHc&=Kwad*5➠a@U᱗!{z-]P/=w˓sOxG=η|=ctH7\j\FimnRG'5K(9M_]Ts96L>P>sW(dkc TYY"=RL9~\kD_څW /r-Լo:vǦ* ӧH,dVuAW2}\v#B# 3Xh B:qajFNGR_*}v2~4&KpK!{]R\ItryEsi @-PsK"η Dرh$Ee*|`ˏ(-Z8.W;| y0UdtwhWӗE 6 (*DcWKM{ҟ}y  wzQ絶q;भ5("7X[{6ѳv%# rko g|:D*A0lrꁓ(gsAX@"j.9Sy3k>u4Qޮ3X~vfp3zf@VlȫZڱ)I :s`#fnI(V"HR?_B}}ʷ _FT&䪂l8CM' l nXWiF'5: '{D8MmYsީO7pj=N]EHW=ii^k{յbyHUN Y2Ӕ-ΐP HQN2@G]#MIootZOTBRߡ]j8ȌBd"2 s@*˘Ğ]b6̌\σJWiNQ$6Τ>)}fáYz٣:i-f2O߱^mfQ/LX+0M`9 k4pwQU{¢Pի DLN cSGT4hEcٽB75@a9 =aNrc;}e>gջ?p˷M3v* 29 ޵O}_ T+6ܞLӷ&TiA*tNѭt)x𢡄fxbACd{u(!G#IqygSyXyT)S:WWL 'es=rD(bg{hlKLa`%x{+ߧK%:#A"0FE@39|=svÄu`)1[ o'axqIvhf@epI6l ~궫X߅}f9Ԛl9[VD_=L?+k0 Z8[gsl8N_@ !w}7uJBȃÿtraG?Glkx t={d&nfO\]yqJ*D*o&,rb4(A5,E|l3UȾuiM2rs9w @7"T̲[;m53ٕd * '}DstbJýeD,4_S3Ѝ+"1FlXDIAv(~"#?⎯t"}L^ ىj'ɟ,ٜQ[Sa(r A0q) C$Uhr>/*v͏ef2UgKι )/LaI”wL0Zܠ/DfoG:yg׿ ҀG|Mf" sVnتH-Sty{^nBP]cM 0Gla ˡCs g&lʗLsfiisL҈cx6\ƭAxvT>8vP#P~u}Y++l@58 R1~EV!=r}Y8oAqlly*+^>҉)%:g IcAl]Ui_Amd?;ר!" +tbBرk|,[k4X 뀈7@r[n%v rI7` jHŠJ)z:wL0$HeE]H<`1VN5sN=e@߁C?BJz u{iw-7[B|]CWG5Hs C+ǻi[Fi2H;7#6U4zblIZ_W1[ص}p|^#@/[oEEQIeuSE3 tzWCmVkϨ!jfj%VtMlf:=xN34DgmWl IDy0ň^|>:i/MͲMsH'<8|6zٻpOF w\ qePX=HgUӋyfqfR##m[G3iHdI,W}Cfs_FM={]cK^t U.t(3u23P8wcy n5zԄ]J7"}f3 =ƪ~[42P(;jkGhuEydNV\YmBu|.ܰ R#["\4^x`${LWLF5/  L3y]\i$N,fBt*`k ^Av< f89_=iCT+~/leمJ¸JCPlj'T^NkkLDjƳ %e G;ϾaB"0~ =t#m@7| ɠ{Ǩ?KM*ifIivwqK^){ wЭ̖e jUEm4Zm ( Kh Dk.0Wk%Пk 4;)y=tF\U ?ap-khx #z(pZ(tNƊ"㥛_,$]1U uUa|l4Put2UWf{S? Ŝ |3gYS[^XSt&@ ka P_. E0+-ń:%QON̜Y-!a)tˮB VDS@/ 46W#t qOF\|BcW 馛ՠeŭaK`&[t?6_,6*}ocv0}0?1}iA䌾0acLgs Mt`'y<"q;ԔU711c%: tA0@W\b9Yu>[[K߰syEgMõu*507EdQ M4Bk&^J :prL9@Q o9΀OLfSSQxZR RYQ֣dC`i|aEfz̽v353fDj{ <KйaΝCaBU o81 ++D nڎȃB*gE)g҃ZvigyhZ\;yՠic$ULpn땺6.8rMP9e=<_{/׿N{.=iOM2q-ҫ3V+Zםd7NxkMiB J )sU:aUK .TQs<8BȃX9lrb\Y7qt vS**>H]t& A( {3Uk=fN0-ˊ 6:&zC bJ݂݅?\Vf)gq z뭪Ş8}8 Cb_&o,3NuZ Q%DKG6]4B%ǹʎ/= 3(:-#=Az)GpNM230)DɁjࢋRfjbK86;yt+V,C%,%#4-kVK ɔ$TT%?!ĜԹ#9vcs]9q*Rϒ~ϱo#nZR2o=lBLC+,IKf{Z&nk*4nތL/w&AiRRjk(&\qxnN 'Vy˘Lw 027C]'*I_,V/(om %`hV]p!4= nW'? ~$ݎ3̠"c!,,5uZ|m5 7$Mz*oF=U4ؘaewډ$fl*fanHW?h_'՚XR[3b<&^e9$RQA'\RD͂U_M:k4ZA?Hc2unpn}Q hTdlC# Q ̪#ifK|Ҍ~@ܱbߥ 9T|?8=y&ȍ¡UU9XSu֑f_Ї zƳE3˖3ј9]譬 ٦7]/U}܎F "xdFr:xLGt}2t5) %>CRiiN0F낆.e2pY&_!5&ֶ)#H9Β(%W47dRuk(ږwꁕfe,(-_GU"58©;m"p, =UR;N_zpl ?AڿYh詬0UJu]lbħog]h \Jr1WM'S&) ;' 4sLt S kLFԴp3jv#eC|{(m|jJL_4S5#[LH@8/:mzG)aTi00Ϋ$^ELlH-F}aվBd nK,* şjY4æ uSReYU>!#z.ΖّD*dc\.U9#pp 怙Vi=)d©5WP r`JxLŞ ^ld=.VLzOrՎį)G_.|^8 w[iecb nn%Y t]_?de6e l~5N^oBnӮF McB:MdA"W%g.!56s7LP qt$ՅadDCR2I()g~pBjϞ dud.^vF̒57لrnE;OH<.G|09ۊZlؖ$[Q*7Z뱲 ҹcQZWTjq2uw|yn؁T=^S?Cl/r˾jRbkԜIe,^_PK:J7`+N߰pX;JDB:I0+;@&-C-9nkF:e_ٮљ82 Ąud*;tX:hLR-|:\^]Eda^ JF4$=~:4DUvvѶװUOi} aLj0 *ec]Ү9\T%S7r\ޑK 8O/ke ȋJ3kHɝWzh`)U]EEOpfyv'7UhlRJ6$>L5+3agQ+);K4_w(?^:/e$_EF3xHC&3qs/QހeOD!Qfl ߞ#ϠK8YA$i _p% @܌ V,A*Jԍt)P?$ىIRex1IKU*X!f>YpIJԎHLFP؅+J,{erZ&i=aʲy~3T*4y 7:9vx7w VLcB::|Ɍv7KJn _vM8%&W0voA=mKu<v FS oQ)h$SCդ^Bϭ`z,+E$ƛAZ- b$ӢӧyWݯY0L&OkbͣG]wщk K[[<ߧ"4I.mSI&"QEF^E7g`UF.Y )JWN{eA - ӂ &.kaҔ Ք@9nHzlmušrISВK8m?_'?K'qq $+uHxonI<מsr3`6gX'>IC,3k۲vϴ9"+X7 ~(K^QY6|MXl)hf %auHIfTy3*Uݗ7 X#2eQA46bQމZe8-~(҆Юu;s^`bfW% W$C}u#g-=oG|K;6GMRot;.4ӗQ^O:tԌLWH5 k9\簽w\Mo> 7z7#ܱ|5?+4}z'!d:&6Uj_8 `kؖY7eSèB34ZxfaI[.ĿNbI/>cփw ݻt{0rwl%YmCJF>g>@w=|` ~E>cJ]*_k {Fʨ6cpN2Z*{W3MEJC?(5 ([>CwvMb5r/-Zhmɷ"Z:4%* '7?•;:=Yϼ=a.zJގ&-ln@~?˯7`g33ԪO 'N=NG,FkGW+/f(JA,[3#s/wKOw:K}Oܧp3F߻ ˑ*VE[o:;B5u_* 4 dUqvjTڴ')J_dh$_(M g|?zvض}!~VY*( x'<3nm~4)2. `\w 4{&."j>7XM$DAp.>HkѯIڰ+ӯdJe>Yh~3Fo߾=행¬l1!#'Leog¿G}]]}Ym~`Ͽp n%-$Vsl|q2j׷i\6!/@:A/EP=qv\įWtLj&&G~WX& 0B-Ej݌dŒ&t3^{~K_LC<?z/?y^_6, )sNb8>226`I>2S5 *py뙛NCdz jr/{ =\@O$܁fMuz>ăXLч9êi>+qJ*#`'PR$'bDWO觠[_PqŚDկYAxXuKŸouΆ^~Ғnp+~389F| .&aW~?y?3Zk Ÿ+zBW-WZ5p#~iM.?a9͗cx`O^*A|Tv&IRB_U e gR5b ɩ-W2{0:N3<՚~񵯦x8~} H:4UFJ^) *'enٹ:Cb[; ` -;l7Ϭl)x~ȹ ףh%^"S2w855mzZW0O/x&C{qćd~~~>ٟb00csIōlUd*SyZ*8m,C9#wƯ/C<NA q?{+{D3T >7UukIkpڣwm5;ơK7uy>r-,nu~v*Jx7_pZ"D;Rvb-`.47WC xJ} oDēipy{?^7c+qkt;f? HL cq~ D'06}ҏ` ?>*^"wKuR:0yE:y@uHOy[?"/.ʝG#]8+I,L)~ľD<cp蓷Dt_~#T(c`djm%KhEW ?I?T G40غxݘA4ÖAN=r%tEXtdate:create2011-10-13T18:23:38+08:00.J%tEXtdate:modify2011-10-13T18:23:38+08:00ۆIENDB`sandboxgamemaker-2.8.2+dfsg/linux/sandbox_krs.png0000644000175000017500000005121512047201140021065 0ustar bofh80bofh80PNG  IHDR>agAMA asRGB cHRMz&u0`:pQ< pHYsgRbKGDQIDATx$Wy.zNUĞvfs^XA!bc^s6u6Gxs6 8\06 ` $!ŕ6<ө}Ω:U3+W?8Z}P-j~n>㸨.aa[ataa֪7(z4T^~bցcqM` 6l`ZM໣\n'mwܩl!Babvy=xދa}O@A)cC~S Q+fޏ㨊 8ViK^?ٷ{ o>w 7\CBhl!A@8HgXaHXb 1{vv< U>y pk0E5Vp_#P 'WW}]}4zd*/҉Dq,YB@]bBXC.o :O)3pk޶>};6marK/ՓaV+"UԭQ%&ZF5g_j+VvܔV+N:xl g ^`0ldr2DLFSp/ݳ 9=W]yj [@ lv ѶbKKoPtbs-yWV:p*7^$@a>!7ס68ZʕZ^^Q jnnNbQQR͖j|P(<*5q:=1Ph-<7eqsmJ Bhps 3|;4;Ν#pe3Rz̐u)jT@Z]]/--E!" 2VWVplYU“9\^]P{G{mfj 7Zpf|*ܤx.TXZ8 G={Tmf>3߳DzT{͐̈N*`PIɬH3& .$ z$zsą"ZB`Bk՚ի^z D#d UnOZ$.\ 72O(V~t8:V. 1S@^i4n8[6"M:mJ5ķ@q́8QA܎]ǚ @BGpro:Ó%a4Bb¦jU pLTUqy*K׸չQVj j,6ߎ}jQh&0C& 7'xj˸E o>P5՝y qfb{Go跦N|{z07' MĿ.^|!# PHADm↌<X@ɱ ?x8 OcO;0DWMh\mWTRCz8bNkНd_UE#TsE57b" Q#3oDg&ԧ>O ۔B* cjU78yYϫ}5T??5&yb;77 -={}aשm_`֎@mխ6U# zh۪x!hH{Z+!nsu)54R@BAMnY+D :`K܃-t&.Rq:Oc K =|ek{u>|˥ G^ЧZۜ]zIVNflչ֞d̐w2̄~lON53Q-x:Zf?}%sxB7dqahLE"f8wi" O}[Mtϛy/W]%Z-EnZnE-_2.Se#𵂭5NkYs(Dž L`)H`bwȢ7`{Kx~#>2y³֏#xxS|i4zȟn8I.T/{A)%~k٘##:%@%u}3C5G[3h qmxb 0b{%\O, CFDBuJIUv߬ʯ!S0#ʾhNS$չ^INp}f͔ھKjp`$J: ND[<}>hgsL5|X9fh #`HfH4",ދO|EO@BjPA`g/_xi5O}u|.DWjĉ6;ôN W&5~̖X,Z${N]YK~[gpqƛ܅k'{Τ>OEIN=aeDkճ AqwLMNx;!suAOl2{NW\QR=(uK`+n@|y9œ3j1TtxwC07~:e6=TW_AG;&uR.%b4ejLMg&TV+ߜ$[x'KRH{I_e@noE9uy[YU)TK4yE*6z߁˄At =ɛD&fF^g>tjM]_v9{\w 8f=I S鏍RHe_r*/.W[+[H!vqxysENdh:= ɞjAg@ڍ{71x;tYԿ#s1-s;yD0;3-_{f˶}iv*/+uukS{jmk-Q)@M:OT5P7~e\|:,`V# l쿏/q: 4e"iB#c"$쌴So.Oe<'(` 8Id3 ?V,=6l ʣ8~Q|>pW&6K>T3TJ˪\g R5)t?zB=82@Ї{ B|]{GD/y-Ρ\h 0ou"%[-[jFz}&14$ZGڔ[?O͈ S hH4~0je)2ڡN9t WenhU#]j KVKs-\_/ux q=ҝw ؖ3*蹛P̷%=BdA}==pjϞ2{+#s<',ͬY]龱J"9&r X L\(XPJRV ;M=E#TCEaMI!&O@lE-óxorSnu;БZp?>o]}|  c: B>ÃLΏmŖM%i+7Ttb5zF< D_oք!ҖX$P.e8rk aZ@Zg jǶnݻ(qHj<_~DM4C}dcH"@#KR3h~&,}B|w;M2oa"uhmyJ)G`_#I|A3ߦ& xz85޻<]ܸM˪D"8!Wafi(BFG }Pb/j~&f5vfިݻ>RB\kn3`酤josoRS+XGO}oTC3j|2GaeJ%0++`R7ۦٹ0?`8⇮Տ 0@(4?r1~qŽ@gfG|eN^Q72]\YCЇNOj|r1Jqؕf,_YxИ19E6̫)0V5͞Z*܃ZdpIVCEQgQ2" xSSo\_Wr"^^/8oR TK…V-ڠ9FQ8-.,⒯%|xASEf Y{(:'E3kwAxQ={"kT#k~ee~tUih3iU/$),-`ujmso.$!7]:yXM)wzdG~Uuz%8}]LCp[ F N0q"·mG[[UkIK"YHKo=VYײ\ZC+utmc\+ smGզ6h"?`&VS Sƹ]ГfntF$+A=NNN#MF<Ḹž 3LӒ-%f*C¤?Pn,!,Q`= !{jtsB%ckza3榎)bc'թ35mK0ԅYG2_;`6 YShR0)@X^<m$b \RG+U wŤQlPߊ:_qׅ 60d3ꋷW̌z`*¤AF!ګ~  /~Luܐ82PD!7~ @NO! HGdiwӰT>sZ"xPwsiIu+UIɔUfn VdT` d U',m=3(H?C !bf/ZQYĒȪ# <}*橎qbb3f~z8ܳs3EXz$y$i(;wAv !g&9,Ҍߚ@enA"5dC(rV{AZc{ GϠ—RL¥=ڛ֒3Ė>-vV":b#(-ͼrn8 R] fEIG-FEUDm𼥕`E_[)=3ɟm ܴvjf. ɷnU^UfCzTι-m`M0+me54}vhE6u.a]mR.~8 ]jphJԓLe[kTh{l fqϤ {%=| >mM\_]ԳsL~R'| 2y>$T3%S[Y\čo]_TMs9SͲgb@V3l,H/b]XhH灣;zxFVf!I3  ݏ]O!6T ߬٠t}T$.$dpIu9W{97DU6nRUlim! ot^,楴J5kjS/w`vI 3ԦkFT{K-BXʓj^hi$QUdQX_abFU1KKp[Չ0ɝƽ"9jk>! mCsv&8ט Hܒd !!tYF7$,c*\(_W:6~&@rʍ-" J)}&wnS~!KK ꋷ<)}QTq*,΋#FF{wVUәEQ|Fs0 ]:rR./u섓g)s`aHj0K[k'Jĺ|&S'ŭ[;z]x/y񍏎o~S01}Ѷ'z4m۬$Y)D/!nf̜,-p$y%U|UKk D?h.z^+YꋕjΓfRHV nyA[oYV5<-(|2cK&ȭ;66oczbT?УR[6v*'NpQi:X@Q ^Tje(u]<2wVU;ykU8.U=xc*U1V*2@ۍge6IK"[!ݪa&驲a PKAudvܪu9*ܪz*oѡ_on~9S[n=^tnKWdK'gU3 f3>,CM{Ȉ;6n(CǦcNze}Ȫ" ѯ͘&_xp\d,QLt~arn+;`,W7 ʆ oľh+}3Y.>jƥ/(JzM*o#ʫiřrFUʛ#@jr/`VW:8zFv-C HNNYՄ!/D@ I851WAk5 LtV>>5:cr ^zêC+UTBPYDK &ҁࡁn!Y62H 9OO.K_ vv1Fx} 1^k]ׯİ3՟pm֍UgtdZe-&Uy3Bm\z2q0=M}1޻ ^?tWRkV؆IqHxRmɡ8zҕFni5=pz hVE eq*PPbBҧ50] VФyfd[ sfE JbͽQW xSKS-0=+5TeuI $30r)Տi&}%QzAkf!i#$%ܚD U.C0_Cxk fÆ ).m n}Zԅ^o޼ICO:5"Lvt^N"3Z?7\ZBB7K!w2{-ΔT-Qm푘 +ludV$nI3=}wpZ@/3*YXÇSlS=o@͍"LkE.;Gb[|n5aD!\eEGg+ =ZUVLU@\Ha-]I%Y1SffV%eG5 ),v#XEM&[:]#p5`zuu ƺ[[Pp=B@@M5˕p9L#[GNr/-׉ :zUu(RIRv.Uc=w7aÇ!K/"p:yrV^, {UW4\<8F6 CBT&`D*zLKzTH3J[x*+sdCCLOWE!S8u ? gk_S7  xrU v(*KN*&zLAG]9˽"Z n+H lVb{Wtt > ;>rZ lgcRa2oJkLj 3ĉ)2Lبs3`N)+:|Fs4m'S]~PrbGu+AJ(GJj#15h%T ܢߒj.Kkph`F4[ƫY fZz!܉VT=׆SA>&~R=SOS[}mƞMKg$L'fPl-%zek1X1FBl-Y6elP%2Dj68y%!||dX="p⥺Ob'6Z\r 8 0KI}__?J xQL2豑8m赓@P+dg 1$KǏ'A69 A8W` 8 3$Sbj% llDlFhk߲s <(QdnϹ,>qJ6舆JLvyJvv?v-_׬zO1DbbL6DV)wתZgC!&=4ș=%T Wf%BQ/„ݞ=|zl<9< G&KYs@bE/p,ڀ' Bk07 CxurWߍ -2q=,*낇> Fx4_z&OvkEJ νDQ"t7J?JHs$%'k$J7Tm D VnՂ|m"sԢGäVegx$A҈c Ac$x*ܿB`˛ڑh !j:rB]0Bflgm7+ligk lUj֐l3卡3I8@c 0~ǴH@)LWdq&,y+96/ws=x[0adX4.=Ns;u(;*k7,'rcgX{=ÃUpic\%hYZ?>aM8M2GA`3HH "l%U2c4P22-(ն84NppgXN5q [TFe~&7u>9~ D{)t;(5u JIj!/=6+ruZ_)tS%pi tm8Uɤ9]HR]ӹ:3ϸ:\&:t40[2gbBd7'A;G1Â<EjnUp$!㡇| w3p "+<*NgzC3*z7(6UMw Q'N!tMAya 5*S^:fuJOGht &o=>Վ];'Jgdꚛq'ڧ5fK JKMpaE"u*}MLM Pi6 P|awbS l۾^ES#UDC“eps  ܄'&g ViJ[dj(H$% *ť c) zZRsH6G%{. LOOD'k_X6.ʼn鉼E"%…\`tP7i/h|܀"5 -~9X77/Fih_:;zK6~Lv!.* ŀ|F0Dgt:)`` *˵i+g=$9 ߂Nj1c_?tWTz _o_/jm۶ *@qj!l\y̎(V c' 0,G<@J}h!vzol+$%h!S{PJfx Yp5@ϹzlS^(5*L'aS 5& 9,Sf*"eLA0[Ƙ=JzfƢwNQL5"M;ٺuڵk;?]9IV0v V8fI/FTO[ѷXN@ M@.S]eͼwC'UE|#pYB8%F˷}+vp293$_oOSFpGK,JIJ7-DzBl Msk}BӧNg9@oڍȨLJ{鑷P $1f7"]Nć֩x6 e%S4߬%]Z#YgZ K /sܪQ㴃(ȵ;J\IP:!w̛c. N8v&s]47;t?2)cw7j I5Ld ZU*v658NLpFdEK$&_{ڍɳn jyIX$XD pɬ"W땤7¥ѝʔ؉`p+B@$R0`2&{9<#Y]U-umc n@BVgE+ڀU,śk}^?zJ;_ G+<̅WzTHfꐔ*{tȔ%gvH?~?V&Aڥs EǏW_fIvla 2I-"N>,5K +r`-J׻ " f"Daf59,q0g-d1VSvvQ4"*,J#C zTMܴEtf: Lo[.R^K1,夜60˭/\mz1w؍ #Q,窨(\3a  FI_ZICW@K-v[[\OI+8^EIg* )^K!4[X-*`aH[]wp9i/X80?ցX:.\6sI0LjJ>HSr;(NyP}"ߞS3]D4oKY9,$( BS3N겳:@h7(b1L&LP j2:D:_V*ԲufLmLG6rsJ')БNLo&]zXw)o"5#FH|W˦Ly@hP #7y axeLR,9{.C(m*d &z?QR%MTvUy=N񾜫W^6vf0N%dH= gUU sa,`QZ:pozXW/*?:UZxq겎`䅆G~Y]!f u*]qt[w0l"SP#;DP3\|T%k q ۥ{Մr"x6 3DJ !9ɨD8u݂𹡛nsw߄rx jiAmd݇.VFusCCH‡dqi1Qx"sb3b3rV]9hس p"?2/, C#/T8ⅶ*6Yy44ٓ[ΞKO)!*g/8joRNURܟ8~L=v~DbWX .Dk3nLI*Nhp=Y!>>,P DJN"rΐ[̑_A'`4\4h`e1%9 vZ);I#.~־ i7rtq>Kțov?[^/d4w'GmRwCc[)Z `%}伳UAAHhhC@0%æ ufcT"G>DO~|LJ-|胷/w1x7מočn5[Yݨɨ5ff!I8q6+pe 46~Sw-yu u7.g7{|Vw]@Ocqwzy[Q mkaf\_\kadF8{J݄^2_^.aKn,;{>0Pz:FZ{[%n-5y\ ý+ L t˫Vɻu&o-=Iorպ~5Sټ:a IpT69p̹^~CVqql[8xwt%mo_́C/CU˻Ɯclr)'xLʯ{ v:jJgwc.LUk,{rub<//Y?9ś:3[mF| M8O#D0+g^0AR"y59&}&pwX j͈|6P ~.Jxq7ȭeK6f$j_Ua(v9fk1@9ұŤg>l P]Oڿ-765}w#x1Bk,#4UM$}=FXSp$`э -Rݘk8qݐõ$4;R.b59.?`I|aSۚL}x͸_E.G1tc=h&zYLTlF*5vBJt/!Ia3@F[֣Ml8/y|_sMNjqr(U|q_T1T G?_^ |ԃ[ ŅhMpLX1=J&[061dm$T|Ykp_5Mj~GVkd9baVMPz<֤Ef v\v:Ⱥnr!؂'Ѿ=uCoA7QՙE 6ƚkl;-;~w~I/AόYMB8;|@~l #M4HB;d2iJO;t/~z"iwHݥx c _4 oٲŋZ̛˻ yy~n.|q?oqC؏' ߁%ֵ*=r#&66`k$~iV&#^[04cMnp*wbS8PG~~n .nL`I|#O.D_IRo\k9t1D7cGb?>4LYT=˵7ؐ+'J%S/m#&[XL70@NUTzmz3q޻bjxS|1o*"7Y2j0%ZN -,aЍIjxyҥAG 'BxnhyV/ďN=]b2,:K/VhF:1UY1gA֤%kaگa]aOc"Wʴ/ߊ_9|-uwЃ1ijˆcʌG"V1_|qu~ KWޢD1(~ۛA~?GwK]^]ҬB*赗K:>42 &Oo~R}'眠/O塟N'C&|= ލia7#$C(t* cC>>à`0-?C?N怙2tnAAvwucWp 6<>kϬAHPhFOǓ߇g{3^_^lgΝ;dELtfFF裰ԴAzTo_RIϟ_ ҿG߷r@! lQa4$Fpư=`Yr-0Oyb7>:Y.d8I 8hr! ?v=j'2ey9Zx޺B."}'aWlѿ=*30|+rp~/"4 (޿ 1w׾G&[7"n.@RiZ=? jO%tEXtdate:create2011-10-13T18:23:38+08:00.J%tEXtdate:modify2011-10-13T18:23:38+08:00ۆIENDB`sandboxgamemaker-2.8.2+dfsg/sandbox_unix0000755000175000017500000001166712047626771017366 0ustar bofh80bofh80#!/bin/bash # SANDBOX_DIR should refer to the directory in which sandbox is placed, the default should be good enough. #SANDBOX_DIR=~/sandbox #SANDBOX_DIR=/usr/local/sandbox SANDBOX_DIR=$(dirname $(readlink -f $0)) SANDBOX_OPTIONS="" SANDBOX_MODULE="fps" SANDBOX_HOME="${HOME}/.platinumarts" SANDBOX_TYPE="client" SANDBOX_PREFIX="sandbox" SANDBOX_EXEC="" while [ $# -ne 0 ] do case $1 in "-h"|"-?"|"-help"|"--help") echo "" echo "Sandbox Linux Launching Script" echo "Example: ./sandbox_unix -gssp -t1" echo "" echo " Script Arguments" echo " -h|-?|-help|--help show this help message" echo " -g set gamemode to (default: fps)" echo " available modes: fps, krs, movie, rpg, ssp" echo " --server launch dedicated server binary instead" echo " --master launch a masterserver for server registration" echo " NOTE: compiled masterserver not included" echo " --debug starts the debug build(s) inside GDB" echo " note that all arguments passed to this script will be" echo " passed to sandbox when run is invokved in gdb." echo " it's recommended that you do this in windowed mode (-t0)" echo "" echo " Client Options" echo " -q use as the home directory (default: ~/.platinumarts)" echo " -k mounts as a package directory" echo " -r executes before launching, use instead of arguments such as -t, -a, -h, etc" echo " -t sets fullscreen to " echo " -d runs a dedicated server (0), or a listen server (1)" echo " -w sets window width, height is set to width * 3 / 4 unless also provided" echo " -h sets window height, width is set to height * 4 / 3 unless also provided" echo " -z sets depth (z) buffer bits (do not touch)" echo " -b sets colour bits (usually 32 bit)" echo " -a sets anti aliasing to " echo " -v sets vsync to -- -1 for auto" echo " -t sets fullscreen to " echo " -s sets stencil buffer bits to (do not touch)" echo " -f sets renderpath/shader precision" echo " 0 - turns shaders off" echo " 1 - 3 sets shader precision for ASM/GLSL renderpath" echo " 4 - 6 sets shader precision for GLSL renderpath" echo " -l loads map after initialisation" echo " -x executes script after initialisation" echo "" echo " Server Options" echo " NOTE: the dedicated server binary uses initserver.cfg, which overrides the below" echo " -u sets the upload rate to " echo " -c sets the maximum amount of clients (max: 127 humans)" echo " -i sets the server's ip address (use with caution)" echo " -j sets the port to use for server connections" echo " -m sets the masterserver's URL to " echo " -q use as the home directory (default: ~/.platinumarts)" echo " -k mounts as a package directory" echo "" echo "Sandbox Script by Kevin \"Hirato Kirata\" Meyer" echo "(c) 2008-2011 - zlib/libpng licensed" echo "" exit 1 ;; esac tag=$(expr substr "$1" 1 2) argument=$(expr substr "$1" 3 1022) case $tag in "-g") SANDBOX_MODULE=$argument ;; "-q") SANDBOX_HOME="\"$argument\"" ;; "--") case $argument in "server") SANDBOX_TYPE="server" ;; "master") SANDBOX_TYPE="master" ;; "debug") SANDBOX_PREFIX="debug" SANDBOX_EXEC="gdb --args" ;; esac ;; *) SANDBOX_OPTIONS+=" \"$tag$argument\"" ;; esac shift done case $(uname -m) in i386|i486|i586|i686) MACHINE_BIT=32 ;; *) MACHINE_BIT=64 #assume 64bit otherwise ;; esac function failed { echo "" echo "A problem was encountered, please check which of the following it is." echo "1) there's no ${SANDBOX_TYPE} for module ${SANDBOX_MODULE}" echo "2) There isn't an available executable for your architecture; $(uname -m)" echo "3) the executable was moved" echo "please make sure that ${SANDBOX_DIR}/bin/${SANDBOX_PREFIX}_${SANDBOX_TYPE}_${MACHINE_BIT}_${SANDBOX_MODULE} exists. If it doesn't..." echo "install the sdl, sdl-image and sdl-mixer DEVELOPMENT libraries and use \"make -C ${SANDBOX_DIR}/src install\" to compile a binary" echo "" exit 1 } cd ${SANDBOX_DIR} case ${SANDBOX_TYPE} in "client") if [ -a bin/${SANDBOX_PREFIX}_client_${MACHINE_BIT}_${SANDBOX_MODULE} ] then eval ${SANDBOX_EXEC} ./bin/${SANDBOX_PREFIX}_client_${MACHINE_BIT}_${SANDBOX_MODULE} -q${SANDBOX_HOME} -r ${SANDBOX_OPTIONS} else failed fi ;; "server") if [ -a bin/${SANDBOX_PREFIX}_server_${MACHINE_BIT}_${SANDBOX_MODULE} ] then eval ${SANDBOX_EXEC} ./bin/${SANDBOX_PREFIX}_server_${MACHINE_BIT}_${SANDBOX_MODULE} -q${SANDBOX_HOME} ${SANDBOX_OPTIONS} else failed fi ;; "master") if [ -a bin/${SANDBOX_PREFIX}_master ] then eval ${SANDBOX_EXEC} ./bin/${SANDBOX_PREFIX}_master else failed fi ;; esac sandboxgamemaker-2.8.2+dfsg/Platinum Arts Sandbox Newsletter Signup.url0000644000175000017500000000014212047201140025025 0ustar bofh80bofh80[InternetShortcut] URL=http://sandboxgamemaker.com/newsletter.html Modified=A0A8D3940645CA01C5 sandboxgamemaker-2.8.2+dfsg/changelog.txt0000644000175000017500000000440512075407135017407 0ustar bofh80bofh80 Changelog 2.8.2 =============== Generic changes * as a fallback, entities without a dedicated QuickEdit GUI will generate one with fallback dummy attributes with a range of -10000 --> 10000 (fixed) * embed mapmodel previews into mapmodel quickedit menu" SSP Changes * allow pickup_armour types to have arbitrary icons and colours set for them. * basic Goomba level AI * DJUMP armour, simpler version of the FLY armour that allows only one jump in the air. * homing mines and grenade projectile types. * various tweaks,cleanup and optimisation * platforms Generic Bugfixes * Allow uitoggle elements to have tooltips like other uibutton derived types * Fix material filter in the edit menu * Possible crash from showenttext 0 FPS Bugfixes * correct spacetf typo * renamed "banana" entities back to 'base" * fix range for 'playermodel' RPG bugfixes * Fix calculation of extra empty inventory, barter and looting buttons. * Fix some potential crashes, such as when r_setref was called outside of a game. SSP Bugfixes * enemies are no longer simulated in editmode with the ability to hurt the player. * fly/doublejump armour no longer causes enemies to jetpack upwards Changelog 2.8.1 =============== Linux * fixed permission errors with install.sh script, and improved it for package creators. People who used the previous script SHOULD MAKE SURE TO CLEAN UP EVERYTHING CREATED/MOVED BY THE PREVIOUS SCRIPT! Art * Courtesy of northstar, mapmodel preview shots for 163 odd models. Generic changes * Save map option in the editing menu (how embarrassing!) * getcurmap command extended to all game modules for getting the name of the current map. * as a fallback, entities without a dedicated QuickEdit GUI will generate one with fallback dummy attributes with a range of -10000 --> 10000 FPS changes * allow scrolling over an item entity to switch between items during editmode SSP changes * make 2HP state a lighter yellow. * enumerate pickups/boxes written by the exporter. Generic bugfixes * fixed model scripts that triggered infinitely recursive loading of themselves. (Really this time) * fix editfacewentpush behaviour when an entity is selected SSP bugfixes * fixed HUD paths and images * fixed box rendering/collision offsets * fixed lightning particles for "attracted" pickups. sandboxgamemaker-2.8.2+dfsg/install.sh0000755000175000017500000000707212046737400016726 0ustar bofh80bofh80#!/bin/bash # dear packagers, there are 2 variables you can set whilst running this script # INSTALL sets the path to copy and install the files to # PREFIX sets the path in which this install will operate # # For example, an AUR ( http://aur.archlinux.org ) script would invoke it as follows # INSTALL="$pkgdir" PREFIX="/usr" ./install.sh if [ "${INSTALL}" == "" ] then INSTALL="" fi if [ "${PREFIX}" == "" ] then echo "You are installing sandbox globally, if you wish to abort, hit Ctrl-C now" echo "" echo "Enter installation prefix..." echo "default: /usr/local" read PREFIX if [ "${PREFIX}" == "" ] then PREFIX="/usr/local" fi echo "Sandbox will be installed in \"${PREFIX}/share/sandbox\"" echo "Files will be copied to \"${INSTALL}${PREFIX}/share/sandbox\"" echo "Press enter to continue" read CC fi if [ -e "${INSTALL}${PREFIX}/share/sandbox" ] then echo "NOTE, \"${INSTALL}${PREFIX}/share/sandbox\" already exists - removing" rm -rf "${INSTALL}${PREFIX}/share/sandbox" fi echo "Creating directory \"${INSTALL}${PREFIX}/share/sandbox\"" mkdir -p "${INSTALL}${PREFIX}/share/sandbox" if [ $? -ne 0 ] then echo "Failed to create directory, do you have permission?" exit 1 fi echo "Copying files to \"${INSTALL}${PREFIX}/share/sandbox\" (this may take a while)" if [ -e .svn ] then echo ".svn folder exists, using svn export..." svn export --quiet . "${INSTALL}${PREFIX}/share/sandbox" else echo "No .svn folder available, copying current directory to destination..." cp -r . "${INSTALL}${PREFIX}/share/sandbox" fi if [ $? -ne 0 ] then echo "Failed to copy files, do you have permission?" exit 1 fi #just in case mkdir -p "${INSTALL}${PREFIX}/bin" echo "Creating symlink from \"${INSTALL}${PREFIX}/bin/sandbox\" to \"${PREFIX}/share/sandbox/sandbox_unix\"" if [ -e "${INSTALL}${PREFIX}/bin/sandbox" ] then echo "NOTE, \"${INSTALL}${PREFIX}/bin/sandbox\" exists - removing" rm -f "${INSTALL}${PREFIX}/bin/sandbox" fi # we want to reference it via the prefix path ln -s "${PREFIX}/share/sandbox/sandbox_unix" "${INSTALL}${PREFIX}/bin/sandbox" if [ $? -ne 0 ] then echo "Failed to create symlink, do you have permission?" exit 1 fi echo "Setting file permissions to 0644 and owner to root..." chmod -R a+X "${INSTALL}${PREFIX}/share/sandbox" chmod -R og-w "${INSTALL}${PREFIX}/share/sandbox" if [ $UID -eq 0 ] then chown -R root:root "${INSTALL}${PREFIX}/share/sandbox" else echo "Warning, cannot set owner of \"${INSTALL}${PREFIX}/share/sandbox\" to root!" fi # this is to undo the above partially so everyone can access these directories echo "Setting executable bits on scripts and binaries (just in case)" chmod +x ${INSTALL}${PREFIX}/share/sandbox/sandbox_unix chmod +x ${INSTALL}${PREFIX}/share/sandbox/bin/sandbox_{client,server}_{32,64}_* mkdir -p "${INSTALL}${PREFIX}/share/pixmaps" echo "Installing pixmaps to ${INSTALL}${PREFIX}/share/pixmaps" cp ./linux/*.png "${INSTALL}${PREFIX}/share/pixmaps" mkdir "${INSTALL}${PREFIX}/share/applications" echo "Installing .desktop files to ${INSTALL}${PREFIX}/share/applications" cp ./linux/*.desktop "${INSTALL}${PREFIX}/share/applications" echo "Sandbox has been successfully installed" echo "" echo "To fully uninstall sandbox, run the following commands" echo "rm \"${INSTALL}${PREFIX}/bin/sandbox\"" echo "rm -r \"${INSTALL}${PREFIX}/share/sandbox\"" echo "rm ${INSTALL}${PREFIX}/share/pixmaps/sandbox_*" echo "rm ${INSTALL}${PREFIX}/share/applications/sandbox_*" echo "" echo "To run sandbox, simply enter \"sandbox\" into your shell of choice" echo "or select one of the launcher from your desktop's menu under the \"Games\" subtree" sandboxgamemaker-2.8.2+dfsg/src/0000755000175000017500000000000012363765327015515 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/src/fpsgame/0000755000175000017500000000000012076771132017127 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/src/fpsgame/ai.h0000644000175000017500000002377312045412564017702 0ustar bofh80bofh80struct fpsent; #define MAXBOTS 32 enum { AI_NONE = 0, AI_BOT, AI_MAX }; #define isaitype(a) (a >= 0 && a <= AI_MAX-1) namespace ai { const int MAXWAYPOINTS = USHRT_MAX - 2; const int MAXWAYPOINTLINKS = 6; const int WAYPOINTRADIUS = 16; const float MINWPDIST = 4.f; // is on top of const float CLOSEDIST = 32.f; // is close const float FARDIST = 128.f; // too far to remap close const float JUMPMIN = 4.f; // decides to jump const float JUMPMAX = 32.f; // max jump const float SIGHTMIN = 64.f; // minimum line of sight const float SIGHTMAX = 1024.f; // maximum line of sight const float VIEWMIN = 90.f; // minimum field of view const float VIEWMAX = 180.f; // maximum field of view struct waypoint { vec o; float curscore, estscore; int weight; ushort route, prev; ushort links[MAXWAYPOINTLINKS]; waypoint() {} waypoint(const vec &o, int weight = 0) : o(o), weight(weight), route(0) { memset(links, 0, sizeof(links)); } int score() const { return int(curscore) + int(estscore); } int find(int wp) { loopi(MAXWAYPOINTLINKS) if(links[i] == wp) return i; return -1; } bool haslinks() { return links[0]!=0; } }; extern vector waypoints; static inline bool iswaypoint(int n) { return n > 0 && n < waypoints.length(); } extern int showwaypoints, dropwaypoints; extern int closestwaypoint(const vec &pos, float mindist, bool links, fpsent *d = NULL); extern void findwaypointswithin(const vec &pos, float mindist, float maxdist, vector &results); extern void inferwaypoints(fpsent *d, const vec &o, const vec &v, float mindist = ai::CLOSEDIST); struct avoidset { struct obstacle { void *owner; int numwaypoints; float above; obstacle(void *owner, float above = -1) : owner(owner), numwaypoints(0), above(above) {} }; vector obstacles; vector waypoints; void clear() { obstacles.setsize(0); waypoints.setsize(0); } void add(void *owner, float above) { obstacles.add(obstacle(owner, above)); } void add(void *owner, float above, int wp) { if(obstacles.empty() || owner != obstacles.last().owner) add(owner, above); obstacles.last().numwaypoints++; waypoints.add(wp); } void add(avoidset &avoid) { waypoints.put(avoid.waypoints.getbuf(), avoid.waypoints.length()); loopv(avoid.obstacles) { obstacle &o = avoid.obstacles[i]; if(obstacles.empty() || o.owner != obstacles.last().owner) add(o.owner, o.above); obstacles.last().numwaypoints += o.numwaypoints; } } void avoidnear(void *owner, float above, const vec &pos, float limit); #define loopavoid(v, d, body) \ if(!(v).obstacles.empty()) \ { \ int cur = 0; \ loopv((v).obstacles) \ { \ const ai::avoidset::obstacle &ob = (v).obstacles[i]; \ int next = cur + ob.numwaypoints; \ if(ob.owner != d) \ { \ for(; cur < next; cur++) \ { \ int wp = (v).waypoints[cur]; \ body; \ } \ } \ cur = next; \ } \ } bool find(int n, fpsent *d) const { loopavoid(*this, d, { if(wp == n) return true; }); return false; } int remap(fpsent *d, int n, vec &pos, bool retry = false); }; extern bool route(fpsent *d, int node, int goal, vector &route, const avoidset &obstacles, int retries = 0); extern void navigate(); extern void clearwaypoints(bool full = false); extern void seedwaypoints(); extern void loadwaypoints(bool force = false, const char *mname = NULL); extern void savewaypoints(bool force = false, const char *mname = NULL); // ai state information for the owner client enum { AI_S_WAIT = 0, // waiting for next command AI_S_DEFEND, // defend goal target AI_S_PURSUE, // pursue goal target AI_S_INTEREST, // interest in goal entity AI_S_MAX }; enum { AI_T_NODE, AI_T_PLAYER, AI_T_AFFINITY, AI_T_ENTITY, AI_T_MAX }; struct interest { int state, node, target, targtype; float score; interest() : state(-1), node(-1), target(-1), targtype(-1), score(0.f) {} ~interest() {} }; struct aistate { int type, millis, targtype, target, idle; bool override; aistate(int m, int t, int r = -1, int v = -1) : type(t), millis(m), targtype(r), target(v) { reset(); } ~aistate() {} void reset() { idle = 0; override = false; } }; const int NUMPREVNODES = 6; struct aiinfo { vector state; vector route; vec target, spot; int enemy, enemyseen, enemymillis, weappref, prevnodes[NUMPREVNODES], targnode, targlast, targtime, targseq, lastrun, lasthunt, lastaction, lastcheck, jumpseed, jumprand, blocktime, huntseq, blockseq, lastaimrnd; float targyaw, targpitch, views[3], aimrnd[3]; bool dontmove, becareful, tryreset, trywipe; aiinfo() { clearsetup(); reset(); loopk(3) views[k] = 0.f; } ~aiinfo() {} void clearsetup() { weappref = GUN_PISTOL; spot = target = vec(0, 0, 0); lastaction = lasthunt = lastcheck = enemyseen = enemymillis = blocktime = huntseq = blockseq = targtime = targseq = lastaimrnd = 0; lastrun = jumpseed = lastmillis; jumprand = lastmillis+5000; targnode = targlast = enemy = -1; } void clear(bool prev = false) { if(prev) memset(prevnodes, -1, sizeof(prevnodes)); route.setsize(0); } void wipe(bool prev = false) { clear(prev); state.setsize(0); addstate(AI_S_WAIT); trywipe = false; } void clean(bool tryit = false) { if(!tryit) becareful = dontmove = false; targyaw = rnd(360); targpitch = 0.f; tryreset = tryit; } void reset(bool tryit = false) { wipe(); clean(tryit); } bool hasprevnode(int n) const { loopi(NUMPREVNODES) if(prevnodes[i] == n) return true; return false; } void addprevnode(int n) { if(prevnodes[0] != n) { memmove(&prevnodes[1], prevnodes, sizeof(prevnodes) - sizeof(prevnodes[0])); prevnodes[0] = n; } } aistate &addstate(int t, int r = -1, int v = -1) { return state.add(aistate(lastmillis, t, r, v)); } void removestate(int index = -1) { if(index < 0) state.pop(); else if(state.inrange(index)) state.remove(index); if(!state.length()) addstate(AI_S_WAIT); } aistate &getstate(int idx = -1) { if(state.inrange(idx)) return state[idx]; return state.last(); } aistate &switchstate(aistate &b, int t, int r = -1, int v = -1) { if((b.type == t && b.targtype == r) || (b.type == AI_S_INTEREST && b.targtype == AI_T_NODE)) { b.millis = lastmillis; b.target = v; b.reset(); return b; } return addstate(t, r, v); } }; extern avoidset obstacles; extern vec aitarget; extern float viewdist(int x = 101); extern float viewfieldx(int x = 101); extern float viewfieldy(int x = 101); extern bool targetable(fpsent *d, fpsent *e); extern bool cansee(fpsent *d, vec &x, vec &y, vec &targ = aitarget); extern void init(fpsent *d, int at, int on, int sk, int bn, int pm, const char *name, const char *team); extern void update(); extern void avoid(); extern void think(fpsent *d, bool run); extern bool badhealth(fpsent *d); extern bool checkothers(vector &targets, fpsent *d = NULL, int state = -1, int targtype = -1, int target = -1, bool teams = false); extern bool makeroute(fpsent *d, aistate &b, int node, bool changed = true, int retries = 0); extern bool makeroute(fpsent *d, aistate &b, const vec &pos, bool changed = true, int retries = 0); extern bool randomnode(fpsent *d, aistate &b, const vec &pos, float guard = SIGHTMIN, float wander = SIGHTMAX); extern bool randomnode(fpsent *d, aistate &b, float guard = SIGHTMIN, float wander = SIGHTMAX); extern bool violence(fpsent *d, aistate &b, fpsent *e, int pursue = 0); extern bool patrol(fpsent *d, aistate &b, const vec &pos, float guard = SIGHTMIN, float wander = SIGHTMAX, int walk = 1, bool retry = false); extern bool defend(fpsent *d, aistate &b, const vec &pos, float guard = SIGHTMIN, float wander = SIGHTMAX, int walk = 1); extern void assist(fpsent *d, aistate &b, vector &interests, bool all = false, bool force = false); extern bool parseinterests(fpsent *d, aistate &b, vector &interests, bool override = false, bool ignore = false); extern void spawned(fpsent *d); extern void damaged(fpsent *d, fpsent *e); extern void killed(fpsent *d, fpsent *e); extern void itemspawned(int ent); extern void render(); } sandboxgamemaker-2.8.2+dfsg/src/fpsgame/ctf.h0000644000175000017500000012230012045412564020047 0ustar bofh80bofh80#ifndef PARSEMESSAGES #define ctfteamflag(s) (!strcmp(s, "good") ? 1 : (!strcmp(s, "evil") ? 2 : 0)) #define ctfflagteam(i) (i==1 ? "good" : (i==2 ? "evil" : NULL)) #ifdef SERVMODE VAR(ctftkpenalty, 0, 1, 1); struct ctfservmode : servmode #else struct ctfclientmode : clientmode #endif { static const int BASERADIUS = 64; static const int BASEHEIGHT = 24; static const int MAXFLAGS = 20; static const int FLAGRADIUS = 16; static const int FLAGLIMIT = 10; static const int MAXHOLDSPAWNS = 100; static const int HOLDSECS = 20; static const int HOLDFLAGS = 1; struct flag { int id, version, spawnindex; vec droploc, spawnloc; int team, droptime, owntime; #ifdef SERVMODE int owner, dropper, invistime; #else fpsent *owner; float dropangle, spawnangle; entitylight light; vec interploc; float interpangle; int interptime, vistime; #endif flag() { reset(); } void reset() { version = 0; spawnindex = -1; droploc = spawnloc = vec(0, 0, 0); #ifdef SERVMODE owner = dropper = -1; invistime = owntime = 0; #else loopv(players) players[i]->flagpickup &= ~(1<o).sub(owner->eyeheight); if(droptime) return droploc; return spawnloc; } #endif }; struct holdspawn { vec o; #ifndef SERVMODE entitylight light; #endif }; vector holdspawns; vector flags; int scores[2]; void resetflags() { holdspawns.shrink(0); flags.shrink(0); loopk(2) scores[k] = 0; } #ifdef SERVMODE bool addflag(int i, const vec &o, int team, int invistime = 0) #else bool addflag(int i, const vec &o, int team, int vistime = -1000) #endif { if(i<0 || i>=MAXFLAGS) return false; while(flags.length()<=i) flags.add(); flag &f = flags[i]; f.reset(); f.id = i; f.team = team; f.spawnloc = o; #ifdef SERVMODE f.invistime = invistime; #else f.vistime = vistime; #endif return true; } #ifdef SERVMODE bool addholdspawn(const vec &o) #else bool addholdspawn(const vec &o) #endif { if(holdspawns.length() >= MAXHOLDSPAWNS) return false; holdspawn &h = holdspawns.add(); h.o = o; return true; } #ifdef SERVMODE void ownflag(int i, int owner, int owntime) #else void ownflag(int i, fpsent *owner, int owntime) #endif { flag &f = flags[i]; f.owner = owner; f.owntime = owntime; #ifdef SERVMODE f.dropper = -1; f.invistime = 0; #else loopv(players) players[i]->flagpickup &= ~(1<flagpickup &= ~(1<flagpickup &= ~(1<= 1 && team <= 2 ? scores[team-1] : 0; } int setscore(int team, int score) { if(team >= 1 && team <= 2) return scores[team-1] = score; return 0; } int addscore(int team, int score) { if(team >= 1 && team <= 2) return scores[team-1] += score; return 0; } bool hidefrags() { return true; } int getteamscore(const char *team) { return totalscore(ctfteamflag(team)); } void getteamscores(vector &tscores) { loopk(2) if(scores[k]) tscores.add(teamscore(ctfflagteam(k+1), scores[k])); } bool insidebase(const flag &f, const vec &o) { float dx = (f.spawnloc.x-o.x), dy = (f.spawnloc.y-o.y), dz = (f.spawnloc.z-o.z); return dx*dx + dy*dy <= BASERADIUS*BASERADIUS && fabs(dz) <= BASEHEIGHT; } #ifdef SERVMODE static const int RESETFLAGTIME = 10000; static const int INVISFLAGTIME = 20000; bool notgotflags; ctfservmode() : notgotflags(false) {} void reset(bool empty) { resetflags(); notgotflags = !empty; } void cleanup() { reset(false); } void setupholdspawns() { if(!m_hold || holdspawns.empty()) return; while(flags.length() < HOLDFLAGS) { int i = flags.length(); if(!addflag(i, vec(0, 0, 0), 0, 0)) break; flag &f = flags[i]; spawnflag(i); sendf(-1, 1, "ri6", N_RESETFLAG, i, ++f.version, f.spawnindex, 0, 0); } } void setup() { reset(false); if(notgotitems || ments.empty()) return; if(m_hold) { loopv(ments) { entity &e = ments[i]; if(e.type != BASE) continue; if(!addholdspawn(e.o)) break; } setupholdspawns(); } else loopv(ments) { entity &e = ments[i]; if(e.type != FLAG || e.attr[1] < 1 || e.attr[1] > 2) continue; if(!addflag(flags.length(), e.o, e.attr[1], m_protect ? lastmillis : 0)) break; } notgotflags = false; } void newmap() { reset(true); } void dropflag(clientinfo *ci, clientinfo *dropper = NULL) { if(notgotflags) return; loopv(flags) if(flags[i].owner==ci->clientnum) { flag &f = flags[i]; if(m_protect && insidebase(f, ci->state.o)) { returnflag(i); sendf(-1, 1, "ri4", N_RETURNFLAG, ci->clientnum, i, ++f.version); } else { ivec o(vec(ci->state.o).mul(DMF)); sendf(-1, 1, "ri7", N_DROPFLAG, ci->clientnum, i, ++f.version, o.x, o.y, o.z); dropflag(i, o.tovec().div(DMF), lastmillis, dropper ? dropper->clientnum : ci->clientnum); } } } void leavegame(clientinfo *ci, bool disconnecting = false) { dropflag(ci); loopv(flags) if(flags[i].dropper == ci->clientnum) flags[i].dropper = -1; } void died(clientinfo *ci, clientinfo *actor) { dropflag(ci, ctftkpenalty && actor && actor != ci && isteam(actor->team, ci->team) ? actor : NULL); loopv(flags) if(flags[i].dropper == ci->clientnum) flags[i].dropper = -1; } bool canchangeteam(clientinfo *ci, const char *oldteam, const char *newteam) { return ctfteamflag(newteam) > 0; } void changeteam(clientinfo *ci, const char *oldteam, const char *newteam) { dropflag(ci); } void spawnflag(int i) { if(holdspawns.empty()) return; int spawnindex = flags[i].spawnindex; loopj(4) { spawnindex = rnd(holdspawns.length()); if(spawnindex != flags[i].spawnindex) break; } flags[i].spawnindex = spawnindex; } void scoreflag(clientinfo *ci, int goal, int relay = -1) { returnflag(relay >= 0 ? relay : goal, m_protect ? lastmillis : 0); ci->state.flags++; int team = ctfteamflag(ci->team), score = addscore(team, 1); if(m_hold) spawnflag(goal); sendf(-1, 1, "rii9", N_SCOREFLAG, ci->clientnum, relay, relay >= 0 ? ++flags[relay].version : -1, goal, ++flags[goal].version, flags[goal].spawnindex, team, score, ci->state.flags); if(score >= FLAGLIMIT) startintermission(); } void takeflag(clientinfo *ci, int i, int version) { if(notgotflags || !flags.inrange(i) || ci->state.state!=CS_ALIVE || !ci->team[0]) return; flag &f = flags[i]; if((m_hold ? f.spawnindex < 0 : !ctfflagteam(f.team)) || f.owner>=0 || f.version != version || (f.droptime && f.dropper == ci->clientnum)) return; int team = ctfteamflag(ci->team); if(m_hold || m_protect == (f.team==team)) { loopvj(flags) if(flags[j].owner==ci->clientnum) return; ownflag(i, ci->clientnum, lastmillis); sendf(-1, 1, "ri4", N_TAKEFLAG, ci->clientnum, i, ++f.version); } else if(m_protect) { if(!f.invistime) scoreflag(ci, i); } else if(f.droptime) { returnflag(i); sendf(-1, 1, "ri4", N_RETURNFLAG, ci->clientnum, i, ++f.version); } else { loopvj(flags) if(flags[j].owner==ci->clientnum) { scoreflag(ci, i, j); break; } } } void update() { if(gamemillis>=gamelimit || notgotflags) return; loopv(flags) { flag &f = flags[i]; if(f.owner<0 && f.droptime && lastmillis - f.droptime >= RESETFLAGTIME) { returnflag(i, m_protect ? lastmillis : 0); if(m_hold) spawnflag(i); sendf(-1, 1, "ri6", N_RESETFLAG, i, ++f.version, f.spawnindex, m_hold ? 0 : f.team, m_hold ? 0 : addscore(f.team, m_protect ? -1 : 0)); } if(f.invistime && lastmillis - f.invistime >= INVISFLAGTIME) { f.invistime = 0; sendf(-1, 1, "ri3", N_INVISFLAG, i, 0); } if(m_hold && f.owner>=0 && lastmillis - f.owntime >= HOLDSECS*1000) { clientinfo *ci = getinfo(f.owner); if(ci) scoreflag(ci, i); else { spawnflag(i); sendf(-1, 1, "ri6", N_RESETFLAG, i, ++f.version, f.spawnindex, 0, 0); } } } } void initclient(clientinfo *ci, packetbuf &p, bool connecting) { putint(p, N_INITFLAGS); loopk(2) putint(p, scores[k]); putint(p, flags.length()); loopv(flags) { flag &f = flags[i]; putint(p, f.version); putint(p, f.spawnindex); putint(p, f.owner); putint(p, f.invistime ? 1 : 0); if(f.owner<0) { putint(p, f.droptime ? 1 : 0); if(f.droptime) { putint(p, int(f.droploc.x*DMF)); putint(p, int(f.droploc.y*DMF)); putint(p, int(f.droploc.z*DMF)); } } } } void parseflags(ucharbuf &p, bool commit) { int numflags = getint(p); loopi(numflags) { int team = getint(p); vec o; loopk(3) o[k] = max(getint(p)/DMF, 0.0f); if(p.overread()) break; if(commit && notgotflags) { if(m_hold) addholdspawn(o); else addflag(i, o, team, m_protect ? lastmillis : 0); } } if(commit && notgotflags) { if(m_hold) setupholdspawns(); notgotflags = false; } } }; #else static const int RESPAWNSECS = 5; void preload() { if(m_hold) preloadmodel("flags/neutral"); else { preloadmodel("flags/red"); preloadmodel("flags/blue"); } } void drawblip(fpsent *d, float x, float y, float s, const vec &pos, bool flagblip) { float scale = calcradarscale(); vec dir = d->o; dir.sub(pos).div(scale); float size = flagblip ? 0.1f : 0.05f, xoffset = flagblip ? -2*(3/32.0f)*size : -size, yoffset = flagblip ? -2*(1 - 3/32.0f)*size : -size, dist = dir.magnitude2(), maxdist = 1 - 0.05f - 0.05f; if(dist >= maxdist) dir.mul(maxdist/dist); dir.rotate_around_z(-camera1->yaw*RAD); drawradar(x + s*0.5f*(1.0f + dir.x + xoffset), y + s*0.5f*(1.0f + dir.y + yoffset), size*s); } void drawblip(fpsent *d, float x, float y, float s, int i, bool flagblip) { flag &f = flags[i]; settexture(m_hold && (!flagblip || !f.owner || lastmillis%1000 < 500) ? (flagblip ? "data/fps/hud/blip_neutral_flag.png" : "data/fps/hud/blip_neutral.png") : ((m_hold ? ctfteamflag(f.owner->team) : f.team)==ctfteamflag(player1->team) ? (flagblip ? "data/fps/hud/blip_blue_flag.png" : "data/fps/hud/blip_blue.png") : (flagblip ? "data/fps/hud/blip_red_flag.png" : "data/fps/hud/blip_red.png")), 3); drawblip(d, x, y, s, flagblip ? (f.owner ? f.owner->o : (f.droptime ? f.droploc : f.spawnloc)) : f.spawnloc, flagblip); } int clipconsole(int w, int h) { return (h*(1 + 1 + 10))/(4*10); } void drawhud(fpsent *d, int w, int h) { if(d->state == CS_ALIVE) { loopv(flags) if(flags[i].owner == d) { int x = HICON_X + 3*HICON_STEP + (d->quadmillis ? HICON_SIZE + HICON_SPACE : 0); drawicon(m_hold ? HICON_NEUTRAL_FLAG : (flags[i].team==ctfteamflag(d->team) ? HICON_BLUE_FLAG : HICON_RED_FLAG), x, HICON_Y); if(m_hold) { glPushMatrix(); glScalef(2, 2, 1); draw_textf("%d", (x + HICON_SIZE + HICON_SPACE)/2, HICON_TEXTY/2, max(HOLDSECS - (lastmillis - flags[i].owntime)/1000, 0)); glPopMatrix(); } break; } } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int s = 1800/4, x = 1800*w/h - s - s/10, y = s/10; glColor4f(1, 1, 1, minimapalpha); if(minimapalpha >= 1) glDisable(GL_BLEND); bindminimap(); drawminimap(d, x, y, s); if(minimapalpha >= 1) glEnable(GL_BLEND); glColor3f(1, 1, 1); float margin = 0.04f, roffset = s*margin, rsize = s + 2*roffset; settexture("data/fps/hud/radar.png", 3); drawradar(x - roffset, y - roffset, rsize); #if 0 settexture("data/fps/hud/compass.png", 3); glPushMatrix(); glTranslatef(x - roffset + 0.5f*rsize, y - roffset + 0.5f*rsize, 0); glRotatef(camera1->yaw + 180, 0, 0, -1); drawradar(-0.5f*rsize, -0.5f*rsize, rsize); glPopMatrix(); #endif if(m_hold) { settexture("data/fps/hud/blip_neutral.png", 3); loopv(holdspawns) drawblip(d, x, y, s, holdspawns[i].o, false); } loopv(flags) { flag &f = flags[i]; if(m_hold ? f.spawnindex < 0 : !ctfflagteam(f.team)) continue; if(!m_hold) drawblip(d, x, y, s, i, false); if(f.owner) { if(!m_hold && lastmillis%1000 >= 500) continue; } else if(f.droptime && (f.droploc.x < 0 || lastmillis%300 >= 150)) continue; drawblip(d, x, y, s, i, true); } if(d->state == CS_DEAD && (m_efficiency || !m_protect)) { int wait = respawnwait(d); if(wait>=0) { glPushMatrix(); glScalef(2, 2, 1); bool flash = wait>0 && d==player1 && lastspawnattempt>=d->lastpain && lastmillis < lastspawnattempt+100; draw_textf("%s%d", (x+s/2)/2-(wait>=10 ? 28 : 16), (y+s/2)/2-32, flash ? "\f3" : "", wait); glPopMatrix(); } } } void removeplayer(fpsent *d) { loopv(flags) if(flags[i].owner == d) { flag &f = flags[i]; f.interploc.x = -1; f.interptime = 0; dropflag(i, f.owner->o, f.owner->yaw, 1); } } vec interpflagpos(flag &f, float &angle) { vec pos = f.owner ? vec(f.owner->abovehead()).add(vec(0, 0, 1)) : (f.droptime ? f.droploc : f.spawnloc); if(f.owner) angle = f.owner->yaw; else if(m_hold) { float yaw, pitch; vectoyawpitch(vec(pos).sub(camera1->o), yaw, pitch); angle = yaw + 180; } else angle = f.droptime ? f.dropangle : f.spawnangle; if(pos.x < 0) return pos; if(f.interptime && f.interploc.x >= 0) { float t = min((lastmillis - f.interptime)/500.0f, 1.0f); pos.lerp(f.interploc, pos, t); angle += (1-t)*(f.interpangle - angle); } return pos; } vec interpflagpos(flag &f) { float angle; return interpflagpos(f, angle); } void rendergame() { loopv(flags) { flag &f = flags[i]; if(!f.owner && f.droptime && f.droploc.x < 0) continue; if(m_hold && f.spawnindex < 0) continue; const char *flagname = m_hold && (!f.owner || lastmillis%1000 < 500) ? "banana" : (m_hold ? ctfteamflag(f.owner->team) : f.team)==ctfteamflag(player1->team) ? "banana/blue" : "banana/red"; float angle; vec pos = interpflagpos(f, angle); if(m_hold) rendermodel(!f.droptime && !f.owner ? &f.light : NULL, flagname, ANIM_MAPMODEL|ANIM_LOOP, pos, angle, 0, 0, MDL_GHOST | MDL_CULL_VFC | (f.droptime || f.owner ? MDL_LIGHT : 0), NULL, NULL, 0, 0, 0.5f + 0.5f*(2*fabs(fmod(lastmillis/1000.0f, 1.0f) - 0.5f))); rendermodel(!f.droptime && !f.owner ? &f.light : NULL, flagname, ANIM_MAPMODEL|ANIM_LOOP, pos, angle, 0, 0, MDL_DYNSHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED | (f.droptime || f.owner ? MDL_LIGHT : 0), NULL, NULL, 0, 0, 0.3f + (f.vistime ? 0.7f*min((lastmillis - f.vistime)/1000.0f, 1.0f) : 0.0f)); if(m_protect && canaddparticles() && f.owner && insidebase(f, f.owner->feetpos())) { particle_flare(pos, f.spawnloc, 0, PART_LIGHTNING, strcmp(f.owner->team, player1->team) ? 0xFF2222 : 0x2222FF, 1.0f); if(!flags.inrange(f.owner->lastbase)) { particle_fireball(pos, 4.8f, PART_EXPLOSION, 250, strcmp(f.owner->team, player1->team) ? 0x802020 : 0x2020FF, 4.8f); particle_splash(PART_SPARK, 50, 250, pos, strcmp(f.owner->team, player1->team) ? 0x802020 : 0x2020FF, 0.24f); } f.owner->lastbase = i; } } if(m_protect && canaddparticles()) loopv(players) { fpsent *d = players[i]; if(!flags.inrange(d->lastbase)) continue; flag &f = flags[d->lastbase]; if(f.owner == d && insidebase(f, d->feetpos())) continue; d->lastbase = -1; float angle; vec pos = interpflagpos(f, angle); particle_fireball(pos, 4.8f, PART_EXPLOSION, 250, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 4.8f); particle_splash(PART_SPARK, 50, 250, pos, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 0.24f); } } void setup() { resetflags(); if(m_hold) { loopv(entities::ents) { extentity *e = entities::ents[i]; if(e->type!=BASE) continue; if(!addholdspawn(e->o)) continue; holdspawns.last().light = e->light; } if(holdspawns.length()) while(flags.length() < HOLDFLAGS) addflag(flags.length(), vec(0, 0, 0), 0, -1000); } else { loopv(entities::ents) { extentity *e = entities::ents[i]; if(e->type!=FLAG) continue; if(e->attr[1]<1 || e->attr[1]>2) continue; int index = flags.length(); if(!addflag(index, e->o, e->attr[1], m_protect ? 0 : -1000)) continue; flags[index].spawnangle = e->attr[0]; flags[index].light = e->light; } } } void senditems(packetbuf &p) { putint(p, N_INITFLAGS); if(m_hold) { putint(p, holdspawns.length()); loopv(holdspawns) { holdspawn &h = holdspawns[i]; putint(p, -1); loopk(3) putint(p, int(h.o[k]*DMF)); } } else { putint(p, flags.length()); loopv(flags) { flag &f = flags[i]; putint(p, f.team); loopk(3) putint(p, int(f.spawnloc[k]*DMF)); } } } void parseflags(ucharbuf &p, bool commit) { loopk(2) { int score = getint(p); if(commit) scores[k] = score; } int numflags = getint(p); loopi(numflags) { int version = getint(p), spawn = getint(p), owner = getint(p), invis = getint(p), dropped = 0; vec droploc(0, 0, 0); if(owner<0) { dropped = getint(p); if(dropped) loopk(3) droploc[k] = getint(p)/DMF; } if(commit && flags.inrange(i)) { flag &f = flags[i]; f.version = version; f.spawnindex = spawn; if(m_hold) spawnflag(f); f.owner = owner>=0 ? (owner==player1->clientnum ? player1 : newclient(owner)) : NULL; f.droptime = dropped; f.droploc = dropped ? droploc : f.spawnloc; f.vistime = invis>0 ? 0 : -1000; f.interptime = 0; if(dropped) { f.droploc.z += 4; if(!droptofloor(f.droploc, 4, 0)) f.droploc = vec(-1, -1, -1); } } } } void trydropflag() { if(!m_ctf) return; loopv(flags) if(flags[i].owner == player1) { addmsg(N_TRYDROPFLAG, "rc", player1); return; } } void dropflag(fpsent *d, int i, int version, const vec &droploc) { if(!flags.inrange(i)) return; flag &f = flags[i]; f.version = version; f.interploc = interpflagpos(f, f.interpangle); f.interptime = lastmillis; dropflag(i, droploc, d->yaw, 1); f.droploc.z += 4; d->flagpickup |= 1<team) ? "your" : "the enemy")); playsound(S_FLAGDROP); } void flagexplosion(int i, int team, const vec &loc) { int fcolor; vec color; if(!team) { fcolor = 0xFF8080; color = vec(1, 0.75f, 0.5f); } else if(team==ctfteamflag(player1->team)) { fcolor = 0x2020FF; color = vec(0.25f, 0.25f, 1); } else { fcolor = 0x802020; color = vec(1, 0.25f, 0.25f); } particle_fireball(loc, 30, PART_EXPLOSION, -1, fcolor, 4.8f); adddynlight(loc, 35, color, 900, 100); particle_splash(PART_SPARK, 150, 300, loc, fcolor, 0.24f); } void flageffect(int i, int team, const vec &from, const vec &to) { vec fromexp(from), toexp(to); if(from.x >= 0) { fromexp.z += 8; flagexplosion(i, team, fromexp); } if(from==to) return; if(to.x >= 0) { toexp.z += 8; flagexplosion(i, team, toexp); } if(from.x >= 0 && to.x >= 0) particle_flare(fromexp, toexp, 600, PART_LIGHTNING, !team ? 0xFFC0A0 : (team==ctfteamflag(player1->team) ? 0x2222FF : 0xFF2222), 1.0f); } void returnflag(fpsent *d, int i, int version) { if(!flags.inrange(i)) return; flag &f = flags[i]; f.version = version; flageffect(i, f.team, interpflagpos(f), f.spawnloc); f.interptime = 0; returnflag(i); if(m_protect && d->feetpos().dist(f.spawnloc) < FLAGRADIUS) d->flagpickup |= 1<team) ? "your" : "the enemy")); playsound(S_FLAGRETURN); } void spawnflag(flag &f) { if(!holdspawns.inrange(f.spawnindex)) return; holdspawn &h = holdspawns[f.spawnindex]; f.spawnloc = h.o; f.light = h.light; } void resetflag(int i, int version, int spawnindex, int team, int score) { setscore(team, score); if(!flags.inrange(i)) return; flag &f = flags[i]; f.version = version; bool shouldeffect = !m_hold || f.spawnindex >= 0; f.spawnindex = spawnindex; if(m_hold) spawnflag(f); if(shouldeffect) flageffect(i, m_hold ? 0 : team, interpflagpos(f), f.spawnloc); f.interptime = 0; returnflag(i, m_protect ? 0 : -1000); if(shouldeffect) { conoutf(CON_GAMEINFO, "%s flag reset", m_hold ? "the" : (f.team==ctfteamflag(player1->team) ? "your" : "the enemy")); playsound(S_FLAGRESET); } } void scoreflag(fpsent *d, int relay, int relayversion, int goal, int goalversion, int goalspawn, int team, int score, int dflags) { setscore(team, score); if(flags.inrange(goal)) { flag &f = flags[goal]; f.version = goalversion; f.spawnindex = goalspawn; if(m_hold) spawnflag(f); if(relay >= 0) { flags[relay].version = relayversion; flageffect(goal, team, f.spawnloc, flags[relay].spawnloc); } else flageffect(goal, team, interpflagpos(f), f.spawnloc); f.interptime = 0; returnflag(relay >= 0 ? relay : goal, m_protect ? 0 : -1000); d->flagpickup &= ~(1<feetpos().dist(f.spawnloc) < FLAGRADIUS) d->flagpickup |= 1<abovehead(), ds, PART_TEXT, 2000, 0x32FF64, 4.0f, -8); } d->flags = dflags; conoutf(CON_GAMEINFO, "%s scored for %s team", d==player1 ? "you" : colorname(d), team==ctfteamflag(player1->team) ? "your" : "the enemy"); playsound(S_FLAGSCORE); if(score >= FLAGLIMIT) conoutf(CON_GAMEINFO, "%s team captured %d flags", team==ctfteamflag(player1->team) ? "your" : "the enemy", score); } void takeflag(fpsent *d, int i, int version) { if(!flags.inrange(i)) return; flag &f = flags[i]; f.version = version; f.interploc = interpflagpos(f, f.interpangle); f.interptime = lastmillis; conoutf(CON_GAMEINFO, "%s %s %s", d==player1 ? "you" : colorname(d), m_hold || m_protect || f.droptime ? "picked up" : "stole", m_hold ? (ctfteamflag(d->team)==ctfteamflag(player1->team) ? "the flag for your team" : "the flag for the enemy team") : (f.team==ctfteamflag(player1->team) ? "your flag" : "the enemy flag")); ownflag(i, d, lastmillis); playsound(S_FLAGPICKUP); } void invisflag(int i, int invis) { if(!flags.inrange(i)) return; flag &f = flags[i]; if(invis>0) f.vistime = 0; else if(!f.vistime) f.vistime = lastmillis; } void checkitems(fpsent *d) { vec o = d->feetpos(); loopv(flags) { flag &f = flags[i]; if((m_hold ? f.spawnindex < 0 : !ctfflagteam(f.team)) || f.owner || (f.droptime && f.droploc.x<0)) continue; const vec &loc = f.droptime ? f.droploc : f.spawnloc; if(o.dist(loc) < FLAGRADIUS) { if(d->flagpickup&(1<flagpickup |= 1<flagpickup &= ~(1<feetpos(); d->flagpickup = 0; loopv(flags) { flag &f = flags[i]; if((m_hold ? f.spawnindex < 0 : !ctfflagteam(f.team)) || f.owner || (f.droptime && f.droploc.x<0)) continue; if(o.dist(f.droptime ? f.droploc : f.spawnloc) < FLAGRADIUS) d->flagpickup |= 1<lastpain)/1000) : 0; } bool pickholdspawn(fpsent *d) { vector spawns; loopv(flags) { flag &f = flags[i]; if(f.spawnindex < 0 || (!f.owner && (!f.droptime || f.droploc.x < 0))) continue; const vec &goal = f.owner ? f.owner->o : f.droploc; extentity *flagspawns[7]; int numflagspawns = 0; memset(flagspawns, 0, sizeof(flagspawns)); loopvj(entities::ents) { extentity *e = entities::ents[j]; if(e->type != PLAYERSTART || e->attr[1] != 0) continue; float dist = e->o.dist(goal); loopk(numflagspawns) { float sdist = flagspawns[k]->o.dist(goal); if(dist >= sdist) continue; swap(e, flagspawns[k]); dist = sdist; } if(numflagspawns < int(sizeof(flagspawns)/sizeof(flagspawns[0]))) flagspawns[numflagspawns++] = e; } loopk(numflagspawns) spawns.add(flagspawns[k]); } if(spawns.empty()) return false; int pick = rnd(spawns.length()); d->pitch = 0; d->roll = 0; loopv(spawns) { int attempt = (pick + i)%spawns.length(); d->o = spawns[attempt]->o; d->yaw = spawns[attempt]->attr[0]; if(entinmap(d, true)) return true; } return false; } void pickspawn(fpsent *d) { if(!m_hold || !pickholdspawn(d)) findplayerspawn(d, -1, m_hold ? 0 : ctfteamflag(d->team)); } const char *prefixnextmap() { return m_hold ? "capture_" : "ctf_"; } bool aihomerun(fpsent *d, ai::aistate &b) { if(m_protect || m_hold) { static vector interests; loopk(2) { interests.setsize(0); ai::assist(d, b, interests, k != 0); if(ai::parseinterests(d, b, interests, false, true)) return true; } } else { vec pos = d->feetpos(); loopk(2) { int goal = -1; loopv(flags) { flag &g = flags[i]; if(g.team == ctfteamflag(d->team) && (k || (!g.owner && !g.droptime)) && (!flags.inrange(goal) || g.spawnloc.squaredist(pos) < flags[goal].spawnloc.squaredist(pos))) { goal = i; } } if(flags.inrange(goal) && ai::makeroute(d, b, flags[goal].spawnloc)) { d->ai->switchstate(b, ai::AI_S_PURSUE, ai::AI_T_AFFINITY, goal); return true; } } } if(b.type == ai::AI_S_INTEREST && b.targtype == ai::AI_T_NODE) return true; // we already did this.. if(randomnode(d, b, ai::SIGHTMIN, 1e16f)) { d->ai->switchstate(b, ai::AI_S_INTEREST, ai::AI_T_NODE, d->ai->route[0]); return true; } return false; } bool aicheck(fpsent *d, ai::aistate &b) { static vector takenflags; takenflags.setsize(0); loopv(flags) { flag &g = flags[i]; if(g.owner == d) return aihomerun(d, b); else if(g.team == ctfteamflag(d->team) && ((g.owner && g.team != ctfteamflag(g.owner->team)) || g.droptime)) takenflags.add(i); } if(!ai::badhealth(d) && !takenflags.empty()) { int flag = takenflags.length() > 2 ? rnd(takenflags.length()) : 0; d->ai->switchstate(b, ai::AI_S_PURSUE, ai::AI_T_AFFINITY, takenflags[flag]); return true; } return false; } void aifind(fpsent *d, ai::aistate &b, vector &interests) { vec pos = d->feetpos(); loopvj(flags) { flag &f = flags[j]; if((!m_protect && !m_hold) || f.owner != d) { static vector targets; // build a list of others who are interested in this targets.setsize(0); bool home = !m_hold && f.team == ctfteamflag(d->team); ai::checkothers(targets, d, home ? ai::AI_S_DEFEND : ai::AI_S_PURSUE, ai::AI_T_AFFINITY, j, true); fpsent *e = NULL; loopi(numdynents()) if((e = (fpsent *)iterdynents(i)) && !e->ai && e->state == CS_ALIVE && isteam(d->team, e->team)) { // try to guess what non ai are doing vec ep = e->feetpos(); if(targets.find(e->clientnum) < 0 && (ep.squaredist(f.pos()) <= (FLAGRADIUS*FLAGRADIUS*4) || f.owner == e)) targets.add(e->clientnum); } if(home) { bool guard = false; if((f.owner && f.team != ctfteamflag(f.owner->team)) || f.droptime || targets.empty()) guard = true; else if(d->hasammo(d->ai->weappref)) { // see if we can relieve someone who only has a piece of crap fpsent *t; loopvk(targets) if((t = getclient(targets[k]))) { if((t->ai && !t->hasammo(t->ai->weappref)) || (!t->ai && (t->gunselect == GUN_FIST || t->gunselect == GUN_PISTOL))) { guard = true; break; } } } if(guard) { // defend the flag ai::interest &n = interests.add(); n.state = ai::AI_S_DEFEND; n.node = ai::closestwaypoint(f.pos(), ai::SIGHTMIN, true); n.target = j; n.targtype = ai::AI_T_AFFINITY; n.score = pos.squaredist(f.pos())/100.f; } } else { if(targets.empty()) { // attack the flag ai::interest &n = interests.add(); n.state = ai::AI_S_PURSUE; n.node = ai::closestwaypoint(f.pos(), ai::SIGHTMIN, true); n.target = j; n.targtype = ai::AI_T_AFFINITY; n.score = pos.squaredist(f.pos()); } else { // help by defending the attacker fpsent *t; loopvk(targets) if((t = getclient(targets[k]))) { ai::interest &n = interests.add(); n.state = ai::AI_S_DEFEND; n.node = t->lastnode; n.target = t->clientnum; n.targtype = ai::AI_T_PLAYER; n.score = d->o.squaredist(t->o); } } } } } } bool aidefend(fpsent *d, ai::aistate &b) { loopv(flags) { flag &g = flags[i]; if(g.owner == d) return aihomerun(d, b); } if(flags.inrange(b.target)) { flag &f = flags[b.target]; if(f.droptime) return ai::makeroute(d, b, f.pos()); if(f.owner) return ai::violence(d, b, f.owner, 4); int walk = 0; if(lastmillis-b.millis >= (201-d->skill)*33) { static vector targets; // build a list of others who are interested in this targets.setsize(0); ai::checkothers(targets, d, ai::AI_S_DEFEND, ai::AI_T_AFFINITY, b.target, true); fpsent *e = NULL; loopi(numdynents()) if((e = (fpsent *)iterdynents(i)) && !e->ai && e->state == CS_ALIVE && isteam(d->team, e->team)) { // try to guess what non ai are doing vec ep = e->feetpos(); if(targets.find(e->clientnum) < 0 && (ep.squaredist(f.pos()) <= (FLAGRADIUS*FLAGRADIUS*4) || f.owner == e)) targets.add(e->clientnum); } if(!targets.empty()) { d->ai->trywipe = true; // re-evaluate so as not to herd return true; } else { walk = 2; b.millis = lastmillis; } } vec pos = d->feetpos(); float mindist = float(FLAGRADIUS*FLAGRADIUS*8); loopv(flags) { // get out of the way of the returnee! flag &g = flags[i]; if(pos.squaredist(g.pos()) <= mindist) { if(!m_protect && !m_hold && g.owner && !strcmp(g.owner->team, d->team)) walk = 1; if(g.droptime && ai::makeroute(d, b, g.pos())) return true; } } return ai::defend(d, b, f.pos(), float(FLAGRADIUS*2), float(FLAGRADIUS*(2+(walk*2))), walk); } return false; } bool aipursue(fpsent *d, ai::aistate &b) { if(flags.inrange(b.target)) { flag &f = flags[b.target]; if(f.owner == d) return aihomerun(d, b); if(!m_hold && f.team == ctfteamflag(d->team)) { if(f.droptime) return ai::makeroute(d, b, f.pos()); if(f.owner) return ai::violence(d, b, f.owner, 4); } else { if(f.owner) return ai::violence(d, b, f.owner, 4); return ai::makeroute(d, b, f.pos()); } } return false; } }; extern ctfclientmode ctfmode; ICOMMAND(dropflag, "", (), { ctfmode.trydropflag(); }); #endif #elif SERVMODE case N_TRYDROPFLAG: { if((ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege) && cq && smode==&ctfmode) ctfmode.dropflag(cq); break; } case N_TAKEFLAG: { int flag = getint(p), version = getint(p); if((ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege) && cq && smode==&ctfmode) ctfmode.takeflag(cq, flag, version); break; } case N_INITFLAGS: if(smode==&ctfmode) ctfmode.parseflags(p, (ci->state.state!=CS_SPECTATOR || ci->privilege || ci->local) && !strcmp(ci->clientmap, smapname)); break; #else case N_INITFLAGS: { ctfmode.parseflags(p, m_ctf); break; } case N_DROPFLAG: { int ocn = getint(p), flag = getint(p), version = getint(p); vec droploc; loopk(3) droploc[k] = getint(p)/DMF; fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_ctf) ctfmode.dropflag(o, flag, version, droploc); break; } case N_SCOREFLAG: { int ocn = getint(p), relayflag = getint(p), relayversion = getint(p), goalflag = getint(p), goalversion = getint(p), goalspawn = getint(p), team = getint(p), score = getint(p), oflags = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_ctf) ctfmode.scoreflag(o, relayflag, relayversion, goalflag, goalversion, goalspawn, team, score, oflags); break; } case N_RETURNFLAG: { int ocn = getint(p), flag = getint(p), version = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_ctf) ctfmode.returnflag(o, flag, version); break; } case N_TAKEFLAG: { int ocn = getint(p), flag = getint(p), version = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_ctf) ctfmode.takeflag(o, flag, version); break; } case N_RESETFLAG: { int flag = getint(p), version = getint(p), spawnindex = getint(p), team = getint(p), score = getint(p); if(m_ctf) ctfmode.resetflag(flag, version, spawnindex, team, score); break; } case N_INVISFLAG: { int flag = getint(p), invis = getint(p); if(m_ctf) ctfmode.invisflag(flag, invis); break; } #endif sandboxgamemaker-2.8.2+dfsg/src/fpsgame/entities.cpp0000644000175000017500000007140712053074143021461 0ustar bofh80bofh80#include "game.h" namespace entities { using namespace game; int extraentinfosize() { return 0; } // size in bytes of what the 2 methods below read/write... so it can be skipped by other games void writeent(entity &e, char *buf) // write any additional data to disk (except for ET_ ents) { } void readent(entity &e, char *buf, int ver) // read from disk, and init { if(ver <= 30) switch(e.type) { case FLAG: case MONSTER: case TELEDEST: case RESPAWNPOINT: case BOX: case BARREL: case PLATFORM: case ELEVATOR: e.attr[0] = (int(e.attr[0])+180)%360; break; } if(ver <= 31) switch(e.type) { case BOX: case BARREL: case PLATFORM: case ELEVATOR: int yaw = (int(e.attr[0])%360 + 360)%360 + 7; e.attr[0] = yaw - yaw%15; break; } } #ifndef STANDALONE vector ents; vector &getents() { return ents; } bool mayattach(extentity &e) { return false; } bool attachent(extentity &e, extentity &a) { return false; } VARP(showlighting, 0, 1, 1); VARP(showdynlights, 0, 1, 1); const char *itemname(int i) { int t = ents[i]->type; if(tI_QUAD) return NULL; return itemstats[t-I_SHELLS].name; } int itemicon(int i) { int t = ents[i]->type; if(tI_QUAD) return -1; return itemstats[t-I_SHELLS].icon; } const char *entmdlname(int type) { static const char *entmdlnames[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "ammo/shells", "ammo/bullets", "ammo/rockets", "ammo/rrounds", "ammo/grenades", "ammo/cartridges", "health", "boost", "armor/green", "armor/yellow", "quad", "teleporter", NULL, NULL, NULL, //"carrot", NULL, NULL, NULL, // "checkpoint", NULL, NULL, NULL, NULL, NULL, NULL }; return entmdlnames[type]; } const char *entmodel(const entity &e) { if(e.type == TELEPORT) { if(e.attr[1] > 0) return mapmodelname(e.attr[1]); if(e.attr[1] < 0) return NULL; } return e.type < MAXENTTYPES ? entmdlname(e.type) : NULL; } void preloadentities() { loopi(MAXENTTYPES) { switch(i) { case I_SHELLS: case I_BULLETS: case I_ROCKETS: case I_ROUNDS: case I_GRENADES: case I_CARTRIDGES: if(m_noammo) continue; break; case I_HEALTH: case I_BOOST: case I_GREENARMOUR: case I_YELLOWARMOUR: case I_QUAD: if(m_noitems) continue; break; case CARROT: case RESPAWNPOINT: if(!m_classicsp) continue; break; } const char *mdl = entmdlname(i); if(!mdl) continue; preloadmodel(mdl); } } void renderentities() { loopv(ents) { extentity &e = *ents[i]; int revs = 10; switch(e.type) { case CARROT: case RESPAWNPOINT: if(e.attr[1]) revs = 1; break; case TELEPORT: if(e.attr[1] < 0) continue; break; default: if(!e.spawned || e.type < I_SHELLS || e.type > I_QUAD) continue; } const char *mdlname = 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); } } } #define renderfocus(i,f) { extentity &e = *ents[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); } bool dynlightsactive[32767]; void adddynlights() { loopv(ents) { if((ents[i]->type == DYNLIGHT && ents[i]->attr[4] > -1 && 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)); } } } void addammo(int type, int &v, bool local) { itemstat &is = itemstats[type-I_SHELLS]; v += is.add; if(v>is.max) v = is.max; if(local) msgsound(is.sound); } void repammo(fpsent *d, int type, bool local) { addammo(type, d->ammo[type-I_SHELLS+GUN_SG], local); } // these two functions are called when the server acknowledges that you really // picked up the item (in multiplayer someone may grab it before you). void pickupeffects(int n, fpsent *d) { if(!ents.inrange(n)) return; int type = ents[n]->type; if(typeI_QUAD) return; ents[n]->spawned = false; if(!d) return; itemstat &is = itemstats[type-I_SHELLS]; if(d!=player1 || isthirdperson()) { //particle_text(d->abovehead(), is.name, PART_TEXT, 2000, 0xFFC864, 4.0f, -8); particle_icon(d->abovehead(), is.icon%4, is.icon/4, PART_HUD_ICON_GREY, 2000, 0xFFFFFF, 2.0f, -8); } playsound(itemstats[type-I_SHELLS].sound, d!=player1 ? &d->o : NULL, NULL, 0, 0, -1, 0, 1500); d->pickup(type); if(d==player1) switch(type) { case I_BOOST: conoutf(CON_GAMEINFO, "\f2you have a permanent +10 health bonus! (%d)", d->maxhealth); playsound(S_V_BOOST, NULL, NULL, 0, 0, -1, 0, 3000); break; case I_QUAD: conoutf(CON_GAMEINFO, "\f2you got the quad!"); playsound(S_V_QUAD, NULL, NULL, 0, 0, -1, 0, 3000); break; } } // these functions are called when the client touches the item void teleporteffects(fpsent *d, int tp, int td, bool local) { if(d == player1) playsound(S_TELEPORT); else { if(ents.inrange(tp)) playsound(S_TELEPORT, &ents[tp]->o); if(ents.inrange(td)) playsound(S_TELEPORT, &ents[td]->o); } if(local && d->clientnum >= 0) { sendposition(d); packetbuf p(32, ENET_PACKET_FLAG_RELIABLE); putint(p, N_TELEPORT); putint(p, d->clientnum); putint(p, tp); putint(p, td); sendclientpacket(p.finalize(), 0); flushclient(); } } void jumppadeffects(fpsent *d, int jp, bool local) { if(d == player1) playsound(S_JUMPPAD); else if(ents.inrange(jp)) playsound(S_JUMPPAD, &ents[jp]->o); if(local && d->clientnum >= 0) { sendposition(d); packetbuf p(16, ENET_PACKET_FLAG_RELIABLE); putint(p, N_JUMPPAD); putint(p, d->clientnum); putint(p, jp); sendclientpacket(p.finalize(), 0); flushclient(); } } void teleport(int n, fpsent *d) // also used by monsters { int e = -1, tag = ents[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(ents[e]->attr[1]==tag) { teleporteffects(d, n, e, true); d->o = ents[e]->o; d->yaw = ents[e]->attr[0]; if(ents[e]->attr[2] > 0) { vec dir; vecfromyawpitch(d->yaw, 0, 1, 0, dir); float speed = d->vel.magnitude2(); d->vel.x = dir.x*speed; d->vel.y = dir.y*speed; } else d->vel = vec(0, 0, 0); entinmap(d); updatedynentcache(d); ai::inferwaypoints(d, ents[n]->o, ents[e]->o, 16.f); break; } } } void trypickup(int n, fpsent *d) { switch(ents[n]->type) { default: if(d->canpickup(ents[n]->type)) { addmsg(N_ITEMPICKUP, "rci", d, n); ents[n]->spawned = false; // even if someone else gets it first } break; case TELEPORT: { if(d->lastpickup==ents[n]->type && lastmillis-d->lastpickupmillis<500) break; if(ents[n]->attr[2] > 0) { defformatstring(hookname)("can_teleport_%d", ents[n]->attr[2]); if(identexists(hookname) && !execute(hookname)) break; } d->lastpickup = ents[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==ents[n]->type && lastmillis-d->lastpickupmillis<300) break; d->lastpickup = ents[n]->type; d->lastpickupmillis = lastmillis; jumppadeffects(d, n, true); vec v((int)(char)ents[n]->attr[2]*10.0f, (int)(char)ents[n]->attr[1]*10.0f, ents[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(fpsent *d) { if(d->state!=CS_ALIVE) return; vec o = d->feetpos(); loopv(ents) { extentity &e = *ents[i]; if(e.type==NOTUSED) continue; if(!e.spawned && e.type!=TELEPORT && e.type!=JUMPPAD && e.type!=RESPAWNPOINT) continue; float dist = e.o.dist(o); if(dist<(e.type==TELEPORT ? 16 : 12)) trypickup(i, d); } } void checkquad(int time, fpsent *d) { if(d->quadmillis && (d->quadmillis -= time)<=0) { d->quadmillis = 0; playsound(S_PUPOUT, d==player1 ? NULL : &d->o); if(d==player1) conoutf(CON_GAMEINFO, "\f2quad damage is over"); } } void putitems(packetbuf &p) // puts items in network stream and also spawns them locally { putint(p, N_ITEMLIST); loopv(ents) if(ents[i]->type>=I_SHELLS && ents[i]->type<=I_QUAD && (!m_noammo || ents[i]->typetype>I_CARTRIDGES)) { putint(p, i); putint(p, ents[i]->type); } putint(p, -1); } void resetspawns() { loopv(ents) ents[i]->spawned = false; } void spawnitems(bool force) { if(m_noitems) return; loopv(ents) if(ents[i]->type>=I_SHELLS && ents[i]->type<=I_QUAD && (!m_noammo || ents[i]->typetype>I_CARTRIDGES)) { ents[i]->spawned = force || m_sp || !server::delayspawn(ents[i]->type); } } void setspawn(int i, bool on) { if(ents.inrange(i)) ents[i]->spawned = on; } extentity *newentity() { return new fpsentity(); } void deleteentity(extentity *e) { delete (fpsentity *)e; } void clearents() { while(ents.length()) deleteentity(ents.pop()); } 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] = { -1, 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 -1 /* reserved 15 */, -1 /* reserved 16 */, -1 /* reserved 17 */, -1 /* reserved 18 */, -1 /* reserved 19 */, -1 /* reserved 20 */, -1 /* reserved 21 */, -1 /* reserved 22 */, -1 /* reserved 23 */, -1 /* reserved 24 */, -1 /* reserved 25 */, -1 /* reserved 26 */, -1 /* reserved 27 */, -1 /* reserved 28 */, TRIG_DISAPPEAR | TRIG_RUMBLE | TRIG_ENDSP, // 29 -1 /* reserved 30 */, -1 /* reserved 31 */, }; #define validtrigger(type) (triggertypes[(type) & (NUMTRIGGERTYPES-1)]>=0) #define checktriggertype(type, flag) (triggertypes[(type) & (NUMTRIGGERTYPES-1)] & (flag)) static inline void setuptriggerflags(fpsentity &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(ents) { fpsentity &e = *(fpsentity *)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(ents) { fpsentity &e = *(fpsentity *)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(ents) { fpsentity &e = *(fpsentity *)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 fpsentity &f = (const fpsentity &)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 fixentity(extentity &e) { switch(e.type) { case FLAG: case BOX: case BARREL: case PLATFORM: case ELEVATOR: case MONSTER: case TELEDEST: case RESPAWNPOINT: e.attr.pop(); e.attr.insert(0, player1->yaw); break; } } void entradius(extentity &e, bool &color) { switch(e.type) { case DYNLIGHT: 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 TELEPORT: 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; } break; case JUMPPAD: renderentarrow(e, vec((int)(char)e.attr[2]*10.0f, (int)(char)e.attr[1]*10.0f, e.attr[0]*12.5f).normalize(), 4); break; case FLAG: case MONSTER: case TELEDEST: case RESPAWNPOINT: case BOX: case BARREL: case PLATFORM: case ELEVATOR: { vec dir; vecfromyawpitch(e.attr[0], 0, 1, 0, dir); renderentarrow(e, dir, 4); break; } case MAPMODEL: if(validtrigger(e.attr[2])) renderentring(e, e.attr[4] ? e.attr[4] : checktriggertype(e.attr[2], TRIG_COLLIDE) ? 20 : 12); break; } } bool radiusent(extentity &e) { switch(e.type) { case LIGHT: case ENVMAP: case MAPSOUND: case DYNLIGHT: return true; break; default: return false; break; } } bool dirent(extentity &e) { switch(e.type) { case MAPMODEL: case PLAYERSTART: case SPOTLIGHT: case TELEDEST: case TELEPORT: case MONSTER: case JUMPPAD: case BOX: case BARREL: case PLATFORM: case ELEVATOR: case RESPAWNPOINT: case FLAG: return true; break; default: return false; break; } } bool printent(extentity &e, char *buf) { return false; } const char *entnameinfo(entity &e) { return ""; } const char *entname(int i) { static const char *entnames[] = { "none?", "light", "mapmodel", "playerstart", "envmap", "particles", "sound", "spotlight", "shells", "bullets", "rockets", "riflerounds", "grenades", "cartridges", "health", "healthboost", "greenarmour", "yellowarmour", "quaddamage", "teleport", "teledest", "creature", "carrot", "jumppad", "base", "respawnpoint", "box", "barrel", "platform", "elevator", "flag", "", "", "", "", }; return i>=0 && size_t(i)= 0 && size_t(type) < sizeof(num)/sizeof(num[0]) ? num[type] : 0; } void renderhelpertext(extentity &e, int &colour, vec &pos, string &tmp) { switch(e.type) { case TELEPORT: pos.z += 3.0; formatstring(tmp)("Teledest Tag: %i\nModel: %s (%i)\nTag: %i", e.attr[0], mapmodelname(e.attr[1]), e.attr[1], e.attr[2] ); return; case TELEDEST: pos.z += 3; formatstring(tmp)("Yaw: %i\nTeleport Tag: %i\n", e.attr[0], e.attr[1] ); return; case MONSTER: pos.z += 4.5; formatstring(tmp)("Yaw: %i\nMonster: %s (%i)\nTag: monster_dead_%i", e.attr[0], ((e.attr[1] >= 0 && e.attr[1] < game::NUMMONSTERTYPES) ? game::monstertypes[e.attr[1]].name : "(null)"), e.attr[1], e.attr[2] ); return; case JUMPPAD: pos.z += 4.5; formatstring(tmp)("Z: %i\nY: %i\nX: %i", e.attr[0], e.attr[1], e.attr[2] ); return; case BASE: pos.z += 3.0f; formatstring(tmp)("Ammo: %i\nTag: base_%i", e.attr[0], e.attr[1] ); return; case RESPAWNPOINT: pos.z += 1.5; formatstring(tmp)("Yaw: %i", e.attr[0] ); return; case BOX: case BARREL: 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] ); return; case PLATFORM: case ELEVATOR: 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] ); return; case FLAG: pos.z += 3.0f; formatstring(tmp)("Yaw: %i\nTeam: %i", e.attr[0], e.attr[1] ); return; case DYNLIGHT: pos.z += 7.5; 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] ); return; } } void editent(int i, bool local) { extentity &e = *ents[i]; if(e.type == ET_MAPMODEL && validtrigger(e.attr[2])) { fpsentity &f = (fpsentity &)e; f.triggerstate = TRIGGER_RESET; f.lasttrigger = 0; setuptriggerflags(f); } else e.flags = 0; if(local) addmsg(N_EDITENT, "rii3i2v", 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()); } float dropheight(entity &e) { if(e.type==BASE || e.type==FLAG) return 0.0f; return 4.0f; } int *getmodelattr(extentity &e) { switch(e.type) { case TELEPORT: case PLATFORM: case ELEVATOR: case BARREL: case BOX: return &e.attr[1]; default: return NULL; } } bool checkmodelusage(extentity &e, int i) { switch(e.type) { case TELEPORT: if(e.attr[1] == 0) return false; case PLATFORM: case ELEVATOR: case BARREL: case BOX: return (e.attr[1] == i); default: return false; } } #endif } sandboxgamemaker-2.8.2+dfsg/src/fpsgame/pch.cpp0000644000175000017500000000002312045412564020375 0ustar bofh80bofh80#include "game.h" sandboxgamemaker-2.8.2+dfsg/src/fpsgame/scoreboard.cpp0000644000175000017500000003120312045412564021752 0ustar bofh80bofh80// creation of scoreboard #include "game.h" namespace game { VARP(scoreboard2d, 0, 1, 1); VARP(showservinfo, 0, 1, 1); VARP(showclientnum, 0, 0, 1); VARP(showpj, 0, 0, 1); VARP(showping, 0, 1, 1); VARP(showspectators, 0, 1, 1); VARP(highlightscore, 0, 1, 1); VARP(showconnecting, 0, 0, 1); static inline bool playersort(const fpsent *a, const fpsent *b) { if(a->state==CS_SPECTATOR) { if(b->state==CS_SPECTATOR) return strcmp(a->name, b->name) < 0; else return false; } else if(b->state==CS_SPECTATOR) return true; if(m_ctf || m_collect) { if(a->flags > b->flags) return true; if(a->flags < b->flags) return false; } if(a->frags > b->frags) return true; if(a->frags < b->frags) return false; return strcmp(a->name, b->name) < 0; } void getbestplayers(vector &best) { loopv(players) { fpsent *o = players[i]; if(o->state!=CS_SPECTATOR) best.add(o); } best.sort(playersort); while(best.length()>1 && best.last()->frags < best[0]->frags) best.drop(); } void sortteams(vector &teamscores) { if(cmode && cmode->hidefrags()) cmode->getteamscores(teamscores); loopv(players) { fpsent *o = players[i]; teamscore *ts = NULL; loopv(teamscores) if(!strcmp(teamscores[i].team, o->team)) { ts = &teamscores[i]; break; } if(!ts) teamscores.add(teamscore(o->team, cmode && cmode->hidefrags() ? 0 : o->frags)); else if(!cmode || !cmode->hidefrags()) ts->score += o->frags; } teamscores.sort(teamscore::compare); } void getbestteams(vector &best) { vector teamscores; sortteams(teamscores); while(teamscores.length()>1 && teamscores.last().score < teamscores[0].score) teamscores.drop(); loopv(teamscores) best.add(teamscores[i].team); } struct scoregroup : teamscore { vector players; }; static vector groups; static vector spectators; static inline bool scoregroupcmp(const scoregroup *x, const scoregroup *y) { if(!x->team) { if(y->team) return false; } else if(!y->team) return true; if(x->score > y->score) return true; if(x->score < y->score) return false; if(x->players.length() > y->players.length()) return true; if(x->players.length() < y->players.length()) return false; return x->team && y->team && strcmp(x->team, y->team) < 0; } static int groupplayers() { int numgroups = 0; spectators.shrink(0); loopv(players) { fpsent *o = players[i]; if(!showconnecting && !o->name[0]) continue; if(o->state==CS_SPECTATOR) { spectators.add(o); continue; } const char *team = m_teammode && o->team[0] ? o->team : NULL; bool found = false; loopj(numgroups) { scoregroup &g = *groups[j]; if(team!=g.team && (!team || !g.team || strcmp(team, g.team))) continue; if(team && (!cmode || !cmode->hidefrags())) g.score += o->frags; g.players.add(o); found = true; } if(found) continue; if(numgroups>=groups.length()) groups.add(new scoregroup); scoregroup &g = *groups[numgroups++]; g.team = team; if(!team) g.score = 0; else if(cmode && cmode->hidefrags()) g.score = cmode->getteamscore(o->team); else g.score = o->frags; g.players.shrink(0); g.players.add(o); } loopi(numgroups) groups[i]->players.sort(playersort); spectators.sort(playersort); groups.sort(scoregroupcmp, 0, numgroups); return numgroups; } #if 0 void renderscoreboard(g3d_gui &g, bool firstpass) { const ENetAddress *address = connectedpeer(); if(showservinfo && address) { string hostname; if(enet_address_get_host_ip(address, hostname, sizeof(hostname)) >= 0) { if(servinfo[0]) g.titlef("%.25s", 0xFFFF80, NULL, servinfo); else g.titlef("%s:%d", 0xFFFF80, NULL, hostname, address->port); } } g.pushlist(); g.spring(); g.text(server::modename(gamemode), 0xFFFF80); g.separator(); const char *mname = getclientmap(); g.text(mname[0] ? mname : "[new map]", 0xFFFF80); if(m_timed && mname[0] && (maplimit >= 0 || intermission)) { g.separator(); if(intermission) g.text("intermission", 0xFFFF80); else { int secs = max(maplimit-lastmillis, 0)/1000, mins = secs/60; secs %= 60; g.pushlist(); g.strut(mins >= 10 ? 4.5f : 3.5f); g.textf("%d:%02d", 0xFFFF80, NULL, mins, secs); g.poplist(); } } if(paused || ispaused()) { g.separator(); g.text("paused", 0xFFFF80); } g.spring(); g.poplist(); g.separator(); int numgroups = groupplayers(); loopk(numgroups) { if((k%2)==0) g.pushlist(); // horizontal scoregroup &sg = *groups[k]; int bgcolor = sg.team && m_teammode ? (isteam(player1->team, sg.team) ? 0x3030C0 : 0xC03030) : 0, fgcolor = 0xFFFF80; g.pushlist(); // vertical g.pushlist(); // horizontal #define loopscoregroup(o, b) \ loopv(sg.players) \ { \ fpsent *o = sg.players[i]; \ b; \ } g.pushlist(); if(sg.team && m_teammode) { g.pushlist(); g.background(bgcolor, numgroups>1 ? 3 : 5); g.strut(1); g.poplist(); } g.text("", 0, " "); loopscoregroup(o, { if(o==player1 && highlightscore && (multiplayer(false) || demoplayback || players.length() > 1)) { g.pushlist(); g.background(0x808080, numgroups>1 ? 3 : 5); } const playermodelinfo &mdl = getplayermodelinfo(o); const char *icon = sg.team && m_teammode ? (isteam(player1->team, sg.team) ? mdl.blueicon : mdl.redicon) : mdl.ffaicon; g.text("", 0, icon); if(o==player1 && highlightscore && (multiplayer(false) || demoplayback || players.length() > 1)) g.poplist(); }); g.poplist(); if(sg.team && m_teammode) { g.pushlist(); // vertical if(sg.score>=10000) g.textf("%s: WIN", fgcolor, NULL, sg.team); else g.textf("%s: %d", fgcolor, NULL, sg.team, sg.score); g.pushlist(); // horizontal } if(!cmode || !cmode->hidefrags()) { g.pushlist(); g.strut(6); g.text("frags", fgcolor); loopscoregroup(o, g.textf("%d", 0xFFFFDD, NULL, o->frags)); g.poplist(); } if(multiplayer(false) || demoplayback) { if(showpj) { g.pushlist(); g.strut(6); g.text("pj", fgcolor); loopscoregroup(o, { if(o->state==CS_LAGGED) g.text("LAG", 0xFFFFDD); else g.textf("%d", 0xFFFFDD, NULL, o->plag); }); g.poplist(); } if(showping) { g.pushlist(); g.text("ping", fgcolor); g.strut(6); loopscoregroup(o, { fpsent *p = o->ownernum >= 0 ? getclient(o->ownernum) : o; if(!p) p = o; if(!showpj && p->state==CS_LAGGED) g.text("LAG", 0xFFFFDD); else g.textf("%d", 0xFFFFDD, NULL, p->ping); }); g.poplist(); } } g.pushlist(); g.text("name", fgcolor); g.strut(13); loopscoregroup(o, { int status = o->state!=CS_DEAD ? 0xFFFFDD : 0x606060; if(o->privilege) { status = o->privilege>=PRIV_ADMIN ? 0xFF8000 : 0x40FF80; if(o->state==CS_DEAD) status = (status>>1)&0x7F7F7F; } g.text(colorname(o), status); }); g.poplist(); if(showclientnum || player1->privilege>=PRIV_MASTER) { g.space(1); g.pushlist(); g.text("cn", fgcolor); loopscoregroup(o, g.textf("%d", 0xFFFFDD, NULL, o->clientnum)); g.poplist(); } if(sg.team && m_teammode) { g.poplist(); // horizontal g.poplist(); // vertical } g.poplist(); // horizontal g.poplist(); // vertical if(k+1privilege>=PRIV_MASTER) { g.pushlist(); g.pushlist(); g.text("spectator", 0xFFFF80, " "); loopv(spectators) { fpsent *o = spectators[i]; int status = 0xFFFFDD; if(o->privilege) status = o->privilege>=PRIV_ADMIN ? 0xFF8000 : 0x40FF80; if(o==player1 && highlightscore) { g.pushlist(); g.background(0x808080, 3); } g.text(colorname(o), status, "spectator"); if(o==player1 && highlightscore) g.poplist(); } g.poplist(); g.space(1); g.pushlist(); g.text("cn", 0xFFFF80); loopv(spectators) g.textf("%d", 0xFFFFDD, NULL, spectators[i]->clientnum); g.poplist(); g.poplist(); } else { g.textf("%d spectator%s", 0xFFFF80, " ", spectators.length(), spectators.length()!=1 ? "s" : ""); loopv(spectators) { if((i%3)==0) { g.pushlist(); g.text("", 0xFFFFDD, "spectator"); } fpsent *o = spectators[i]; int status = 0xFFFFDD; if(o->privilege) status = o->privilege>=PRIV_ADMIN ? 0xFF8000 : 0x40FF80; if(o==player1 && highlightscore) { g.pushlist(); g.background(0x808080); } g.text(colorname(o), status); if(o==player1 && highlightscore) g.poplist(); if(i+1 teleports; static const int TOTMFREQ = 14; const int NUMMONSTERTYPES = 7; const monstertype monstertypes[NUMMONSTERTYPES] = { { GUN_FIST, 4, 100, 3, 0, 100, 800, 50, 0, 5, S_PAINO, S_DIE, "A Butterfly", "butterfly", "butterfly"}, { GUN_BITE, 20, 800, 5, 0, 400, 1600, 100, 60, 4000, S_PAINO, S_DIE, "A Dragon", "rpg/characters/dragon", "Dragon"}, { GUN_FIST, 8, 800, 5, 0, 400, 1600, 100, 16, 4000, S_PAINO, S_DIE, "A Golem", "rpg/characters/golem", "golem"}, { GUN_FIST, 12, 200, 5, 0, 400, 1600, 100, 16, 800, S_PAINO, S_DIE, "A Grizzly", "rpg/characters/grizzly", "grizzly"}, { GUN_BITE, 25, 50, 5, 0, 400, 1600, 100, 2, 30, S_PAINO, S_DIE, "A Rat", "rpg/characters/rat", "rat"}, { GUN_FIST, 7, 150, 5, 0, 400, 1600, 100, 16, 200, S_PAINO, S_DIE, "A Snagon", "rpg/characters/snagon", "snagon"}, { GUN_BITE, 28, 80, 5, 0, 400, 1600, 100, 6, 150, S_PAINO, S_DIE, "A Wolf", "rpg/characters/wolf", "wolf"}, }; VAR(skill, 1, 3, 10); VAR(killsendsp, 0, 1, 1); bool monsterhurt; vec monsterhurtpos; struct monster : fpsent { int monsterstate; // one of M_*, M_NONE means human int mtype, tag; // see monstertypes table fpsent *enemy; // monster wants to kill this entity float targetyaw; // monster wants to look in this direction int trigger; // millis at which transition to another monsterstate takes place vec attacktarget; // delayed attacks int anger; // how many times already hit by fellow monster physent *stacked; vec stackpos; monster(int _type, int _yaw, int _tag, int _state, int _trigger, int _move) : monsterstate(_state), tag(_tag), stacked(NULL), stackpos(0, 0, 0) { type = ENT_AI; respawn(); if(_type>=NUMMONSTERTYPES || _type < 0) { conoutf(CON_WARN, "warning: unknown monster in spawn: %d", _type); _type = 0; } mtype = _type; const monstertype &t = monstertypes[mtype]; eyeheight = 8.0f; aboveeye = 7.0f; radius *= t.bscale/10.0f; xradius = yradius = radius; eyeheight *= t.bscale/10.0f; aboveeye *= t.bscale/10.0f; weight = t.weight; if(_state!=M_SLEEP) spawnplayer(this); trigger = lastmillis+_trigger; targetyaw = yaw = (float)_yaw; move = _move; enemy = player1; gunselect = t.gun; maxspeed = (float)t.speed*4; health = t.health; armour = 0; loopi(NUMGUNS) ammo[i] = 10000; pitch = 0; roll = 0; state = CS_ALIVE; anger = 0; copystring(name, t.name); } void normalize_yaw(float angle) { while(yawangle+180.0f) yaw -= 360.0f; } // monster AI is sequenced using transitions: they are in a particular state where // they execute a particular behaviour until the trigger time is hit, and then they // reevaluate their situation based on the current state, the environment etc., and // transition to the next state. Transition timeframes are parametrized by difficulty // level (skill), faster transitions means quicker decision making means tougher AI. void transition(int _state, int _moving, int n, int r) // n = at skill 0, n/2 = at skill 10, r = added random factor { monsterstate = _state; move = _moving; n = n*130/100; trigger = lastmillis+n-skill*(n/16)+rnd(r+1); } void monsteraction(int curtime) // main AI thinking routine, called every frame for every monster { if(enemy->state==CS_DEAD) { enemy = player1; anger = 0; } normalize_yaw(targetyaw); if(targetyaw>yaw) // slowly turn monster towards his target { yaw += curtime*0.5f; if(targetyawyaw) yaw = targetyaw; } float dist = enemy->o.dist(o); if(monsterstate!=M_SLEEP) pitch = asin((enemy->o.z - o.z) / dist) / RAD; if(blocked) // special case: if we run into scenery { blocked = false; if(!rnd(20000/monstertypes[mtype].speed)) // try to jump over obstackle (rare) { jumping = true; } else if(triggero.x - o.x, enemy->o.y - o.y)/RAD; switch(monsterstate) { case M_PAIN: case M_ATTACKING: case M_SEARCH: if(triggero, target)) { transition(M_HOME, 1, 500, 200); playsound(S_GRUNT1+rnd(2), &o); } } break; } case M_AIMING: // this state is the delay between wanting to shoot and actually firing if(triggero, target)) // no visual contact anymore, let monster get as close as possible then search for player { transition(M_HOME, 1, 800, 500); } else { bool melee = false, longrange = false; switch(monstertypes[mtype].gun) { case GUN_BITE: case GUN_FIST: melee = true; break; case GUN_RIFLE: longrange = true; break; } // the closer the monster is the more likely he wants to shoot, if((!melee || dist<20) && !rnd(longrange ? (int)dist/12+1 : min((int)dist/12+1,6)) && enemy->state==CS_ALIVE) // get ready to fire { attacktarget = target; transition(M_AIMING, 0, monstertypes[mtype].lag, 10); } else // track player some more { transition(M_HOME, 1, monstertypes[mtype].rate, 0); } } } break; } if(move || maymove() || (stacked && (stacked->state!=CS_ALIVE || stackpos != stacked->o))) { vec pos = feetpos(); loopv(teleports) // equivalent of player entity touch, but only teleports are used { entity &e = *entities::ents[teleports[i]]; float dist = e.o.dist(pos); if(dist<16) entities::teleport(teleports[i], this); } if(physsteps > 0) stacked = NULL; moveplayer(this, 1, true); // use physics to move monster } } void monsterpain(int damage, fpsent *d) { if(d->type==ENT_AI) // a monster hit us { if(this!=d) // guard for RL guys shooting themselves :) { anger++; // don't attack straight away, first get angry int _anger = d->type==ENT_AI && mtype==((monster *)d)->mtype ? anger/2 : anger; if(_anger>=monstertypes[mtype].loyalty) enemy = d; // monster infight if very angry } } else if(d->type==ENT_PLAYER) // player hit us { anger = 0; enemy = d; monsterhurt = true; monsterhurtpos = o; } damageeffect(damage, this); if((health -= damage)<=0) { state = CS_DEAD; lastpain = lastmillis; playsound(monstertypes[mtype].diesound, &o); monsterkilled(); gibeffect(max(-health, 0), vel, this); defformatstring(id)("monster_dead_%d", tag); if(identexists(id)) execute(id); } else { transition(M_PAIN, 0, monstertypes[mtype].pain, 200); // in this state monster won't attack playsound(monstertypes[mtype].painsound, &o); } } }; void stackmonster(monster *d, physent *o) { d->stacked = o; d->stackpos = o->o; } int nummonsters(int tag, int state) { int n = 0; loopv(monsters) if(monsters[i]->tag==tag && (monsters[i]->state==CS_ALIVE ? state!=1 : state>=1)) n++; return n; } ICOMMAND(nummonsters, "ii", (int *tag, int *state), intret(nummonsters(*tag, *state))); void preloadmonsters() { loopi(NUMMONSTERTYPES) preloadmodel(monstertypes[i].mdlname); } vector monsters; int nextmonster, spawnremain, numkilled, monstertotal, mtimestart, remain; void spawnmonster() // spawn a random monster according to freq distribution in DMSP { int n = rnd(TOTMFREQ), type; for(int i = 0; ; i++) if((n -= monstertypes[i].freq)<0) { type = i; break; } monsters.add(new monster(type, rnd(360), 0, M_SEARCH, 1000, 1)); } void clearmonsters() // called after map start or when toggling edit mode to reset/spawn all monsters to initial state { removetrackedparticles(); removetrackeddynlights(); loopv(monsters) delete monsters[i]; cleardynentcache(); monsters.shrink(0); numkilled = 0; monstertotal = 0; spawnremain = 0; remain = 0; monsterhurt = false; if(m_dmsp) { nextmonster = mtimestart = lastmillis+10000; monstertotal = spawnremain = skill*10; } else if(m_classicsp) { mtimestart = lastmillis; loopv(entities::ents) { extentity &e = *entities::ents[i]; if(e.type!=MONSTER) continue; monster *m = new monster(e.attr[1], e.attr[0], e.attr[2], M_SLEEP, 100, 0); monsters.add(m); m->o = e.o; entinmap(m); updatedynentcache(m); monstertotal++; } } teleports.setsize(0); if(m_dmsp || m_classicsp) { loopv(entities::ents) if(entities::ents[i]->type==TELEPORT) teleports.add(i); } } void endsp(bool allkilled) { conoutf(CON_GAMEINFO, allkilled ? "\f2you have cleared the map!" : "\f2you reached the exit!"); monstertotal = 0; game::addmsg(N_FORCEINTERMISSION, "r"); } ICOMMAND(endsp, "", (), endsp(false)); void monsterkilled() { numkilled++; player1->frags = numkilled; remain = monstertotal-numkilled; if(remain>0 && remain<=5) conoutf(CON_GAMEINFO, "\f2only %d monster(s) remaining", remain); } void updatemonsters(int curtime) { if(m_dmsp && spawnremain && lastmillis>nextmonster) { if(spawnremain--==monstertotal) { conoutf(CON_GAMEINFO, "\f2The invasion has begun!"); playsound(S_V_FIGHT); } nextmonster = lastmillis+1000; spawnmonster(); } if(killsendsp && monstertotal && !spawnremain && numkilled==monstertotal) endsp(true); bool monsterwashurt = monsterhurt; loopv(monsters) { if(monsters[i]->state==CS_ALIVE) monsters[i]->monsteraction(curtime); else if(monsters[i]->state==CS_DEAD) { if(lastmillis-monsters[i]->lastpain<2000) { //monsters[i]->move = 0; monsters[i]->move = monsters[i]->strafe = 0; moveplayer(monsters[i], 1, true); } } } if(monsterwashurt) monsterhurt = false; } void rendermonsters() { loopv(monsters) { monster &m = *monsters[i]; if(m.state!=CS_DEAD || lastmillis-m.lastpain<10000) { modelattach vwep[2]; vwep[0] = modelattach("tag_weapon", monstertypes[m.mtype].vwepname, ANIM_VWEP_IDLE|ANIM_LOOP, 0); float fade = 1; if(m.state==CS_DEAD) fade -= clamp(float(lastmillis - (m.lastpain + 9000))/1000, 0.0f, 1.0f); renderclient(&m, monstertypes[m.mtype].mdlname, vwep, 0, m.monsterstate==M_ATTACKING ? -ANIM_ATTACK1 : 0, 300, m.lastaction, m.lastpain, fade); } } } void suicidemonster(monster *m) { m->monsterpain(400, player1); } void hitmonster(int damage, monster *m, fpsent *at, const vec &vel, int gun) { m->monsterpain(damage, at); } void spsummary(int accuracy) { conoutf(CON_GAMEINFO, "\f2--- single player time score: ---"); int pen, score = 0; pen = ((lastmillis-maptime)*100)/(1000*getvar("gamespeed")); score += pen; if(pen) conoutf(CON_GAMEINFO, "\f2time taken: %d seconds (%d simulated seconds)", pen, (lastmillis-maptime)/1000); pen = player1->deaths*60; score += pen; if(pen) conoutf(CON_GAMEINFO, "\f2time penalty for %d deaths (1 minute each): %d seconds", player1->deaths, pen); pen = remain*10; score += pen; if(pen) conoutf(CON_GAMEINFO, "\f2time penalty for %d monsters remaining (10 seconds each): %d seconds", remain, pen); pen = (10-skill)*20; score += pen; if(pen) conoutf(CON_GAMEINFO, "\f2time penalty for lower skill level (20 seconds each): %d seconds", pen); pen = 100-accuracy; score += pen; if(pen) conoutf(CON_GAMEINFO, "\f2time penalty for missed shots (1 second each %%): %d seconds", pen); defformatstring(aname)("bestscore_%s", getclientmap()); const char *bestsc = getalias(aname); int bestscore = *bestsc ? parseint(bestsc) : score; if(score hits; VARP(maxdebris, 10, 25, 1000); VARP(maxbarreldebris, 5, 10, 1000); ICOMMAND(getweapon, "", (), intret(player1->gunselect)); void gunselect(int gun, fpsent *d) { if(gun!=d->gunselect) { addmsg(N_GUNSELECT, "rci", d, gun); playsound(S_WEAPLOAD, &d->o); } d->gunselect = gun; } void nextweapon(int dir, bool force = false) { if(player1->state!=CS_ALIVE) return; dir = (dir < 0 ? NUMGUNS-1 : 1); int gun = player1->gunselect; loopi(NUMGUNS) { gun = (gun + dir)%NUMGUNS; if(force || player1->ammo[gun]) break; } if(gun != player1->gunselect) gunselect(gun, player1); else playsound(S_NOAMMO); } ICOMMAND(nextweapon, "ii", (int *dir, int *force), nextweapon(*dir, *force!=0)); int getweapon(const char *name) { const char *abbrevs[] = { "FI", "SG", "CG", "RL", "RI", "GL", "PI" }; if(isdigit(name[0])) return parseint(name); else loopi(sizeof(abbrevs)/sizeof(abbrevs[0])) if(!strcasecmp(abbrevs[i], name)) return i; return -1; } void setweapon(const char *name, bool force = false) { int gun = getweapon(name); if(player1->state!=CS_ALIVE || gunGUN_PISTOL) return; if(force || player1->ammo[gun]) gunselect(gun, player1); else playsound(S_NOAMMO); } ICOMMAND(setweapon, "si", (char *name, int *force), setweapon(name, *force!=0)); void cycleweapon(int numguns, int *guns, bool force = false) { if(numguns<=0 || player1->state!=CS_ALIVE) return; int offset = 0; loopi(numguns) if(guns[i] == player1->gunselect) { offset = i+1; break; } loopi(numguns) { int gun = guns[(i+offset)%numguns]; if(gun>=0 && gunammo[gun])) { gunselect(gun, player1); return; } } playsound(S_NOAMMO); } ICOMMAND(cycleweapon, "V", (tagval *args, int numargs), { int numguns = min(numargs, 7); int guns[7]; loopi(numguns) guns[i] = getweapon(args[i].getstr()); cycleweapon(numguns, guns); }); void weaponswitch(fpsent *d) { if(d->state!=CS_ALIVE) return; int s = d->gunselect; if (s!=GUN_CG && d->ammo[GUN_CG]) s = GUN_CG; else if(s!=GUN_RL && d->ammo[GUN_RL]) s = GUN_RL; else if(s!=GUN_SG && d->ammo[GUN_SG]) s = GUN_SG; else if(s!=GUN_RIFLE && d->ammo[GUN_RIFLE]) s = GUN_RIFLE; else if(s!=GUN_GL && d->ammo[GUN_GL]) s = GUN_GL; else if(s!=GUN_PISTOL && d->ammo[GUN_PISTOL]) s = GUN_PISTOL; else s = GUN_FIST; gunselect(s, d); } ICOMMAND(weapon, "V", (tagval *args, int numargs), { if(player1->state!=CS_ALIVE) return; loopi(7) { const char *name = i < numargs ? args[i].getstr() : ""; if(name[0]) { int gun = getweapon(name); if(gun >= GUN_FIST && gun <= GUN_PISTOL && gun != player1->gunselect && player1->ammo[gun]) { gunselect(gun, player1); return; } } else { weaponswitch(player1); return; } } playsound(S_NOAMMO); }); void offsetray(const vec &from, const vec &to, int spread, float range, vec &dest) { vec offset; do offset = vec(rndscale(1), rndscale(1), rndscale(1)).sub(0.5f); while(offset.squaredlen() > 0.5f*0.5f); offset.mul((to.dist(from)/1024)*spread); offset.z /= 2; dest = vec(offset).add(to); vec dir = vec(dest).sub(from).normalize(); raycubepos(from, dir, dest, range, RAY_CLIPMAT|RAY_ALPHAPOLY); } void createrays(const vec &from, const vec &to) // create random spread of rays for the shotgun { loopi(SGRAYS) offsetray(from, to, guns[GUN_SG].spread, guns[GUN_SG].range, sg[i]); } enum { BNC_GRENADE, BNC_GIBS, BNC_DEBRIS, BNC_BARRELDEBRIS }; struct bouncer : physent { int lifetime, bounces; float lastyaw, roll; bool local; fpsent *owner; int bouncetype, variant; vec offset; int offsetmillis; int id; entitylight light; bouncer() : bounces(0), roll(0), variant(0) { type = ENT_BOUNCE; collidetype = COLLIDE_AABB; } }; vector bouncers; vec hudgunorigin(int gun, const vec &from, const vec &to, fpsent *d); void newbouncer(const vec &from, const vec &to, bool local, int id, fpsent *owner, int type, int lifetime, int speed, entitylight *light = NULL) { bouncer &bnc = *bouncers.add(new bouncer); bnc.o = from; bnc.radius = bnc.xradius = bnc.yradius = type==BNC_DEBRIS ? 0.5f : 1.5f; bnc.eyeheight = bnc.radius; bnc.aboveeye = bnc.radius; bnc.lifetime = lifetime; bnc.local = local; bnc.owner = owner; bnc.bouncetype = type; bnc.id = local ? lastmillis : id; if(light) bnc.light = *light; switch(type) { case BNC_GRENADE: bnc.collidetype = COLLIDE_ELLIPSE; break; case BNC_DEBRIS: case BNC_BARRELDEBRIS: bnc.variant = rnd(4); break; case BNC_GIBS: bnc.variant = rnd(3); break; } vec dir(to); dir.sub(from).normalize(); bnc.vel = dir; bnc.vel.mul(speed); avoidcollision(&bnc, dir, owner, 0.1f); if(type==BNC_GRENADE) { bnc.offset = hudgunorigin(GUN_GL, from, to, owner); if(owner==hudplayer() && !isthirdperson()) bnc.offset.sub(owner->o).rescale(16).add(owner->o); } else bnc.offset = from; bnc.offset.sub(bnc.o); bnc.offsetmillis = OFFSETMILLIS; bnc.resetinterp(); } void bounced(physent *d, const vec &surface) { if(d->type != ENT_BOUNCE) return; bouncer *b = (bouncer *)d; if(b->bouncetype != BNC_GIBS || b->bounces >= 2) return; b->bounces++; adddecal(DECAL_WATERBURN, vec(b->o).sub(vec(surface).mul(b->radius)), surface, 2.96f/b->bounces, bvec(0x60, 0xFF, 0xFF), rnd(4)); } void updatebouncers(int time) { loopv(bouncers) { bouncer &bnc = *bouncers[i]; if(bnc.bouncetype==BNC_GRENADE && bnc.vel.magnitude() > 50.0f) { vec pos(bnc.o); pos.add(vec(bnc.offset).mul(bnc.offsetmillis/float(OFFSETMILLIS))); regular_particle_splash(PART_SMOKE, 1, 150, pos, 0x00B2EE, 2.4f, 50, -20); } vec old(bnc.o); bool stopped = false; if(bnc.bouncetype==BNC_GRENADE) stopped = bounce(&bnc, 0.6f, 0.5f) || (bnc.lifetime -= time)<0; else { // cheaper variable rate physics for debris, gibs, etc. for(int rtime = time; rtime > 0;) { int qtime = min(30, rtime); rtime -= qtime; if((bnc.lifetime -= qtime)<0 || bounce(&bnc, qtime/1000.0f, 0.6f, 0.5f)) { stopped = true; break; } } } if(stopped) { if(bnc.bouncetype==BNC_GRENADE) { int qdam = guns[GUN_GL].damage*(bnc.owner->quadmillis ? 4 : 1); hits.setsize(0); explode(bnc.local, bnc.owner, bnc.o, NULL, qdam, GUN_GL); adddecal(DECAL_WATERBURN, bnc.o, vec(0, 0, 1), RL_DAMRAD/2); if(bnc.local) addmsg(N_EXPLODE, "rci3iv", bnc.owner, lastmillis-maptime, GUN_GL, bnc.id-maptime, hits.length(), hits.length()*sizeof(hitmsg)/sizeof(int), hits.getbuf()); } delete bouncers.remove(i--); } else { bnc.roll += old.sub(bnc.o).magnitude()/(4*RAD); bnc.offsetmillis = max(bnc.offsetmillis-time, 0); } } } void removebouncers(fpsent *owner) { loopv(bouncers) if(bouncers[i]->owner==owner) { delete bouncers[i]; bouncers.remove(i--); } } void clearbouncers() { bouncers.deletecontents(); } struct projectile { vec dir, o, to, offset; float speed; fpsent *owner; int gun; bool local; int offsetmillis; int id; entitylight light; }; vector projs; void clearprojectiles() { projs.shrink(0); } void newprojectile(const vec &from, const vec &to, float speed, bool local, int id, fpsent *owner, int gun) { projectile &p = projs.add(); p.dir = vec(to).sub(from).normalize(); p.o = from; p.to = to; p.offset = hudgunorigin(gun, from, to, owner); p.offset.sub(from); p.speed = speed; p.local = local; p.owner = owner; p.gun = gun; p.offsetmillis = OFFSETMILLIS; p.id = local ? lastmillis : id; } void removeprojectiles(fpsent *owner) { // can't use loopv here due to strange GCC optimizer bug int len = projs.length(); loopi(len) if(projs[i].owner==owner) { projs.remove(i--); len--; } } VARP(blood, 0, 1, 1); void damageeffect(int damage, fpsent *d, bool thirdperson) { vec p = d->o; p.z += 0.6f*(d->eyeheight + d->aboveeye) - d->eyeheight; if(blood) particle_splash(PART_WATERLEAK, damage/10, 1000, p, 0xf70000, 2.96f); if(thirdperson) { defformatstring(ds)("%d", damage); particle_textcopy(d->abovehead(), ds, PART_TEXT, 2000, 0x00B2EE, 4.0f, -8); } } void spawnbouncer(const vec &p, const vec &vel, fpsent *d, int type, entitylight *light = NULL) { vec to(rnd(100)-50, rnd(100)-50, rnd(100)-50); if(to.iszero()) to.z += 1; to.normalize(); to.add(p); newbouncer(p, to, true, 0, d, type, rnd(1000)+1000, rnd(100)+20, light); } void gibeffect(int damage, const vec &vel, fpsent *d) { // TODO gibbage models if(true || !blood || damage <= 0) return; vec from = d->abovehead(); loopi(min(damage/25, 40)+1) spawnbouncer(from, vel, d, BNC_GIBS); } void hit(int damage, dynent *d, fpsent *at, const vec &vel, int gun, float info1, int info2 = 1) { if(at==player1 && d!=at) { extern int hitsound; if(hitsound && lasthit != lastmillis) playsound(S_HIT); lasthit = lastmillis; } if(d->type==ENT_INANIMATE) { hitmovable(damage, (movable *)d, at, vel, gun); return; } fpsent *f = (fpsent *)d; f->lastpain = lastmillis; if(at->type==ENT_PLAYER && !isteam(at->team, f->team)) at->totaldamage += damage; if(f->type==ENT_AI || !m_mp(gamemode) || f==at) f->hitpush(damage, vel, at, gun); if(f->type==ENT_AI) hitmonster(damage, (monster *)f, at, vel, gun); else if(!m_mp(gamemode)) damaged(damage, f, at); else { hitmsg &h = hits.add(); h.target = f->clientnum; h.lifesequence = f->lifesequence; h.info1 = int(info1*DMF); h.info2 = info2; h.dir = f==at ? ivec(0, 0, 0) : ivec(int(vel.x*DNF), int(vel.y*DNF), int(vel.z*DNF)); if(at==player1) { damageeffect(damage, f); if(f==player1) { damageblend(damage); damagecompass(damage, at ? at->o : f->o); playsound(S_PAIN); } else playsound(S_PAIN, &f->o); } } } void hitpush(int damage, dynent *d, fpsent *at, vec &from, vec &to, int gun, int rays) { hit(damage, d, at, vec(to).sub(from).normalize(), gun, from.dist(to), rays); } float projdist(dynent *o, vec &dir, const vec &v) { vec middle = o->o; middle.z += (o->aboveeye-o->eyeheight)/2; float dist = middle.dist(v, dir); dir.div(dist); if(dist<0) dist = 0; return dist; } void radialeffect(dynent *o, const vec &v, int qdam, fpsent *at, int gun) { if(o->state!=CS_ALIVE) return; vec dir; float dist = projdist(o, dir, v); if(disto==v ? vec(0, 0, 0) : vec(owner->o).sub(v).normalize(), debrisorigin(v); if(gun==GUN_RL) debrisorigin.add(vec(debrisvel).mul(8)); //TODO gibbage models if(false && numdebris) { entitylight light; lightreaching(debrisorigin, light.color, light.dir); loopi(numdebris) spawnbouncer(debrisorigin, debrisvel, owner, gun==GUN_BARREL ? BNC_BARRELDEBRIS : BNC_DEBRIS, &light); } if(!local) return; loopi(numdynents()) { dynent *o = iterdynents(i); if(o==safe) continue; radialeffect(o, v, damage, owner, gun); } } void projsplash(projectile &p, vec &v, dynent *safe, int damage) { if(guns[p.gun].part) { particle_splash(PART_SPARK, 100, 200, v, 0x00B2EE, 0.24f); playsound(S_FEXPLODE, &v); // no push? } else { explode(p.local, p.owner, v, safe, damage, GUN_RL); adddecal(DECAL_WATERBURN, v, vec(p.dir).neg(), RL_DAMRAD/2); } } void explodeeffects(int gun, fpsent *d, bool local, int id) { if(local) return; switch(gun) { case GUN_RL: loopv(projs) { projectile &p = projs[i]; if(p.gun == gun && p.owner == d && p.id == id && !p.local) { vec pos(p.o); pos.add(vec(p.offset).mul(p.offsetmillis/float(OFFSETMILLIS))); explode(p.local, p.owner, pos, NULL, 0, GUN_RL); adddecal(DECAL_WATERBURN, pos, vec(p.dir).neg(), RL_DAMRAD/2); projs.remove(i); break; } } break; case GUN_GL: loopv(bouncers) { bouncer &b = *bouncers[i]; if(b.bouncetype == BNC_GRENADE && b.owner == d && b.id == id && !b.local) { vec pos(b.o); pos.add(vec(b.offset).mul(b.offsetmillis/float(OFFSETMILLIS))); explode(b.local, b.owner, pos, NULL, 0, GUN_GL); adddecal(DECAL_WATERBURN, pos, vec(0, 0, 1), RL_DAMRAD/2); delete bouncers.remove(i); break; } } break; default: break; } } bool projdamage(dynent *o, projectile &p, vec &v, int qdam) { if(o->state!=CS_ALIVE) return false; if(!intersect(o, p.o, v)) return false; projsplash(p, v, o, qdam); vec dir; projdist(o, dir, v); hit(qdam, o, p.owner, dir, p.gun, 0); return true; } void updateprojectiles(int time) { loopv(projs) { projectile &p = projs[i]; p.offsetmillis = max(p.offsetmillis-time, 0); int qdam = guns[p.gun].damage*(p.owner->quadmillis ? 4 : 1); if(p.owner->type==ENT_AI) qdam /= MONSTERDAMAGEFACTOR; vec v; float dist = p.to.dist(p.o, v); float dtime = dist*1000/p.speed; if(time > dtime) dtime = time; v.mul(time/dtime); v.add(p.o); bool exploded = false; hits.setsize(0); if(p.local) { loopj(numdynents()) { dynent *o = iterdynents(j); if(p.owner==o || o->o.reject(v, 10.0f)) continue; if(projdamage(o, p, v, qdam)) { exploded = true; break; } } } if(!exploded) { if(dist<4) { if(p.o!=p.to) // if original target was moving, reevaluate endpoint { if(raycubepos(p.o, p.dir, p.to, 0, RAY_CLIPMAT|RAY_ALPHAPOLY)>=4) continue; } projsplash(p, v, NULL, qdam); exploded = true; } else { vec pos(v); pos.add(vec(p.offset).mul(p.offsetmillis/float(OFFSETMILLIS))); if(guns[p.gun].part) { regular_particle_splash(PART_SMOKE, 2, 300, pos, 0x404040, 0.6f, 150, -20); int color = 0xFFFFFF; switch(guns[p.gun].part) { case PART_FIREBALL1: color = 0x00B2EE; break; } particle_splash(guns[p.gun].part, 1, 1, pos, color, 4.8f, 150, 20); } else regular_particle_splash(PART_SMOKE, 2, 300, pos, 0x00B2EE, 2.4f, 50, -20); } } if(exploded) { if(p.local) addmsg(N_EXPLODE, "rci3iv", p.owner, lastmillis-maptime, p.gun, p.id-maptime, hits.length(), hits.length()*sizeof(hitmsg)/sizeof(int), hits.getbuf()); projs.remove(i--); } else p.o = v; } } extern int chainsawhudgun; VARP(muzzleflash, 0, 1, 1); VARP(muzzlelight, 0, 1, 1); void shoteffects(int gun, const vec &from, const vec &to, fpsent *d, bool local, int id, int prevaction) // create visual effect from a shot { int sound = guns[gun].sound, pspeed = 25; switch(gun) { case GUN_FIST: if(d->type==ENT_PLAYER && chainsawhudgun) sound = S_CHAINSAW_ATTACK; break; case GUN_SG: { if(!local) createrays(from, to); if(muzzleflash && d->muzzle.x >= 0) particle_flare(d->muzzle, d->muzzle, 200, PART_MUZZLE_FLASH3, 0xFFFFFF, .75f, d); loopi(SGRAYS) { particle_splash(PART_SPARK, 20, 250, sg[i], 0x00B2EE, 0.24f); particle_flare(hudgunorigin(gun, from, sg[i], d), sg[i], 300, PART_STREAK, 0x00B2EE, 0.28f); if(!local) adddecal(DECAL_RIPPLE, sg[i], vec(from).sub(sg[i]).normalize(), 2.0f); } if(muzzlelight) adddynlight(hudgunorigin(gun, d->o, to, d), 30, vec(0.5f, 0.375f, 0.25f), 100, 100, DL_FLASH, 0, vec(0, 0, 0), d); break; } case GUN_CG: case GUN_PISTOL: { particle_splash(PART_SPARK, 200, 250, to, 0x00B2EE, 0.24f); particle_flare(hudgunorigin(gun, from, to, d), to, 600, PART_STREAK, 0x00B2EE, 0.28f); if(muzzleflash && d->muzzle.x >= 0) particle_flare(d->muzzle, d->muzzle, gun==GUN_CG ? 100 : 200, PART_MUZZLE_FLASH1, 0xFFFFFF, gun==GUN_CG ? .25f : .25f, d); if(!local) adddecal(DECAL_RIPPLE, to, vec(from).sub(to).normalize(), 2.0f); if(muzzlelight) adddynlight(hudgunorigin(gun, d->o, to, d), gun==GUN_CG ? 30 : 15, vec(0.5f, 0.375f, 0.25f), gun==GUN_CG ? 50 : 100, gun==GUN_CG ? 50 : 100, DL_FLASH, 0, vec(0, 0, 0), d); break; } case GUN_RL: if(muzzleflash && d->muzzle.x >= 0) particle_flare(d->muzzle, d->muzzle, 250, PART_MUZZLE_FLASH2, 0xFFFFFF, 1.0f, d); case GUN_FIREBALL: case GUN_ICEBALL: case GUN_SLIMEBALL: pspeed = guns[gun].projspeed*4; if(d->type==ENT_AI) pspeed /= 2; newprojectile(from, to, (float)pspeed, local, id, d, gun); break; case GUN_GL: { float dist = from.dist(to); vec up = to; up.z += dist/8; if(muzzleflash && d->muzzle.x >= 0) particle_flare(d->muzzle, d->muzzle, 200, PART_MUZZLE_FLASH2, 0xFFFFFF, .5f, d); if(muzzlelight) adddynlight(hudgunorigin(gun, d->o, to, d), 20, vec(0.5f, 0.375f, 0.25f), 100, 100, DL_FLASH, 0, vec(0, 0, 0), d); newbouncer(from, up, local, id, d, BNC_GRENADE, 1500, guns[GUN_GL].projspeed); break; } case GUN_RIFLE: particle_splash(PART_SPARK, 200, 250, to, 0x00B2EE, 0.24f); particle_trail(PART_SMOKE, 500, hudgunorigin(gun, from, to, d), to, 0x00B2EE, 0.6f, 20); if(muzzleflash && d->muzzle.x >= 0) particle_flare(d->muzzle, d->muzzle, 150, PART_MUZZLE_FLASH3, 0xFFFFFF, 1.25f, d); if(!local) adddecal(DECAL_RIPPLE, to, vec(from).sub(to).normalize(), 3.0f); if(muzzlelight) adddynlight(hudgunorigin(gun, d->o, to, d), 25, vec(0.5f, 0.375f, 0.25f), 75, 75, DL_FLASH, 0, vec(0, 0, 0), d); break; } bool looped = false; if(d->attacksound >= 0 && d->attacksound != sound) d->stopattacksound(); if(d->idlesound >= 0) d->stopidlesound(); switch(sound) { case S_CHAINSAW_ATTACK: if(d->attacksound >= 0) looped = true; d->attacksound = sound; d->attackchan = playsound(sound, d==hudplayer() ? NULL : &d->o, NULL, -1, 100, d->attackchan); break; default: playsound(sound, d==hudplayer() ? NULL : &d->o); break; } if(d->quadmillis && lastmillis-prevaction>200 && !looped) playsound(S_ITEMPUP, d==hudplayer() ? NULL : &d->o); } void particletrack(physent *owner, vec &o, vec &d) { if(owner->type!=ENT_PLAYER && owner->type!=ENT_AI) return; fpsent *pl = (fpsent *)owner; if(pl->muzzle.x < 0 || pl->lastattackgun != pl->gunselect) 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, vec &hud) { if(owner->type!=ENT_PLAYER && owner->type!=ENT_AI) return; fpsent *pl = (fpsent *)owner; if(pl->muzzle.x < 0 || pl->lastattackgun != pl->gunselect) return; o = pl->muzzle; hud = owner == hudplayer() ? vec(pl->o).add(vec(0, 0, 2)) : pl->muzzle; } float intersectdist = 1e16f; bool intersect(dynent *d, const vec &from, const vec &to, float &dist) // if lineseg hits entity bounding box { 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, fpsent *at, float &bestdist) { dynent *best = NULL; bestdist = 1e16f; loopi(numdynents()) { dynent *o = iterdynents(i); if(o==at || o->state!=CS_ALIVE) continue; float dist; if(!intersect(o, from, to, dist)) continue; if(distgunselect].damage; if(d->quadmillis) qdam *= 4; if(d->type==ENT_AI) qdam /= MONSTERDAMAGEFACTOR; dynent *o; float dist; if(d->gunselect==GUN_SG) { dynent *hits[SGRAYS]; loopi(SGRAYS) { if((hits[i] = intersectclosest(from, sg[i], d, dist))) shorten(from, sg[i], dist); else adddecal(DECAL_RIPPLE, sg[i], vec(from).sub(sg[i]).normalize(), 2.0f); } loopi(SGRAYS) if(hits[i]) { o = hits[i]; hits[i] = NULL; int numhits = 1; for(int j = i+1; j < SGRAYS; j++) if(hits[j] == o) { hits[j] = NULL; numhits++; } hitpush(numhits*qdam, o, d, from, to, d->gunselect, numhits); } } else if((o = intersectclosest(from, to, d, dist))) { shorten(from, to, dist); hitpush(qdam, o, d, from, to, d->gunselect, 1); } else if(d->gunselect!=GUN_FIST && d->gunselect!=GUN_BITE) adddecal(DECAL_RIPPLE, to, vec(from).sub(to).normalize(), d->gunselect==GUN_RIFLE ? 3.0f : 2.0f); } void shoot(fpsent *d, const vec &targ) { int prevaction = d->lastaction, attacktime = lastmillis-prevaction; if(attacktimegunwait) return; d->gunwait = 0; if((d==player1 || d->ai) && !d->attacking) return; d->lastaction = lastmillis; d->lastattackgun = d->gunselect; if(!d->ammo[d->gunselect]) { if(d==player1) { msgsound(S_NOAMMO, d); d->gunwait = 600; d->lastattackgun = -1; weaponswitch(d); } return; } if(d->gunselect) d->ammo[d->gunselect]--; vec from = d->o; vec to = targ; vec unitv; float dist = to.dist(from, unitv); unitv.div(dist); vec kickback(unitv); kickback.mul(guns[d->gunselect].kickamount*-2.5f); d->vel.add(kickback); float shorten = 0; if(guns[d->gunselect].range && dist > guns[d->gunselect].range) shorten = guns[d->gunselect].range; float barrier = raycube(d->o, unitv, dist, RAY_CLIPMAT|RAY_ALPHAPOLY); if(barrier > 0 && barrier < dist && (!shorten || barrier < shorten)) shorten = barrier; if(shorten) to = vec(unitv).mul(shorten).add(from); if(d->gunselect == GUN_SG) createrays(from, to); else if(guns[d->gunselect].spread) offsetray(from, to, guns[d->gunselect].spread, guns[d->gunselect].range, to); hits.setsize(0); if(!guns[d->gunselect].projspeed) raydamage(from, to, d); shoteffects(d->gunselect, from, to, d, true, 0, prevaction); if(d==player1 || d->ai) { addmsg(N_SHOOT, "rci2i6iv", d, lastmillis-maptime, d->gunselect, (int)(from.x*DMF), (int)(from.y*DMF), (int)(from.z*DMF), (int)(to.x*DMF), (int)(to.y*DMF), (int)(to.z*DMF), hits.length(), hits.length()*sizeof(hitmsg)/sizeof(int), hits.getbuf()); } d->gunwait = guns[d->gunselect].attackdelay; if(d->gunselect == GUN_PISTOL && d->ai) d->gunwait += int(d->gunwait*(((101-d->skill)+rnd(111-d->skill))/100.f)); d->totalshots += guns[d->gunselect].damage*(d->quadmillis ? 4 : 1)*(d->gunselect==GUN_SG ? SGRAYS : 1); } void adddynlights() { entities::adddynlights(); loopv(projs) { projectile &p = projs[i]; if(p.gun!=GUN_RL) continue; vec pos(p.o); pos.add(vec(p.offset).mul(p.offsetmillis/float(OFFSETMILLIS))); adddynlight(pos, RL_DAMRAD/2, vec(1, 0.75f, 0.5f)); } loopv(bouncers) { bouncer &bnc = *bouncers[i]; if(bnc.bouncetype!=BNC_GRENADE) continue; vec pos(bnc.o); pos.add(vec(bnc.offset).mul(bnc.offsetmillis/float(OFFSETMILLIS))); adddynlight(pos, 8, vec(0.25f, 1, 1)); } } static const char * const projnames[2] = { "projectiles/grenade", "projectiles/rocket" }; static const char * const gibnames[3] = { "gibs/gib01", "gibs/gib02", "gibs/gib03" }; static const char * const debrisnames[4] = { "debris/debris01", "debris/debris02", "debris/debris03", "debris/debris04" }; static const char * const barreldebrisnames[4] = { "barreldebris/debris01", "barreldebris/debris02", "barreldebris/debris03", "barreldebris/debris04" }; void preloadbouncers() { loopi(sizeof(projnames)/sizeof(projnames[0])) preloadmodel(projnames[i]); //FIXME reenable when we have gibs // loopi(sizeof(gibnames)/sizeof(gibnames[0])) preloadmodel(gibnames[i]); // loopi(sizeof(debrisnames)/sizeof(debrisnames[0])) preloadmodel(debrisnames[i]); // loopi(sizeof(barreldebrisnames)/sizeof(barreldebrisnames[0])) preloadmodel(barreldebrisnames[i]); } void renderbouncers() { float yaw, pitch; loopv(bouncers) { bouncer &bnc = *bouncers[i]; vec pos(bnc.o); pos.add(vec(bnc.offset).mul(bnc.offsetmillis/float(OFFSETMILLIS))); vec vel(bnc.vel); if(vel.magnitude() <= 25.0f) yaw = bnc.lastyaw; else { vectoyawpitch(vel, yaw, pitch); yaw += 90; bnc.lastyaw = yaw; } pitch = -bnc.roll; if(bnc.bouncetype==BNC_GRENADE) rendermodel(&bnc.light, "projectiles/grenade", ANIM_MAPMODEL|ANIM_LOOP, pos, yaw, pitch, MDL_CULL_VFC|MDL_CULL_OCCLUDED|MDL_LIGHT|MDL_LIGHT_FAST|MDL_DYNSHADOW); else { const char *mdl = NULL; int cull = MDL_CULL_VFC|MDL_CULL_DIST|MDL_CULL_OCCLUDED; float fade = 1; if(bnc.lifetime < 250) fade = bnc.lifetime/250.0f; switch(bnc.bouncetype) { case BNC_GIBS: mdl = gibnames[bnc.variant]; cull |= MDL_LIGHT|MDL_LIGHT_FAST|MDL_DYNSHADOW; break; case BNC_DEBRIS: mdl = debrisnames[bnc.variant]; break; case BNC_BARRELDEBRIS: mdl = barreldebrisnames[bnc.variant]; break; default: continue; } rendermodel(&bnc.light, mdl, ANIM_MAPMODEL|ANIM_LOOP, pos, yaw, pitch, cull, NULL, NULL, 0, 0, fade); } } } void renderprojectiles() { float yaw, pitch; loopv(projs) { projectile &p = projs[i]; if(p.gun!=GUN_RL) continue; float dist = min(p.o.dist(p.to)/32.0f, 1.0f); vec pos = vec(p.o).add(vec(p.offset).mul(dist*p.offsetmillis/float(OFFSETMILLIS))), v = dist < 1e-6f ? p.dir : vec(p.to).sub(pos).normalize(); // the amount of distance in front of the smoke trail needs to change if the model does vectoyawpitch(v, yaw, pitch); yaw += 90; v.mul(3); v.add(pos); rendermodel(&p.light, "projectiles/rocket", ANIM_MAPMODEL|ANIM_LOOP, v, yaw, pitch, MDL_CULL_VFC|MDL_CULL_OCCLUDED|MDL_LIGHT|MDL_LIGHT_FAST); } } void checkattacksound(fpsent *d, bool local) { int gun = -1; switch(d->attacksound) { case S_CHAINSAW_ATTACK: if(chainsawhudgun) gun = GUN_FIST; break; default: return; } if(gun >= 0 && gun < NUMGUNS && d->clientnum >= 0 && d->state == CS_ALIVE && d->lastattackgun == gun && lastmillis - d->lastaction < guns[gun].attackdelay + 50) { d->attackchan = playsound(d->attacksound, local ? NULL : &d->o, NULL, -1, -1, d->attackchan); if(d->attackchan < 0) d->attacksound = -1; } else d->stopattacksound(); } void checkidlesound(fpsent *d, bool local) { int sound = -1, radius = 0; if(d->clientnum >= 0 && d->state == CS_ALIVE) switch(d->gunselect) { case GUN_FIST: if(chainsawhudgun && d->attacksound < 0) { sound = S_CHAINSAW_IDLE; radius = 50; } break; } if(d->idlesound != sound) { if(d->idlesound >= 0) d->stopidlesound(); if(sound >= 0) { d->idlechan = playsound(sound, local ? NULL : &d->o, NULL, -1, 100, d->idlechan, radius); if(d->idlechan >= 0) d->idlesound = sound; } } else if(sound >= 0) { d->idlechan = playsound(sound, local ? NULL : &d->o, NULL, -1, -1, d->idlechan, radius); if(d->idlechan < 0) d->idlesound = -1; } } void removeweapons(fpsent *d) { removebouncers(d); removeprojectiles(d); } void updateweapons(int curtime) { updateprojectiles(curtime); if(player1->clientnum>=0 && player1->state==CS_ALIVE) shoot(player1, worldpos); // only shoot when connected to server updatebouncers(curtime); // need to do this after the player shoots so grenades don't end up inside player's BB next frame fpsent *following = followingplayer(); if(!following) following = player1; loopv(players) { fpsent *d = players[i]; checkattacksound(d, d==following); checkidlesound(d, d==following); } } void avoidweapons(ai::avoidset &obstacles, float radius) { loopv(projs) { projectile &p = projs[i]; obstacles.avoidnear(NULL, p.o.z + RL_DAMRAD + 1, p.o, radius + RL_DAMRAD); } loopv(bouncers) { bouncer &bnc = *bouncers[i]; if(bnc.bouncetype != BNC_GRENADE) continue; obstacles.avoidnear(NULL, bnc.o.z + RL_DAMRAD + 1, bnc.o, radius + RL_DAMRAD); } } }; sandboxgamemaker-2.8.2+dfsg/src/fpsgame/waterwars.txt0000644000175000017500000000064312047476455021722 0ustar bofh80bofh80Weapons * water pistol (default) * water bombs * super soaker - fires a constant stream (chaingun) we still need replacements for the following * rocket launcher * shotgun - super soaker burst fire mode? * rifle * melee power ups * rain coat - temporary invulnerability * dry clothes - reduces saturation * waterproofing salve - armour, washed away when attacked instead of saturating the player quad - keep as quad?sandboxgamemaker-2.8.2+dfsg/src/fpsgame/waypoint.cpp0000644000175000017500000006331012045412564021505 0ustar bofh80bofh80#include "game.h" extern selinfo sel; namespace ai { using namespace game; vector waypoints; bool clipped(const vec &o) { int material = lookupmaterial(o), clipmat = material&MATF_CLIP; return clipmat == MAT_CLIP || material&MAT_DEATH || (material&MATF_VOLUME) == MAT_LAVA; } int getweight(const vec &o) { vec pos = o; pos.z += ai::JUMPMIN; if(!insideworld(vec(pos.x, pos.y, min(pos.z, getworldsize() - 1e-3f)))) return -2; float dist = raycube(pos, vec(0, 0, -1), 0, RAY_CLIPMAT); int posmat = lookupmaterial(pos), weight = 1; if(isliquid(posmat&MATF_VOLUME)) weight *= 5; if(dist >= 0) { weight = int(dist/ai::JUMPMIN); pos.z -= clamp(dist-8.0f, 0.0f, pos.z); int trgmat = lookupmaterial(pos); if(trgmat&MAT_DEATH || (trgmat&MATF_VOLUME) == MAT_LAVA) weight *= 10; else if(isliquid(trgmat&MATF_VOLUME)) weight *= 2; } return weight; } enum { WPCACHE_STATIC = 0, WPCACHE_DYNAMIC, NUMWPCACHES }; struct wpcachenode { float split[2]; uint child[2]; int axis() const { return child[0]>>30; } int childindex(int which) const { return child[which]&0x3FFFFFFF; } bool isleaf(int which) const { return (child[1]&(1<<(30+which)))!=0; } }; struct wpcache { vector nodes; int firstwp, lastwp, maxdepth; vec bbmin, bbmax; wpcache() { clear(); } void clear() { nodes.setsize(0); firstwp = lastwp = -1; maxdepth = -1; bbmin = vec(1e16f, 1e16f, 1e16f); bbmax = vec(-1e16f, -1e16f, -1e16f); } void build(int first = -1, int last = -1) { if(last < 0) last = waypoints.length(); vector indices; for(int i = first; i < last; i++) { waypoint &w = waypoints[i]; indices.add(i); if(firstwp < 0) firstwp = i; float radius = WAYPOINTRADIUS; bbmin.min(vec(w.o).sub(radius)); bbmax.max(vec(w.o).add(radius)); } build(indices.getbuf(), indices.length(), bbmin, bbmax); } void build(int *indices, int numindices, const vec &vmin, const vec &vmax, int depth = 1) { int axis = 2; loopk(2) if(vmax[k] - vmin[k] > vmax[axis] - vmin[axis]) axis = k; vec leftmin(1e16f, 1e16f, 1e16f), leftmax(-1e16f, -1e16f, -1e16f), rightmin(1e16f, 1e16f, 1e16f), rightmax(-1e16f, -1e16f, -1e16f); float split = 0.5f*(vmax[axis] + vmin[axis]), splitleft = -1e16f, splitright = 1e16f; int left, right; for(left = 0, right = numindices; left < right;) { waypoint &w = waypoints[indices[left]]; float radius = WAYPOINTRADIUS; if(max(split - (w.o[axis]-radius), 0.0f) > max((w.o[axis]+radius) - split, 0.0f)) { ++left; splitleft = max(splitleft, w.o[axis]+radius); leftmin.min(vec(w.o).sub(radius)); leftmax.max(vec(w.o).add(radius)); } else { --right; swap(indices[left], indices[right]); splitright = min(splitright, w.o[axis]-radius); rightmin.min(vec(w.o).sub(radius)); rightmax.max(vec(w.o).add(radius)); } } if(!left || right==numindices) { leftmin = rightmin = vec(1e16f, 1e16f, 1e16f); leftmax = rightmax = vec(-1e16f, -1e16f, -1e16f); left = right = numindices/2; splitleft = -1e16f; splitright = 1e16f; loopi(numindices) { waypoint &w = waypoints[indices[i]]; float radius = WAYPOINTRADIUS; if(i < left) { splitleft = max(splitleft, w.o[axis]+radius); leftmin.min(vec(w.o).sub(radius)); leftmax.max(vec(w.o).add(radius)); } else { splitright = min(splitright, w.o[axis]-radius); rightmin.min(vec(w.o).sub(radius)); rightmax.max(vec(w.o).add(radius)); } } } int node = nodes.length(); nodes.add(); nodes[node].split[0] = splitleft; nodes[node].split[1] = splitright; if(left<=1) nodes[node].child[0] = (axis<<30) | (left>0 ? indices[0] : 0x3FFFFFFF); else { nodes[node].child[0] = (axis<<30) | (nodes.length()-node); if(left) build(indices, left, leftmin, leftmax, depth+1); } if(numindices-right<=1) nodes[node].child[1] = (1<<31) | (left<=1 ? 1<<30 : 0) | (numindices-right>0 ? indices[right] : 0x3FFFFFFF); else { nodes[node].child[1] = (left<=1 ? 1<<30 : 0) | (nodes.length()-node); if(numindices-right) build(&indices[right], numindices-right, rightmin, rightmax, depth+1); } maxdepth = max(maxdepth, depth); } } wpcaches[NUMWPCACHES]; static int invalidatedwpcaches = 0, clearedwpcaches = (1<= 1000) { numinvalidatewpcaches = 0; invalidatedwpcaches = (1<= wpcaches[i].firstwp && wp <= wpcaches[i].lastwp) || i+1 >= NUMWPCACHES) { invalidatedwpcaches |= 1< 0 ? wpcaches[i-1].lastwp+1 : 0, i+1 >= NUMWPCACHES || wpcaches[i+1].maxdepth < 0 ? -1 : wpcaches[i+1].firstwp); clearedwpcaches = 0; lastwpcache = waypoints.length(); wpavoid.clear(); loopv(waypoints) if(waypoints[i].weight < 0) wpavoid.avoidnear(NULL, waypoints[i].o.z + WAYPOINTRADIUS, waypoints[i].o, WAYPOINTRADIUS); } struct wpcachestack { wpcachenode *node; float tmin, tmax; }; vector wpcachestack; int closestwaypoint(const vec &pos, float mindist, bool links, fpsent *d) { if(waypoints.empty()) return -1; if(clearedwpcaches) buildwpcache(); #define CHECKCLOSEST(index) do { \ int n = (index); \ const waypoint &w = waypoints[n]; \ if(!links || w.links[0]) \ { \ float dist = w.o.squaredist(pos); \ if(dist < mindist*mindist) { closest = n; mindist = sqrtf(dist); } \ } \ } while(0) int closest = -1; wpcachenode *curnode; loop(which, NUMWPCACHES) for(curnode = &wpcaches[which].nodes[0], wpcachestack.setsize(0);;) { int axis = curnode->axis(); float dist1 = pos[axis] - curnode->split[0], dist2 = curnode->split[1] - pos[axis]; if(dist1 >= mindist) { if(dist2 < mindist) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKCLOSEST(curnode->childindex(1)); } } else if(curnode->isleaf(0)) { CHECKCLOSEST(curnode->childindex(0)); if(dist2 < mindist) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKCLOSEST(curnode->childindex(1)); } } else { if(dist2 < mindist) { if(!curnode->isleaf(1)) wpcachestack.add(curnode + curnode->childindex(1)); else CHECKCLOSEST(curnode->childindex(1)); } curnode += curnode->childindex(0); continue; } if(wpcachestack.empty()) break; curnode = wpcachestack.pop(); } for(int i = lastwpcache; i < waypoints.length(); i++) { CHECKCLOSEST(i); } return closest; } void findwaypointswithin(const vec &pos, float mindist, float maxdist, vector &results) { if(waypoints.empty()) return; if(clearedwpcaches) buildwpcache(); float mindist2 = mindist*mindist, maxdist2 = maxdist*maxdist; #define CHECKWITHIN(index) do { \ int n = (index); \ const waypoint &w = waypoints[n]; \ float dist = w.o.squaredist(pos); \ if(dist > mindist2 && dist < maxdist2) results.add(n); \ } while(0) wpcachenode *curnode; loop(which, NUMWPCACHES) for(curnode = &wpcaches[which].nodes[0], wpcachestack.setsize(0);;) { int axis = curnode->axis(); float dist1 = pos[axis] - curnode->split[0], dist2 = curnode->split[1] - pos[axis]; if(dist1 >= maxdist) { if(dist2 < maxdist) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKWITHIN(curnode->childindex(1)); } } else if(curnode->isleaf(0)) { CHECKWITHIN(curnode->childindex(0)); if(dist2 < maxdist) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKWITHIN(curnode->childindex(1)); } } else { if(dist2 < maxdist) { if(!curnode->isleaf(1)) wpcachestack.add(curnode + curnode->childindex(1)); else CHECKWITHIN(curnode->childindex(1)); } curnode += curnode->childindex(0); continue; } if(wpcachestack.empty()) break; curnode = wpcachestack.pop(); } for(int i = lastwpcache; i < waypoints.length(); i++) { CHECKWITHIN(i); } } void avoidset::avoidnear(void *owner, float above, const vec &pos, float limit) { if(ai::waypoints.empty()) return; if(clearedwpcaches) buildwpcache(); float limit2 = limit*limit; #define CHECKNEAR(index) do { \ int n = (index); \ const waypoint &w = ai::waypoints[n]; \ if(w.o.squaredist(pos) < limit2) add(owner, above, n); \ } while(0) wpcachenode *curnode; loop(which, NUMWPCACHES) for(curnode = &wpcaches[which].nodes[0], wpcachestack.setsize(0);;) { int axis = curnode->axis(); float dist1 = pos[axis] - curnode->split[0], dist2 = curnode->split[1] - pos[axis]; if(dist1 >= limit) { if(dist2 < limit) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKNEAR(curnode->childindex(1)); } } else if(curnode->isleaf(0)) { CHECKNEAR(curnode->childindex(0)); if(dist2 < limit) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKNEAR(curnode->childindex(1)); } } else { if(dist2 < limit) { if(!curnode->isleaf(1)) wpcachestack.add(curnode + curnode->childindex(1)); else CHECKNEAR(curnode->childindex(1)); } curnode += curnode->childindex(0); continue; } if(wpcachestack.empty()) break; curnode = wpcachestack.pop(); } for(int i = lastwpcache; i < waypoints.length(); i++) { CHECKNEAR(i); } } int avoidset::remap(fpsent *d, int n, vec &pos, bool retry) { if(!obstacles.empty()) { int cur = 0; loopv(obstacles) { obstacle &ob = obstacles[i]; int next = cur + ob.numwaypoints; if(ob.owner != d) { for(; cur < next; cur++) if(waypoints[cur] == n) { if(ob.above < 0) return retry ? n : -1; vec above(pos.x, pos.y, ob.above); if(above.z-d->o.z >= ai::JUMPMAX) return retry ? n : -1; // too much scotty int node = closestwaypoint(above, ai::SIGHTMIN, true, d); if(ai::iswaypoint(node) && node != n) { // try to reroute above their head? if(!find(node, d)) { pos = ai::waypoints[node].o; return node; } else return retry ? n : -1; } else { vec old = d->o; d->o = vec(above).add(vec(0, 0, d->eyeheight)); bool col = collide(d, vec(0, 0, 1)); d->o = old; if(col) { pos = above; return n; } else return retry ? n : -1; } } } cur = next; } } return n; } static inline float heapscore(waypoint *q) { return q->score(); } bool route(fpsent *d, int node, int goal, vector &route, const avoidset &obstacles, int retries) { if(waypoints.empty() || !iswaypoint(node) || !iswaypoint(goal) || goal == node || !waypoints[node].links[0]) return false; static ushort routeid = 1; static vector queue; if(!routeid) { loopv(waypoints) waypoints[i].route = 0; routeid = 1; } if(d) { if(retries <= 1 && d->ai) loopi(ai::NUMPREVNODES) if(d->ai->prevnodes[i] != node && iswaypoint(d->ai->prevnodes[i])) { waypoints[d->ai->prevnodes[i]].route = routeid; waypoints[d->ai->prevnodes[i]].curscore = -1; waypoints[d->ai->prevnodes[i]].estscore = 0; } if(retries <= 0) { loopavoid(obstacles, d, { if(iswaypoint(wp) && wp != node && wp != goal && waypoints[node].find(wp) < 0 && waypoints[goal].find(wp) < 0) { waypoints[wp].route = routeid; waypoints[wp].curscore = -1; waypoints[wp].estscore = 0; } }); } } waypoints[node].route = routeid; waypoints[node].curscore = waypoints[node].estscore = 0; waypoints[node].prev = 0; queue.setsize(0); queue.add(&waypoints[node]); route.setsize(0); int lowest = -1; while(!queue.empty()) { waypoint &m = *queue.removeheap(); float prevscore = m.curscore; m.curscore = -1; loopi(MAXWAYPOINTLINKS) { int link = m.links[i]; if(!link) break; if(iswaypoint(link) && (link == node || link == goal || waypoints[link].links[0])) { waypoint &n = waypoints[link]; int weight = max(n.weight, 1); float curscore = prevscore + n.o.dist(m.o)*weight; if(n.route == routeid && curscore >= n.curscore) continue; n.curscore = curscore; n.prev = ushort(&m - &waypoints[0]); if(n.route != routeid) { n.estscore = n.o.dist(waypoints[goal].o)*weight; if(n.estscore <= WAYPOINTRADIUS*4 && (lowest < 0 || n.estscore <= waypoints[lowest].estscore)) lowest = link; n.route = routeid; if(link == goal) goto foundgoal; queue.addheap(&n); } else loopvj(queue) if(queue[j] == &n) { queue.upheap(j); break; } } } } foundgoal: routeid++; if(lowest >= 0) // otherwise nothing got there { for(waypoint *m = &waypoints[lowest]; m > &waypoints[0]; m = &waypoints[m->prev]) route.add(m - &waypoints[0]); // just keep it stored backward } return !route.empty(); } VAR(dropwaypoints, 0, 0, 1); int addwaypoint(const vec &o, int weight = -1) { if(waypoints.length() > MAXWAYPOINTS) return -1; int n = waypoints.length(); waypoints.add(waypoint(o, weight >= 0 ? weight : getweight(o))); return n; } void linkwaypoint(waypoint &a, int n) { loopi(MAXWAYPOINTLINKS) { if(a.links[i] == n) return; if(!a.links[i]) { a.links[i] = n; return; } } a.links[rnd(MAXWAYPOINTLINKS)] = n; } string loadedwaypoints = ""; static inline bool shouldnavigate() { if(dropwaypoints) return true; loopvrev(players) if(players[i]->aitype != AI_NONE) return true; return false; } static inline bool shoulddrop(fpsent *d) { return !d->ai && (dropwaypoints || !loadedwaypoints[0]); } void inferwaypoints(fpsent *d, const vec &o, const vec &v, float mindist) { if(!shouldnavigate()) return; if(shoulddrop(d)) { if(waypoints.empty()) seedwaypoints(); int from = closestwaypoint(o, mindist, false), to = closestwaypoint(v, mindist, false); if(!iswaypoint(from)) from = addwaypoint(o); if(!iswaypoint(to)) to = addwaypoint(v); if(d->lastnode != from && iswaypoint(d->lastnode) && iswaypoint(from)) linkwaypoint(waypoints[d->lastnode], from); if(iswaypoint(to)) { if(from != to && iswaypoint(from) && iswaypoint(to)) linkwaypoint(waypoints[from], to); d->lastnode = to; } } else d->lastnode = closestwaypoint(v, WAYPOINTRADIUS*2, false, d); } void navigate(fpsent *d) { vec v(d->feetpos()); if(d->state != CS_ALIVE) { d->lastnode = -1; return; } bool dropping = shoulddrop(d); int mat = lookupmaterial(v); if((mat&MATF_CLIP) == MAT_CLIP || (mat&MATF_VOLUME) == MAT_LAVA || mat&MAT_DEATH) dropping = false; float dist = dropping ? WAYPOINTRADIUS : (d->ai ? WAYPOINTRADIUS : SIGHTMIN); int curnode = closestwaypoint(v, dist, false, d), prevnode = d->lastnode; if(!iswaypoint(curnode) && dropping) { if(waypoints.empty()) seedwaypoints(); curnode = addwaypoint(v); } if(iswaypoint(curnode)) { if(dropping && d->lastnode != curnode && iswaypoint(d->lastnode)) { linkwaypoint(waypoints[d->lastnode], curnode); if(!d->timeinair) linkwaypoint(waypoints[curnode], d->lastnode); } d->lastnode = curnode; if(d->ai && iswaypoint(prevnode) && d->lastnode != prevnode) d->ai->addprevnode(prevnode); } else if(!iswaypoint(d->lastnode) || waypoints[d->lastnode].o.squaredist(v) > SIGHTMIN*SIGHTMIN) d->lastnode = closestwaypoint(v, SIGHTMAX, false, d); } void navigate() { if(shouldnavigate()) loopv(players) ai::navigate(players[i]); if(invalidatedwpcaches) clearwpcache(false); } void clearwaypoints(bool full) { waypoints.setsize(0); clearwpcache(); if(full) { loadedwaypoints[0] = '\0'; dropwaypoints = 0; } } ICOMMAND(clearwaypoints, "", (), clearwaypoints()); void seedwaypoints() { if(waypoints.empty()) addwaypoint(vec(0, 0, 0)); loopv(entities::ents) { extentity &e = *entities::ents[i]; switch(e.type) { case PLAYERSTART: case TELEPORT: case JUMPPAD: case FLAG: case BASE: addwaypoint(e.o); break; default: if(e.type >= I_SHELLS && e.type <= I_QUAD) addwaypoint(e.o); break; } } } void remapwaypoints() { vector remap; int total = 0; loopv(waypoints) remap.add(waypoints[i].links[1] == 0xFFFF ? 0 : total++); total = 0; loopvj(waypoints) { if(waypoints[j].links[1] == 0xFFFF) continue; waypoint &w = waypoints[total]; if(j != total) w = waypoints[j]; int k = 0; loopi(MAXWAYPOINTLINKS) { int link = w.links[i]; if(!link) break; if((w.links[k] = remap[link])) k++; } if(k < MAXWAYPOINTLINKS) w.links[k] = 0; total++; } waypoints.setsize(total); } bool cleanwaypoints() { int cleared = 0; loopv(waypoints) { waypoint &w = waypoints[i]; if(clipped(w.o)) { w.links[0] = 0; w.links[1] = 0xFFFF; cleared++; } } if(cleared) { player1->lastnode = -1; loopv(players) if(players[i]) players[i]->lastnode = -1; remapwaypoints(); clearwpcache(); return true; } return false; } bool getwaypointfile(const char *name, char *wptname) { if(!name || !*name) name = getclientmap(); if(!*name) return false; getmapfilenames(name); formatstring(wptname)("packages/%s/%s.wpt", mpath, mname); path(wptname); return true; } void loadwaypoints(bool force, const char *name) { string wptname; if(!getwaypointfile(name, wptname)) return; if(!force && (waypoints.length() || !strcmp(loadedwaypoints, wptname))) return; stream *f = opengzfile(wptname, "rb"); if(!f) return; char magic[4]; if(f->read(magic, 4) < 4 || memcmp(magic, "OWPT", 4)) { delete f; return; } copystring(loadedwaypoints, wptname); waypoints.setsize(0); waypoints.add(vec(0, 0, 0)); ushort numwp = f->getlil(); loopi(numwp) { if(f->end()) break; vec o; o.x = f->getlil(); o.y = f->getlil(); o.z = f->getlil(); waypoint &w = waypoints.add(waypoint(o, getweight(o))); int numlinks = f->getchar(); loopj(numlinks) { ushort link = f->getlil(); if(j < MAXWAYPOINTLINKS) w.links[j] = link; } } delete f; conoutf("loaded %d waypoints from %s", numwp, wptname); if(!cleanwaypoints()) clearwpcache(); } ICOMMAND(loadwaypoints, "s", (char *name), loadwaypoints(true, name)); void savewaypoints(bool force, const char *name) { if((!dropwaypoints && !force) || waypoints.empty()) return; string wptname; if(!getwaypointfile(name, wptname)) return; stream *f = opengzfile(wptname, "wb"); if(!f) return; f->write("OWPT", 4); f->putlil(waypoints.length()-1); for(int i = 1; i < waypoints.length(); i++) { waypoint &w = waypoints[i]; f->putlil(w.o.x); f->putlil(w.o.y); f->putlil(w.o.z); int numlinks = 0; loopj(MAXWAYPOINTLINKS) { if(!w.links[j]) break; numlinks++; } f->putchar(numlinks); loopj(numlinks) f->putlil(w.links[j]); } delete f; conoutf("saved %d waypoints to %s", waypoints.length()-1, wptname); } ICOMMAND(savewaypoints, "s", (char *name), savewaypoints(true, name)); void delselwaypoints() { if(noedit(true)) return; vec o = sel.o.tovec().sub(0.1f), s = sel.s.tovec().mul(sel.grid).add(o).add(0.1f); int cleared = 0; loopv(waypoints) { waypoint &w = waypoints[i]; if(w.o.x >= o.x && w.o.x <= s.x && w.o.y >= o.y && w.o.y <= s.y && w.o.z >= o.z && w.o.z <= s.z) { w.links[0] = 0; w.links[1] = 0xFFFF; cleared++; } } if(cleared) { player1->lastnode = -1; remapwaypoints(); clearwpcache(); } } COMMAND(delselwaypoints, ""); } sandboxgamemaker-2.8.2+dfsg/src/fpsgame/client.cpp0000644000175000017500000020721412045412564021114 0ustar bofh80bofh80#include "game.h" namespace game { VARP(minradarscale, 0, 384, 10000); VARP(maxradarscale, 1, 1024, 10000); FVARP(minimapalpha, 0, 1, 1); float calcradarscale() { return clamp(max(minimapradius.x, minimapradius.y)/3, float(minradarscale), float(maxradarscale)); } void drawminimap(fpsent *d, float x, float y, float s) { vec pos = vec(d->o).sub(minimapcenter).mul(minimapscale).add(0.5f), dir; vecfromyawpitch(camera1->yaw, 0, 1, 0, dir); float scale = calcradarscale(); glBegin(GL_TRIANGLE_FAN); loopi(16) { vec tc = vec(dir).rotate_around_z(i/16.0f*2*M_PI); glTexCoord2f(pos.x + tc.x*scale*minimapscale.x, pos.y + tc.y*scale*minimapscale.y); vec v = vec(0, -1, 0).rotate_around_z(i/16.0f*2*M_PI); glVertex2f(x + 0.5f*s*(1.0f + v.x), y + 0.5f*s*(1.0f + v.y)); } glEnd(); } void drawradar(float x, float y, float s) { glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0.0f, 0.0f); glVertex2f(x, y); glTexCoord2f(1.0f, 0.0f); glVertex2f(x+s, y); glTexCoord2f(0.0f, 1.0f); glVertex2f(x, y+s); glTexCoord2f(1.0f, 1.0f); glVertex2f(x+s, y+s); glEnd(); } #include "capture.h" #include "ctf.h" #include "collect.h" clientmode *cmode = NULL; captureclientmode capturemode; ctfclientmode ctfmode; collectclientmode collectmode; void setclientmode() { if(m_capture) cmode = &capturemode; else if(m_ctf) cmode = &ctfmode; else if(m_collect) cmode = &collectmode; else cmode = NULL; } 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, mastermode = MM_OPEN; string servinfo = "", 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(N_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 switchteam(const char *team) { if(team[0]) { if(player1->clientnum < 0) filtertext(player1->team, team, false, MAXTEAMLEN); else addmsg(N_SWITCHTEAM, "rs", team); } else conoutf("your team is: %s", player1->team); } ICOMMAND(team, "s", (char *s), switchteam(s)); ICOMMAND(getteam, "", (), result(player1->team)); void switchplayermodel(int playermodel) { player1->playermodel = playermodel; addmsg(N_SWITCHMODEL, "ri", player1->playermodel); } 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)); bool hasauthkey(const char *name, const char *desc) { if(!name[0] && !desc[0]) return authkeys.length() > 0; loopvrev(authkeys) if(!strcmp(authkeys[i]->desc, desc) && !strcmp(authkeys[i]->name, name)) return true; return false; } ICOMMAND(hasauthkey, "ss", (char *name, char *desc), intret(hasauthkey(name, desc) ? 1 : 0)); 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", escapestring(a->name), escapestring(a->key), escapestring(a->desc)); } conoutf("saved authkeys to auth.cfg"); delete f; } COMMAND(saveauthkeys, ""); void sendmapinfo() { sendcrc = true; if(player1->state!=CS_SPECTATOR || player1->privilege || !remote) senditemstoserver = true; } void writeclientinfo(stream *f) { f->printf("name %s\n", escapestring(player1->name)); } bool allowedittoggle() { if(editmode) return true; 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) { addmsg(N_EDITMODE, "ri", on ? 1 : 0); if(player1->state==CS_DEAD) deathstate(player1, true); else if(player1->state==CS_EDITING && player1->editstate==CS_DEAD) showscores(false); disablezoom(); player1->suicided = player1->respawned = -2; } const char *getclientname(int cn) { fpsent *d = getclient(cn); return d ? d->name : ""; } ICOMMAND(getclientname, "i", (int *cn), result(getclientname(*cn))); int getclientping(int cn) { fpsent *d = getclient(cn); return d ? d->ping : 0; } ICOMMAND(getclientping, "i", (int *cn), intret(getclientping(*cn))); int getclientpj(int cn) { fpsent *d = getclient(cn); return d ? d->plag : 0; } ICOMMAND(getclientpj, "i", (int *cn), intret(getclientpj(*cn))); int getclientfrags(int cn) { fpsent *d = getclient(cn); return d ? d->frags : 0; } ICOMMAND(getclientfrags, "i", (int *cn), intret(getclientfrags(*cn))); int getclientflags(int cn) { fpsent *d = getclient(cn); return d ? d->flags : 0; } ICOMMAND(getclientflags, "i", (int *cn), intret(getclientflags(*cn))); int getclientaccuracy(int cn) { fpsent *d = getclient(cn); return d ? d->totaldamage * 100 / max(d->totalshots, 1) : 0; } ICOMMAND(getclientaccuracy, "i", (int *cn), intret(getclientaccuracy(*cn))); const char *getclientteam(int cn) { fpsent *d = getclient(cn); return d ? d->team : ""; } ICOMMAND(getclientteam, "i", (int *cn), result(getclientteam(*cn))); int getclientmodel(int cn) { fpsent *d = getclient(cn); return d ? d->playermodel : -1; } ICOMMAND(getclientmodel, "i", (int *cn), intret(getclientmodel(*cn))); const char *getclienticon(int cn) { fpsent *d = getclient(cn); if(!d || d->state==CS_SPECTATOR) return "spectator"; const playermodelinfo &mdl = getplayermodelinfo(d); return m_teammode ? (isteam(player1->team, d->team) ? mdl.blueicon : mdl.redicon) : mdl.ffaicon; } ICOMMAND(getclienticon, "i", (int *cn), result(getclienticon(*cn))); int getteamscore(const char *team) { int score = 0; if(cmode) score = cmode->getteamscore(team); else if(m_teammode) loopv(players) { if(!strcmp(team, players[i]->team)) score += players[i]->frags; } return score; } ICOMMAND(getteamscore, "s", (const char *team), intret(getteamscore(team))); bool isdead(int cn) { fpsent *d = getclient(cn); return d && d->state == CS_DEAD; } ICOMMAND(isdead, "i", (int *cn), intret(isdead(*cn) ? 1 : 0)); bool ismaster(int cn) { fpsent *d = getclient(cn); return d && d->privilege >= PRIV_MASTER; } ICOMMAND(ismaster, "i", (int *cn), intret(ismaster(*cn) ? 1 : 0)); bool isadmin(int cn) { fpsent *d = getclient(cn); return d && d->privilege >= PRIV_ADMIN; } ICOMMAND(isadmin, "i", (int *cn), intret(isadmin(*cn) ? 1 : 0)); ICOMMAND(getmastermode, "", (), intret(mastermode)); ICOMMAND(mastermodename, "i", (int *mm), result(server::mastermodename(*mm, ""))); bool isspectator(int cn) { fpsent *d = getclient(cn); return d && d->state==CS_SPECTATOR; } ICOMMAND(isspectator, "i", (int *cn), intret(isspectator(*cn) ? 1 : 0)); bool isai(int cn, int type) { fpsent *d = getclient(cn); int aitype = type > 0 && type < AI_MAX ? type : AI_BOT; return d && d->aitype==aitype; } ICOMMAND(isai, "ii", (int *cn, int *type), intret(isai(*cn, *type) ? 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) { fpsent *o = players[i]; if(!strcmp(arg, o->name)) return o->clientnum; } // nothing found, try case insensitive loopv(players) { fpsent *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(N_CLEARBANS, "r"); } COMMAND(clearbans, ""); void kick(const char *arg) { int i = parseplayer(arg); if(i>=0 && i!=player1->clientnum) addmsg(N_KICK, "ri", i); } COMMAND(kick, "s"); vector ignores; void ignore(int cn) { fpsent *d = getclient(cn); if(!d || d == player1) return; conoutf("ignoring %s", d->name); if(ignores.find(cn) < 0) ignores.add(cn); } void unignore(int cn) { if(ignores.find(cn) < 0) return; fpsent *d = getclient(cn); if(d) conoutf("stopped ignoring %s", d->name); ignores.removeobj(cn); } bool isignored(int cn) { return ignores.find(cn) >= 0; } ICOMMAND(ignore, "s", (char *arg), ignore(parseplayer(arg))); ICOMMAND(unignore, "s", (char *arg), unignore(parseplayer(arg))); ICOMMAND(isignored, "s", (char *arg), intret(isignored(parseplayer(arg)) ? 1 : 0)); void setteam(const char *arg1, const char *arg2) { int i = parseplayer(arg1); if(i>=0) addmsg(N_SETTEAM, "ris", i, arg2); } COMMAND(setteam, "ss"); 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 = parseint(arg); else server::hashpassword(player1->clientnum, sessionid, arg, hash); addmsg(N_SETMASTER, "ris", val, hash); } COMMAND(setmaster, "s"); ICOMMAND(mastermode, "i", (int *val), addmsg(N_MASTERMODE, "ri", *val)); bool tryauth(const char *desc) { authkey *a = findauthkey(desc); if(!a) return false; a->lastauth = lastmillis; addmsg(N_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(N_SPECTATOR, "rii", i, val); } ICOMMAND(spectator, "is", (int *val, char *who), togglespectator(*val, who)); ICOMMAND(checkmaps, "", (), addmsg(N_CHECKMAPS, "r")); VARP(localmode, STARTGAMEMODE, 1, STARTGAMEMODE + NUMGAMEMODES - 1); SVARP(localmap, "house"); VARP(lobbymode, STARTGAMEMODE, 0, STARTGAMEMODE + NUMGAMEMODES - 1); SVARP(lobbymap, "house"); 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, "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; if(editmode) toggleedit(); if(m_demo) { entities::resetspawns(); return; } if((m_edit && !name[0]) || !load_world(name)) { emptymap(0, true, name); senditemstoserver = false; } startgame(); } void setmode(int mode) { if(multiplayer(false) && !m_mp(mode)) { conoutf(CON_ERROR, "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)); ICOMMAND(timeremaining, "i", (int *formatted), { int val = max(maplimit - lastmillis, 0)/1000; if(*formatted) { defformatstring(str)("%d:%02d", val/60, val%60); result(str); } else intret(val); }); ICOMMANDS("m_noitems", "i", (int *mode), { int gamemode = *mode; intret(m_noitems); }); ICOMMANDS("m_noammo", "i", (int *mode), { int gamemode = *mode; intret(m_noammo); }); ICOMMANDS("m_insta", "i", (int *mode), { int gamemode = *mode; intret(m_insta); }); ICOMMANDS("m_tactics", "i", (int *mode), { int gamemode = *mode; intret(m_tactics); }); ICOMMANDS("m_efficiency", "i", (int *mode), { int gamemode = *mode; intret(m_efficiency); }); ICOMMANDS("m_capture", "i", (int *mode), { int gamemode = *mode; intret(m_capture); }); ICOMMANDS("m_regencapture", "i", (int *mode), { int gamemode = *mode; intret(m_regencapture); }); ICOMMANDS("m_ctf", "i", (int *mode), { int gamemode = *mode; intret(m_ctf); }); ICOMMANDS("m_protect", "i", (int *mode), { int gamemode = *mode; intret(m_protect); }); ICOMMANDS("m_hold", "i", (int *mode), { int gamemode = *mode; intret(m_hold); }); ICOMMANDS("m_collect", "i", (int *mode), { int gamemode = *mode; intret(m_collect); }); ICOMMANDS("m_teammode", "i", (int *mode), { int gamemode = *mode; intret(m_teammode); }); ICOMMANDS("m_demo", "i", (int *mode), { int gamemode = *mode; intret(m_demo); }); ICOMMANDS("m_edit", "i", (int *mode), { int gamemode = *mode; intret(m_edit); }); ICOMMANDS("m_lobby", "i", (int *mode), { int gamemode = *mode; intret(m_lobby); }); ICOMMANDS("m_sp", "i", (int *mode), { int gamemode = *mode; intret(m_sp); }); ICOMMANDS("m_dmsp", "i", (int *mode), { int gamemode = *mode; intret(m_dmsp); }); ICOMMANDS("m_classicsp", "i", (int *mode), { int gamemode = *mode; intret(m_classicsp); }); void changemap(const char *name, int mode) // request map change, server may ignore { 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(N_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(N_NEWMAP, "ri", size); } int needclipboard = -1; void sendclipboard() { uchar *outbuf = NULL; int inlen = 0, outlen = 0; if(!packeditinfo(localedit, inlen, outbuf, outlen)) { outbuf = NULL; inlen = outlen = 0; } packetbuf p(16 + outlen, ENET_PACKET_FLAG_RELIABLE); putint(p, N_CLIPBOARD); putint(p, inlen); putint(p, outlen); if(outlen > 0) p.put(outbuf, outlen); sendclientpacket(p.finalize(), 1); needclipboard = -1; } 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: { switch(op) { case EDIT_COPY: needclipboard = 0; break; case EDIT_PASTE: if(needclipboard > 0) { c2sinfo(true); sendclipboard(); } break; } addmsg(N_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(N_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: { addmsg(N_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_REPLACE: { addmsg(N_EDITF + op, "ri9i7", 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, arg3); break; } case EDIT_REMIP: { addmsg(N_EDITF + op, "r"); break; } } } void printvar(fpsent *d, ident *id) { if(id) switch(id->type) { case ID_VAR: { int val = *id->storage.i; string str; if(val < 0) formatstring(str)("%d", val); else 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(N_EDITVAR, "risi", ID_VAR, id->name, *id->storage.i); break; case ID_FVAR: addmsg(N_EDITVAR, "risf", ID_FVAR, id->name, *id->storage.f); break; case ID_SVAR: addmsg(N_EDITVAR, "riss", ID_SVAR, id->name, *id->storage.s); break; default: return; } printvar(player1, id); } void pausegame(int *val) { addmsg(N_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': { fpsent *d = va_arg(args, fpsent *); 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, N_FROMAI); 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(); ignores.setsize(0); connected = remote = false; player1->clientnum = -1; sessionid = 0; mastermode = MM_OPEN; messages.setsize(0); messagereliable = false; messagecn = -1; player1->respawn(); player1->lifesequence = 0; player1->state = CS_ALIVE; player1->privilege = PRIV_NONE; senditemstoserver = 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(N_TEXT, "rcis", player1, CHAT_TALK, text); } COMMANDN(say, toserver, "C"); void sayteam(char *text) { conoutf(CON_TEAMCHAT, "<%s>\f1 %s", colorname(player1), text); addmsg(N_TEXT, "rcis", player1, CHAT_TEAM, text); } COMMAND(sayteam, "C"); void emote(char *text) { conoutf(CON_CHAT, "\f6* %s %s", colorname(player1), text); addmsg(N_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(N_TEXT, "rcis", player1, CHAT_TEAM|CHAT_EMOTE, text); } COMMANDN(meteam, teamemote, "C"); ICOMMAND(servcmd, "C", (char *cmd), addmsg(N_SERVCMD, "rs", cmd)); static void sendposition(fpsent *d, packetbuf &q) { putint(q, N_POS); putuint(q, d->clientnum); // 3 bits phys state, 1 bit life sequence, 2 bits move, 2 bits strafe uchar physstate = d->physstate | ((d->lifesequence&1)<<3) | ((d->move&3)<<4) | ((d->strafe&3)<<6); q.put(physstate); ivec o = ivec(vec(d->o.x, d->o.y, d->o.z-d->eyeheight).mul(DMF)); uint vel = min(int(d->vel.magnitude()*DVELF), 0xFFFF), fall = min(int(d->falling.magnitude()*DVELF), 0xFFFF); // 3 bits position, 1 bit velocity, 3 bits falling, 1 bit material uint flags = 0; if(o.x < 0 || o.x > 0xFFFF) flags |= 1<<0; if(o.y < 0 || o.y > 0xFFFF) flags |= 1<<1; if(o.z < 0 || o.z > 0xFFFF) flags |= 1<<2; if(vel > 0xFF) flags |= 1<<3; if(fall > 0) { flags |= 1<<4; if(fall > 0xFF) flags |= 1<<5; if(d->falling.x || d->falling.y || d->falling.z > 0) flags |= 1<<6; } if((lookupmaterial(d->feetpos())&MATF_CLIP) == MAT_GAMECLIP) flags |= 1<<7; putuint(q, flags); loopk(3) { q.put(o[k]&0xFF); q.put((o[k]>>8)&0xFF); if(o[k] < 0 || o[k] > 0xFFFF) q.put((o[k]>>16)&0xFF); } uint dir = (d->yaw < 0 ? 360 + int(d->yaw)%360 : int(d->yaw)%360) + clamp(int(d->pitch+90), 0, 180)*360; q.put(dir&0xFF); q.put((dir>>8)&0xFF); q.put(clamp(int(d->roll+90), 0, 180)); q.put(vel&0xFF); if(vel > 0xFF) q.put((vel>>8)&0xFF); float velyaw, velpitch; vectoyawpitch(d->vel, velyaw, velpitch); uint veldir = (velyaw < 0 ? 360 + int(velyaw)%360 : int(velyaw)%360) + clamp(int(velpitch+90), 0, 180)*360; q.put(veldir&0xFF); q.put((veldir>>8)&0xFF); if(fall > 0) { q.put(fall&0xFF); if(fall > 0xFF) q.put((fall>>8)&0xFF); if(d->falling.x || d->falling.y || d->falling.z > 0) { float fallyaw, fallpitch; vectoyawpitch(d->falling, fallyaw, fallpitch); uint falldir = (fallyaw < 0 ? 360 + int(fallyaw)%360 : int(fallyaw)%360) + clamp(int(fallpitch+90), 0, 180)*360; q.put(falldir&0xFF); q.put((falldir>>8)&0xFF); } } } void sendposition(fpsent *d, bool reliable) { if(d->state != CS_ALIVE && d->state != CS_EDITING) return; packetbuf q(100, reliable ? ENET_PACKET_FLAG_RELIABLE : 0); sendposition(d, q); sendclientpacket(q.finalize(), 0); } void sendpositions() { loopv(players) { fpsent *d = players[i]; if((d == player1 || d->ai) && (d->state == CS_ALIVE || d->state == CS_EDITING)) { packetbuf q(100); sendposition(d, q); for(int j = i+1; j < players.length(); j++) { fpsent *d = players[j]; if((d == player1 || d->ai) && (d->state == CS_ALIVE || d->state == CS_EDITING)) sendposition(d, q); } sendclientpacket(q.finalize(), 0); break; } } } void sendmessages() { packetbuf p(MAXTRANS); if(sendcrc) { p.reliable(); sendcrc = false; const char *mname = getclientmap(); putint(p, N_MAPCRC); sendstring(mname, p); putint(p, mname[0] ? getmapcrc() : 0); } 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(totalmillis-lastping>250) { putint(p, N_PING); putint(p, totalmillis); lastping = totalmillis; } sendclientpacket(p.finalize(), 1); } void c2sinfo(bool force) // send update to the server { static int lastupdate = -1000; if(totalmillis - lastupdate < 33 && !force) return; // don't update faster than 30fps lastupdate = totalmillis; sendpositions(); sendmessages(); flushclient(); } void sendintro() { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); putint(p, N_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); putint(p, player1->playermodel); sendclientpacket(p.finalize(), 1); } void updatepos(fpsent *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 = totalmillis-d->lastupdate; if(lagtime) { if(d->state!=CS_SPAWNING && d->lastupdate) d->plag = (d->plag*5+lagtime)/6; d->lastupdate = totalmillis; } } void parsepositions(ucharbuf &p) { int type; while(p.remaining()) switch(type = getint(p)) { case N_POS: // position of another client { int cn = getuint(p), physstate = p.get(), flags = getuint(p); vec o, vel, falling; float yaw, pitch, roll; loopk(3) { int n = p.get(); n |= p.get()<<8; if(flags&(1<>3)&1; fpsent *d = getclient(cn); if(!d || d->lifesequence < 0 || seqcolor!=(d->lifesequence&1) || d->state==CS_DEAD) continue; float oldyaw = d->yaw, oldpitch = d->pitch, oldroll = d->roll; d->yaw = yaw; d->pitch = pitch; d->roll = roll; d->move = (physstate>>4)&2 ? -1 : (physstate>>4)&1; d->strafe = (physstate>>6)&2 ? -1 : (physstate>>6)&1; vec oldpos(d->o); if(allowmove(d)) { d->o = o; d->o.z += d->eyeheight; d->vel = vel; d->falling = falling; d->physstate = physstate&7; } 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->newroll = d->roll; d->o = oldpos; d->yaw = oldyaw; d->pitch = oldpitch; d->roll = oldroll; (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->deltaroll = oldroll - d->newroll; d->smoothmillis = lastmillis; } else d->smoothmillis = 0; if(d->state==CS_LAGGED || d->state==CS_SPAWNING) d->state = CS_ALIVE; break; } case N_TELEPORT: { int cn = getint(p), tp = getint(p), td = getint(p); fpsent *d = getclient(cn); if(!d || d->lifesequence < 0 || d->state==CS_DEAD) continue; entities::teleporteffects(d, tp, td, false); break; } case N_JUMPPAD: { int cn = getint(p), jp = getint(p); fpsent *d = getclient(cn); if(!d || d->lifesequence < 0 || d->state==CS_DEAD) continue; entities::jumppadeffects(d, jp, false); break; } default: neterr("type"); return; } } void parsestate(fpsent *d, ucharbuf &p, bool resume = false) { if(!d) { static fpsent dummy; d = &dummy; } if(resume) { if(d==player1) getint(p); else d->state = getint(p); d->frags = getint(p); d->flags = getint(p); if(d==player1) getint(p); else d->quadmillis = getint(p); } d->lifesequence = getint(p); d->health = getint(p); d->maxhealth = getint(p); d->armour = getint(p); d->armourtype = getint(p); if(resume && d==player1) { getint(p); loopi(GUN_PISTOL-GUN_SG+1) getint(p); } else { int gun = getint(p); d->gunselect = clamp(gun, int(GUN_FIST), int(GUN_PISTOL)); loopi(GUN_PISTOL-GUN_SG+1) d->ammo[GUN_SG+i] = getint(p); } } extern int deathscore; void parsemessages(int cn, fpsent *d, ucharbuf &p) { static char text[MAXTRANS]; int type; bool mapchanged = false, initmap = false; while(p.remaining()) switch(type = getint(p)) { case N_SERVINFO: // welcome messsage from the server { 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"); getstring(text, p); copystring(servinfo, text); sendintro(); break; } case N_WELCOME: { int hasmap = getint(p); if(!hasmap) initmap = true; // we are the first client on this server, set map break; } case N_PAUSEGAME: { int val = getint(p); gamepaused = val > 0; conoutf("game is %s", gamepaused ? "paused" : "resumed"); break; } case N_CLIENT: { int cn = getint(p), len = getuint(p); ucharbuf q = p.subbuf(len); parsemessages(cn, getclient(cn), q); break; } case N_SOUND: if(!d) return; playsound(getint(p), &d->o); break; case N_TEXT: { int tcn = getint(p), mtype = getint(p); getstring(text, p); filtertext(text, text); fpsent *t = getclient(tcn); if(isignored(t->clientnum)) break; 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 N_MAPCHANGE: getstring(text, p); changemapserv(text, getint(p)); mapchanged = true; if(getint(p)) entities::spawnitems(); else senditemstoserver = false; break; case N_FORCEDEATH: { int cn = getint(p); fpsent *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 N_ITEMLIST: { int n; while((n = getint(p))>=0 && !p.overread()) { if(mapchanged) entities::setspawn(n, true); getint(p); // type } break; } case N_MAPRELOAD: // server requests next map { defformatstring(nextmapalias)("nextmap_%s%s", (cmode ? cmode->prefixnextmap() : ""), getclientmap()); const char *map = getalias(nextmapalias); // look up map in the cycle addmsg(N_MAPCHANGE, "rsi", *map ? map : getclientmap(), nextmode); break; } case N_INITCLIENT: // another client either connected or changed name/team { int cn = getint(p); fpsent *d = newclient(cn); 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) && !isignored(d->clientnum)) conoutf("%s is now known as %s", colorname(d), colorname(d, text)); } else // new client { conoutf("connected: %s", colorname(d, text)); if(needclipboard >= 0) needclipboard++; } copystring(d->name, text, MAXNAMELEN+1); getstring(text, p); filtertext(d->team, text, false, MAXTEAMLEN); d->playermodel = getint(p); break; } case N_SWITCHNAME: getstring(text, p); if(d) { filtertext(text, text, false, MAXNAMELEN); if(!text[0]) copystring(text, "unnamed"); if(strcmp(text, d->name)) { if(!isignored(d->clientnum)) conoutf("%s is now known as %s", colorname(d), colorname(d, text)); copystring(d->name, text, MAXNAMELEN+1); } } break; case N_SWITCHMODEL: { int model = getint(p); if(d) { d->playermodel = model; if(d->ragdoll) cleanragdoll(d); } break; } case N_CDIS: clientdisconnected(getint(p)); break; case N_SPAWN: { if(d) { if(d->state==CS_DEAD && d->lastpain) saveragdoll(d); d->respawn(); } parsestate(d, p); if(!d) break; d->state = CS_SPAWNING; if(player1->state==CS_SPECTATOR && following==d->clientnum) lasthit = 0; break; } case N_SPAWNSTATE: { int scn = getint(p); fpsent *s = getclient(scn); if(!s) { parsestate(NULL, p); break; } if(s->state==CS_DEAD && s->lastpain) saveragdoll(s); if(s==player1) { if(editmode) toggleedit(); stopfollowing(); } s->respawn(); parsestate(s, p); s->state = CS_ALIVE; if(cmode) cmode->pickspawn(s); else findplayerspawn(s); if(s == player1) { showscores(false); lasthit = 0; } if(cmode) cmode->respawned(s); ai::spawned(s); addmsg(N_SPAWN, "rcii", s, s->lifesequence, s->gunselect); break; } case N_SHOTFX: { int scn = getint(p), gun = getint(p), id = getint(p); vec from, to; loopk(3) from[k] = getint(p)/DMF; loopk(3) to[k] = getint(p)/DMF; fpsent *s = getclient(scn); if(!s) break; if(gun>GUN_FIST && gun<=GUN_PISTOL && s->ammo[gun]) s->ammo[gun]--; s->gunselect = clamp(gun, (int)GUN_FIST, (int)GUN_PISTOL); s->gunwait = guns[s->gunselect].attackdelay; int prevaction = s->lastaction; s->lastaction = lastmillis; s->lastattackgun = s->gunselect; shoteffects(gun, from, to, s, false, id, prevaction); break; } case N_EXPLODEFX: { int ecn = getint(p), gun = getint(p), id = getint(p); fpsent *e = getclient(ecn); if(!e) break; explodeeffects(gun, e, false, id); break; } case N_DAMAGE: { int tcn = getint(p), acn = getint(p), damage = getint(p), armour = getint(p), health = getint(p); fpsent *target = getclient(tcn), *actor = getclient(acn); if(!target || !actor) break; target->armour = armour; target->health = health; if(target->state == CS_ALIVE && actor != player1) target->lastpain = lastmillis; damaged(damage, target, actor, false); break; } case N_HITPUSH: { int tcn = getint(p), gun = getint(p), damage = getint(p); fpsent *target = getclient(tcn); vec dir; loopk(3) dir[k] = getint(p)/DNF; if(target) target->hitpush(damage * (target->health<=0 ? deadpush : 1), dir, NULL, gun); break; } case N_DIED: { int vcn = getint(p), acn = getint(p), frags = getint(p); fpsent *victim = getclient(vcn), *actor = getclient(acn); if(!actor) break; actor->frags = frags; if(actor!=player1 && (!cmode || !cmode->hidefrags())) { defformatstring(ds)("%d", actor->frags); particle_textcopy(actor->abovehead(), ds, PART_TEXT, 2000, 0x32FF64, 4.0f, -8); } if(!victim) break; killed(victim, actor); break; } case N_GUNSELECT: { if(!d) return; int gun = getint(p); d->gunselect = clamp(gun, int(GUN_FIST), int(GUN_PISTOL)); playsound(S_WEAPLOAD, &d->o); break; } case N_TAUNT: { if(!d) return; d->lasttaunt = lastmillis; break; } case N_RESUME: { for(;;) { int cn = getint(p); if(p.overread() || cn<0) break; fpsent *d = (cn == player1->clientnum ? player1 : newclient(cn)); parsestate(d, p, true); } break; } case N_ITEMSPAWN: { int i = getint(p); if(!entities::ents.inrange(i)) break; entities::setspawn(i, true); ai::itemspawned(i); playsound(S_ITEMSPAWN, &entities::ents[i]->o, NULL, 0, 0, -1, 0, 1500); #if 0 const char *name = entities::itemname(i); if(name) particle_text(entities::ents[i]->o, name, PART_TEXT, 2000, 0x32FF64, 4.0f, -8); #endif int icon = entities::itemicon(i); if(icon >= 0) particle_icon(vec(0.0f, 0.0f, 4.0f).add(entities::ents[i]->o), icon%4, icon/4, PART_HUD_ICON, 2000, 0xFFFFFF, 2.0f, -8); break; } case N_ITEMACC: // server acknowledges that I picked up this item { int i = getint(p), cn = getint(p); fpsent *d = getclient(cn); entities::pickupeffects(i, d); break; } case N_CLIPBOARD: { int cn = getint(p), unpacklen = getint(p), packlen = getint(p); fpsent *d = getclient(cn); ucharbuf q = p.subbuf(max(packlen, 0)); if(d) unpackeditinfo(d->edit, q.buf, q.maxlen, unpacklen); break; } case N_EDITF: // coop editing messages case N_EDITT: case N_EDITM: case N_FLIP: case N_COPY: case N_PASTE: case N_ROTATE: case N_REPLACE: case N_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 N_EDITF: dir = getint(p); mode = getint(p); if(sel.validate()) mpeditface(dir, mode, sel, false); break; case N_EDITT: tex = getint(p); allfaces = getint(p); if(sel.validate()) mpedittex(tex, allfaces, sel, false); break; case N_EDITM: mat = getint(p); filter = getint(p); if(sel.validate()) mpeditmat(mat, filter, sel, false); break; case N_FLIP: if(sel.validate()) mpflip(sel, false); break; case N_COPY: if(d && sel.validate()) mpcopy(d->edit, sel, false); break; case N_PASTE: if(d && sel.validate()) mppaste(d->edit, sel, false); break; case N_ROTATE: dir = getint(p); if(sel.validate()) mprotate(dir, sel, false); break; case N_REPLACE: tex = getint(p); newtex = getint(p); insel = getint(p); if(sel.validate()) mpreplacetex(tex, newtex, insel>0, sel, false); break; case N_DELCUBE: if(sel.validate()) mpdelcube(sel, false); break; } break; } case N_REMIP: { if(!d) return; conoutf("%s remipped", colorname(d)); mpremip(false); break; } case N_EDITENT: // coop edit of ent { if(!d) return; 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 N_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_OVERRIDE && !(id->flags&IDF_READONLY)) setvar(name, val); break; } case ID_FVAR: { float val = getfloat(p); if(id && id->flags&IDF_OVERRIDE && !(id->flags&IDF_READONLY)) setfvar(name, val); break; } case ID_SVAR: { getstring(text, p); if(id && id->flags&IDF_OVERRIDE && !(id->flags&IDF_READONLY)) setsvar(name, text); break; } } printvar(d, id); break; } case N_PONG: addmsg(N_CLIENTPING, "i", player1->ping = (player1->ping*5+totalmillis-getint(p))/6); break; case N_CLIENTPING: if(!d) return; d->ping = getint(p); break; case N_TIMEUP: timeupdate(getint(p)); break; case N_SERVMSG: getstring(text, p); conoutf("%s", text); break; case N_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 N_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 N_CURRENTMASTER: { int mn = getint(p), priv = getint(p), mm = getint(p); loopv(players) players[i]->privilege = PRIV_NONE; if(mn>=0) { fpsent *m = mn==player1->clientnum ? player1 : newclient(mn); if(m) m->privilege = priv; } if(mm != mastermode) { mastermode = mm; conoutf("mastermode is %s (%d)", server::mastermodename(mastermode), mastermode); } break; } case N_MASTERMODE: { mastermode = getint(p); conoutf("mastermode is %s (%d)", server::mastermodename(mastermode), mastermode); break; } case N_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 N_SPECTATOR: { int sn = getint(p), val = getint(p); fpsent *s; if(sn==player1->clientnum) { s = player1; if(val && remote && !player1->privilege) senditemstoserver = 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; } case N_SETTEAM: { int wn = getint(p); getstring(text, p); int reason = getint(p); fpsent *w = getclient(wn); if(!w) return; filtertext(w->team, text, false, MAXTEAMLEN); static const char *fmt[2] = { "%s switched to team %s", "%s forced to team %s"}; if(reason >= 0 && size_t(reason) < sizeof(fmt)/sizeof(fmt[0])) conoutf(fmt[reason], colorname(w), w->team); break; } #define PARSEMESSAGES 1 #include "capture.h" #include "ctf.h" #include "collect.h" #undef PARSEMESSAGES case N_ANNOUNCE: { int t = getint(p); if (t==I_QUAD) { playsound(S_V_QUAD10, NULL, NULL, 0, 0, -1, 0, 3000); conoutf(CON_GAMEINFO, "\f2quad damage will spawn in 10 seconds!"); } else if(t==I_BOOST) { playsound(S_V_BOOST10, NULL, NULL, 0, 0, -1, 0, 3000); conoutf(CON_GAMEINFO, "\f2+10 health will spawn in 10 seconds!"); } break; } case N_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 N_REQAUTH: { getstring(text, p); if(autoauth && text[0] && tryauth(text)) conoutf("server requested authkey \"%s\"", text); break; } case N_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(N_AUTHANS, "rsis", a->desc, id, buf.getbuf()); } break; } case N_INITAI: { int bn = getint(p), on = getint(p), at = getint(p), sk = clamp(getint(p), 1, 101), pm = getint(p); string name, team; getstring(text, p); filtertext(name, text, false, MAXNAMELEN); getstring(text, p); filtertext(team, text, false, MAXTEAMLEN); fpsent *b = newclient(bn); if(!b) break; ai::init(b, at, on, sk, bn, pm, name, team); break; } //__offtools__ attachments: attach stuff case N_ATTACH: { int part = getint(p); getstring(text,p); int animrule = getint(p); if(d) { d->attached.add(part,text,animrule); } break; } //__offtools__ attachments: detach stuff case N_DETACH: { int part = getint(p); if(d) { d->attached.remove(part); } break; } case N_SERVCMD: getstring(text, p); 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; entities::spawnitems(true); 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 N_SENDCFG: { if(!m_edit) return; stream *cfg = openrawfile(path(cname), "wb"); if(!cfg) return; cfg->write(data, len); delete cfg; break; } case N_SENDMAP: { if(!m_edit) return; string oldname; copystring(oldname, getclientmap()); stream *map = openrawfile(path(fname), "wb"); if(!map) return; conoutf("received map"); map->write(data, len); delete map; if(load_world("getmap", oldname[0] ? oldname : NULL)) entities::spawnitems(true); remove(findfile(fname, "rb")); remove(findfile(cname, "rb")); break; } } } /* THIS IS ONLY A PORTION OF IT void receivefile(uchar *data, int len) { //offtools: receive textures case N_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 { if(p.packet->flags&ENET_PACKET_FLAG_UNSEQUENCED) return; 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(!m_edit) { conoutf(CON_ERROR, "\"getmap\" only works in coop edit mode"); return; } conoutf("getting map..."); addmsg(N_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/fps/%s.ogz", mname); defformatstring(cname)("packages/base/fps/%s-art.cfg", mname); stream *map = openrawfile(fname, "rb"); stream *cfg = openrawfile(cname, "rb"); if(map && cfg) { stream::offset len = map->size(); if(len > 4*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, "ri", N_UPLOADCFG); sendfile(-1, 2, map, "ri", N_UPLOADMAP); if(needclipboard >= 0) needclipboard++; } 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) { fpsent *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/"; } /* * offtools: * helper functions for attachments * TODO: move to a better place :) */ const char* attachtag(int i) { if(i < ATTACH_PARTS || i >= 0) return body[i].tag; else return NULL; } int attachnumbypart(char* part) { for( int i = 0; i < ATTACH_PARTS; i++) { if (strcmp(body[i].part, part) == 0) return i; } return -1; } void playerattach(int p, char* m, int r) { player1->attached.add(p,m,r); addmsg(N_ATTACH, "risi", p, m, r); } void playerdetach(int p) { player1->attached.remove(p); addmsg(N_DETACH, "ri", p); } ICOMMAND(getattachnum, "s", (char *p), intret(attachnumbypart(p))); ICOMMAND(playerattach, "isi", (int *p, char *m, int *r), playerattach(*p,m,*r)); ICOMMAND(playerdetach, "i", (int *p), playerdetach(*p)); } sandboxgamemaker-2.8.2+dfsg/src/fpsgame/collect.h0000644000175000017500000005557712045412564020745 0ustar bofh80bofh80#ifndef PARSEMESSAGES #define collectteambase(s) (!strcmp(s, "good") ? 1 : (!strcmp(s, "evil") ? 2 : 0)) #define collectbaseteam(i) (i==1 ? "good" : (i==2 ? "evil" : NULL)) #ifdef SERVMODE struct collectservmode : servmode #else struct collectclientmode : clientmode #endif { static const int BASERADIUS = 16; static const int BASEHEIGHT = 16; static const int MAXBASES = 20; static const int TOKENRADIUS = 16; static const int TOKENLIMIT = 5; static const int TOKENDIST = 16; static const int SCORELIMIT = 50; struct base { int id, team; vec o; #ifndef SERVMODE vec tokenpos; string info; entitylight light; #endif base() { reset(); } void reset() { o = vec(0, 0, 0); team = 0; } }; struct token { int id, team, droptime; vec o; #ifdef SERVMODE int yaw, dropper; #else entitylight light; #endif token() { reset(); } void reset() { o = vec(0, 0, 0); team = 0; #ifdef SERVMODE dropper = -1; #endif droptime = 0; } }; vector bases; int scores[2]; vector tokens; #ifdef SERVMODE int nexttoken; #endif void resetbases() { bases.shrink(0); tokens.shrink(0); loopk(2) scores[k] = 0; tokens.shrink(0); #ifdef SERVMODE nexttoken = 0; #endif } #ifdef SERVMODE bool addbase(int i, const vec &o, int team) #else bool addbase(int i, const vec &o, int team) #endif { if(i<0 || i>=MAXBASES) return false; while(bases.length()<=i) bases.add(); base &b = bases[i]; b.reset(); b.id = i; b.team = team; b.o = o; return true; } token *findtoken(int id) { loopv(tokens) if(tokens[i].id == id) return &tokens[i]; return NULL; } #ifdef SERVMODE token &droptoken(const vec &o, int yaw, int team, int droptime, int dropper) #else token &droptoken(int id, const vec &o, int team, int droptime) #endif { token &t = tokens.add(); t.o = o; t.team = team; t.droptime = droptime; #ifdef SERVMODE if(++nexttoken < 0) nexttoken = 1; t.id = nexttoken; t.dropper = dropper; t.yaw = yaw; #else t.id = id; #endif return t; } bool removetoken(int id) { loopv(tokens) if(tokens[i].id == id) { tokens.removeunordered(i); return true; } return false; } int totalscore(int team) { return team >= 1 && team <= 2 ? scores[team-1] : 0; } int setscore(int team, int score) { if(team >= 1 && team <= 2) return scores[team-1] = score; return 0; } int addscore(int team, int score) { if(team >= 1 && team <= 2) return scores[team-1] += score; return 0; } bool hidefrags() { return true; } int getteamscore(const char *team) { return totalscore(collectteambase(team)); } void getteamscores(vector &tscores) { loopk(2) if(scores[k]) tscores.add(teamscore(collectbaseteam(k+1), scores[k])); } bool insidebase(const base &b, const vec &o) { float dx = (b.o.x-o.x), dy = (b.o.y-o.y), dz = (b.o.z-o.z); return dx*dx + dy*dy <= BASERADIUS*BASERADIUS && fabs(dz) <= BASEHEIGHT; } #ifdef SERVMODE static const int EXPIRETOKENTIME = 10000; bool notgotbases; collectservmode() : notgotbases(false) {} void reset(bool empty) { resetbases(); notgotbases = !empty; } void cleanup() { reset(false); } void setup() { reset(false); if(notgotitems || ments.empty()) return; loopv(ments) { entity &e = ments[i]; if(e.type != FLAG || e.attr[1] < 1 || e.attr[1] > 2) continue; if(!addbase(bases.length(), e.o, e.attr[1])) break; } notgotbases = false; } void newmap() { reset(true); } #if 0 void losetokens(clientinfo *ci) { if(notgotbases || ci->state.tokens <= 0) return; sendf(-1, 1, "ri2", N_LOSETOKENS, ci->clientnum); ci->state.tokens = 0; } #endif void droptokens(clientinfo *ci, bool penalty = false) { if(notgotbases) return; int team = collectteambase(ci->team), totalenemy = penalty ? 0 : ci->state.tokens, totalfriendly = 1, expired = 0; packetbuf p(300, ENET_PACKET_FLAG_RELIABLE); loopvrev(tokens) { token &t = tokens[i]; if(t.dropper == ci->clientnum && (t.team == team ? ++totalfriendly > TOKENLIMIT : ++totalenemy > TOKENLIMIT)) { if(!expired) putint(p, N_EXPIRETOKENS); expired++; putint(p, t.id); tokens.removeunordered(i); } } if(expired) putint(p, -1); putint(p, N_DROPTOKENS); putint(p, ci->clientnum); putint(p, int(ci->state.o.x*DMF)); putint(p, int(ci->state.o.y*DMF)); putint(p, int(ci->state.o.z*DMF)); int numdrops = 1 + (penalty ? 0 : ci->state.tokens), yaw = rnd(360); loopi(numdrops) { token &t = droptoken(ci->state.o, yaw + (i*360)/numdrops, !i ? team : -team, lastmillis, ci->clientnum); putint(p, t.id); putint(p, t.team); putint(p, t.yaw); } putint(p, -1); sendpacket(-1, 1, p.finalize()); ci->state.tokens = 0; } void leavegame(clientinfo *ci, bool disconnecting = false) { ci->state.tokens = 0; } void died(clientinfo *ci, clientinfo *actor) { droptokens(ci, !actor || isteam(actor->team, ci->team)); } bool canchangeteam(clientinfo *ci, const char *oldteam, const char *newteam) { return collectteambase(newteam) > 0; } void changeteam(clientinfo *ci, const char *oldteam, const char *newteam) { } void deposittokens(clientinfo *ci, int i) { if(notgotbases || !bases.inrange(i) || ci->state.state!=CS_ALIVE || !ci->team[0] || ci->state.tokens <= 0) return; base &b = bases[i]; if(!collectbaseteam(b.team)) return; int team = collectteambase(ci->team); if(b.team==team) return; ci->state.flags += ci->state.tokens; int score = addscore(team, ci->state.tokens); sendf(-1, 1, "ri7", N_DEPOSITTOKENS, ci->clientnum, i, ci->state.tokens, team, score, ci->state.flags); ci->state.tokens = 0; if(score >= SCORELIMIT) startintermission(); } void taketoken(clientinfo *ci, int id) { if(notgotbases || ci->state.state!=CS_ALIVE || !ci->team[0]) return; token *t = findtoken(id); if(!t) return; int team = collectteambase(ci->team); if(t->team != team && (t->team > 0 || -t->team == team) && ci->state.tokens < TOKENLIMIT) ci->state.tokens++; sendf(-1, 1, "ri4", N_TAKETOKEN, ci->clientnum, id, ci->state.tokens); } void update() { if(gamemillis>=gamelimit || notgotbases) return; vector resets; loopvrev(tokens) { token &t = tokens[i]; if(lastmillis - t.droptime >= EXPIRETOKENTIME) { resets.add(t.id); tokens.removeunordered(i); } } if(resets.length()) sendf(-1, 1, "rivi", N_EXPIRETOKENS, resets.length(), resets.getbuf(), -1); } void initclient(clientinfo *ci, packetbuf &p, bool connecting) { putint(p, N_INITTOKENS); loopk(2) putint(p, scores[k]); putint(p, tokens.length()); loopv(tokens) { token &t = tokens[i]; putint(p, t.id); putint(p, t.team); putint(p, t.yaw); putint(p, int(t.o.x*DMF)); putint(p, int(t.o.y*DMF)); putint(p, int(t.o.z*DMF)); } loopv(clients) if(clients[i]->state.state == CS_ALIVE && clients[i]->state.tokens > 0) { putint(p, clients[i]->clientnum); putint(p, clients[i]->state.tokens); } putint(p, -1); } void parsebases(ucharbuf &p, bool commit) { int numbases = getint(p); loopi(numbases) { int team = getint(p); vec o; loopk(3) o[k] = max(getint(p)/DMF, 0.0f); if(p.overread()) break; if(commit && notgotbases) { addbase(i, o, team); } } if(commit && notgotbases) { notgotbases = false; } } }; #else static const int TOKENHEIGHT = 5; static const int RESPAWNSECS = 5; void preload() { preloadmodel("base/red"); preloadmodel("base/blue"); preloadmodel("skull/red"); preloadmodel("skull/blue"); } void drawblip(fpsent *d, float x, float y, float s, const vec &pos) { float scale = calcradarscale(); vec dir = d->o; dir.sub(pos).div(scale); float size = 0.05f, xoffset = -size, yoffset = -size, dist = dir.magnitude2(), maxdist = 1 - 0.05f - 0.05f; if(dist >= maxdist) dir.mul(maxdist/dist); dir.rotate_around_z(-camera1->yaw*RAD); drawradar(x + s*0.5f*(1.0f + dir.x + xoffset), y + s*0.5f*(1.0f + dir.y + yoffset), size*s); } void drawblip(fpsent *d, float x, float y, float s, int i) { base &b = bases[i]; settexture(b.team==collectteambase(player1->team) ? "data/fps/hud/blip_blue.png" : "data/fps/hud/blip_red.png", 3); drawblip(d, x, y, s, b.o); } int clipconsole(int w, int h) { return (h*(1 + 1 + 10))/(4*10); } void drawhud(fpsent *d, int w, int h) { if(d->state == CS_ALIVE && d->tokens > 0) { int x = HICON_X + 3*HICON_STEP + (d->quadmillis ? HICON_SIZE + HICON_SPACE : 0); glPushMatrix(); glScalef(2, 2, 1); draw_textf("%d", (x + HICON_SIZE + HICON_SPACE)/2, HICON_TEXTY/2, d->tokens); glPopMatrix(); drawicon(HICON_TOKEN, x, HICON_Y); } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int s = 1800/4, x = 1800*w/h - s - s/10, y = s/10; glColor4f(1, 1, 1, minimapalpha); if(minimapalpha >= 1) glDisable(GL_BLEND); bindminimap(); drawminimap(d, x, y, s); if(minimapalpha >= 1) glEnable(GL_BLEND); glColor3f(1, 1, 1); float margin = 0.04f, roffset = s*margin, rsize = s + 2*roffset; settexture("data/fps/hud/radar.png", 3); drawradar(x - roffset, y - roffset, rsize); #if 0 settexture("data/fps/hud/compass.png", 3); glPushMatrix(); glTranslatef(x - roffset + 0.5f*rsize, y - roffset + 0.5f*rsize, 0); glRotatef(camera1->yaw + 180, 0, 0, -1); drawradar(-0.5f*rsize, -0.5f*rsize, rsize); glPopMatrix(); #endif loopv(bases) { base &b = bases[i]; if(!collectbaseteam(b.team)) continue; drawblip(d, x, y, s, i); } if(d->state == CS_DEAD) { int wait = respawnwait(d); if(wait>=0) { glPushMatrix(); glScalef(2, 2, 1); bool flash = wait>0 && d==player1 && lastspawnattempt>=d->lastpain && lastmillis < lastspawnattempt+100; draw_textf("%s%d", (x+s/2)/2-(wait>=10 ? 28 : 16), (y+s/2)/2-32, flash ? "\f3" : "", wait); glPopMatrix(); } } } void rendergame() { int team = collectteambase(player1->team); vec theight(0, 0, 0); abovemodel(theight, "skull/red"); loopv(bases) { base &b = bases[i]; const char *basename = b.team==team ? "banana/blue" : "banana/red"; rendermodel(&b.light, basename, ANIM_MAPMODEL|ANIM_LOOP, b.o, 0, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED); float fradius = 1.0f, fheight = 0.5f; regular_particle_flame(PART_FLAME, vec(b.tokenpos.x, b.tokenpos.y, b.tokenpos.z - 4.5f), fradius, fheight, b.team==team ? 0x2020FF : 0x802020, 3, 2.0f); vec tokenpos(b.tokenpos); tokenpos.z -= theight.z/2 + sinf(lastmillis/100.0f)/20; rendermodel(&b.light, b.team==team ? "skull/blue" : "skull/red", ANIM_MAPMODEL|ANIM_LOOP, tokenpos, lastmillis/10.0f, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED); formatstring(b.info)("%d", totalscore(b.team)); vec above(b.tokenpos); above.z += TOKENHEIGHT; if(b.info[0]) particle_text(above, b.info, PART_TEXT, 1, b.team==team ? 0x6496FF : 0xFF4B19, 2.0f); } loopv(tokens) { token &t = tokens[i]; vec p = t.o; p.z += 1+sinf(lastmillis/100.0+t.o.x+t.o.y)/20; rendermodel(&t.light, t.team == team || (t.team < 0 && -t.team != team) ? "skull/blue" : "skull/red", ANIM_MAPMODEL|ANIM_LOOP, p, lastmillis/10.0f, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED); } fpsent *exclude = isthirdperson() ? NULL : hudplayer(); loopv(players) { fpsent *d = players[i]; if(d->state != CS_ALIVE || d->tokens <= 0 || d == exclude) continue; vec pos = d->abovehead().add(vec(0, 0, 1)); entitylight light; lightreaching(pos, light.color, light.dir, true); int dteam = collectteambase(d->team); loopj(d->tokens) { rendermodel(&light, dteam != team ? "skull/blue" : "skull/red", ANIM_MAPMODEL|ANIM_LOOP, pos, d->yaw+90, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED); pos.z += TOKENHEIGHT + 1; } } } void setup() { resetbases(); vector radarents; loopv(entities::ents) { extentity *e = entities::ents[i]; if(e->type!=FLAG) continue; if(e->attr[1]<1 || e->attr[1]>2) continue; int index = bases.length(); if(!addbase(index, e->o, e->attr[1])) continue; base &b = bases[index]; b.tokenpos = b.o; abovemodel(b.tokenpos, "banana/blue"); b.tokenpos.z += TOKENHEIGHT-2; b.light = e->light; } } void senditems(packetbuf &p) { putint(p, N_INITTOKENS); putint(p, bases.length()); loopv(bases) { base &b = bases[i]; putint(p, b.team); loopk(3) putint(p, int(b.o[k]*DMF)); } } vec movetoken(const vec &o, int yaw) { static struct dropent : physent { dropent() { type = ENT_CAMERA; collidetype = COLLIDE_AABB; } } d; d.o = o; d.o.z += 4; d.radius = d.xradius = d.yradius = 4; d.eyeheight = d.aboveeye = 4; vecfromyawpitch(yaw, 0, 1, 0, d.vel); d.o.add(vec(d.vel).mul(4)); movecamera(&d, d.vel, TOKENDIST-4, 1); if(!droptofloor(d.o, 4, 4)) return vec(-1, -1, -1); return d.o; } void parsetokens(ucharbuf &p, bool commit) { loopk(2) { int score = getint(p); if(commit) scores[k] = score; } int numtokens = getint(p); loopi(numtokens) { int id = getint(p), team = getint(p), yaw = getint(p); vec o; loopk(3) o[k] = getint(p)/DMF; if(p.overread()) break; o = movetoken(o, yaw); if(o.z >= 0) droptoken(id, o, team, lastmillis); } for(;;) { int cn = getint(p); if(cn < 0) break; int tokens = getint(p); if(p.overread()) break; fpsent *d = cn == player1->clientnum ? player1 : newclient(cn); if(d) d->tokens = tokens; } } void expiretoken(int id) { token *t = findtoken(id); if(!t) return; playsound(S_ITEMAMMO, &t->o); removetoken(id); } void taketoken(fpsent *d, int id, int total) { int team = collectteambase(d->team); token *t = findtoken(id); if(t) { playsound(t->team == team || (t->team < 0 && -t->team != team) ? S_ITEMAMMO : S_ITEMHEALTH, d!=player1 ? &d->o : NULL); removetoken(id); } d->tokens = total; } void droptoken(fpsent *d, int id, const vec &o, int team, int yaw, int n) { vec pos = movetoken(o, yaw); if(pos.z < 0) return; token &t = droptoken(id, pos, team, lastmillis); lightreaching(vec(o).add(vec(0, 0, TOKENHEIGHT)), t.light.color, t.light.dir, true); if(!n) playsound(S_ITEMSPAWN, &d->o); } void deposittokens(fpsent *d, int i, int deposited, int team, int score, int flags) { if(bases.inrange(i)) { base &b = bases[i]; playsound(S_FLAGSCORE, d != player1 ? &b.tokenpos : NULL); } d->tokens = 0; d->flags = flags; setscore(team, score); } void checkitems(fpsent *d) { if(d->state!=CS_ALIVE) return; vec o = d->feetpos(); if(d->tokens > 0) { int team = collectteambase(d->team); loopv(bases) { base &b = bases[i]; if(!collectbaseteam(b.team) || b.team == team) continue; if(insidebase(b, o)) { addmsg(N_DEPOSITTOKENS, "rci", d, i); d->tokens = 0; } } } if(d->tokens < TOKENLIMIT) loopv(tokens) { token &t = tokens[i]; if(o.dist(t.o) < TOKENRADIUS && d->lastcollect.dist(t.o) >= TOKENRADIUS && (lookupmaterial(o)&MATF_CLIP) != MAT_GAMECLIP && (lookupmaterial(t.o)&MATF_CLIP) != MAT_GAMECLIP) addmsg(N_TAKETOKEN, "rci", d, t.id); } d->lastcollect = o; } int respawnwait(fpsent *d) { return max(0, RESPAWNSECS-(lastmillis-d->lastpain)/1000); } void pickspawn(fpsent *d) { findplayerspawn(d, -1, collectteambase(d->team)); } const char *prefixnextmap() { return "ctf_"; } bool aicheck(fpsent *d, ai::aistate &b) { if(ai::badhealth(d)) return false; int team = collectteambase(d->team), best = -1; float bestdist = 1e16f; if(d->tokens > 0) { loopv(bases) { base &b = bases[i]; if(b.team == team) continue; float dist = d->o.dist(b.o); if(best < 0 || dist < bestdist) { best = i; bestdist = dist; } } if(best < 0 || !ai::makeroute(d, b, bases[best].o)) return false; d->ai->switchstate(b, ai::AI_S_PURSUE, ai::AI_T_AFFINITY, -(best+1)); } else { loopv(tokens) { token &t = tokens[i]; float dist = d->o.dist(t.o)/(t.team != team && (t.team > 0 || -t.team == team) ? 10.0f : 1.0f); if(best < 0 || dist < bestdist) { best = i; bestdist = dist; } } if(best < 0 || !ai::makeroute(d, b, tokens[best].o)) return false; d->ai->switchstate(b, ai::AI_S_PURSUE, ai::AI_T_AFFINITY, tokens[best].id); } return true; } void aifind(fpsent *d, ai::aistate &b, vector &interests) { vec pos = d->feetpos(); int team = collectteambase(d->team); if(d->tokens > 0) { loopv(bases) { base &b = bases[i]; if(b.team == team) continue; ai::interest &n = interests.add(); n.state = ai::AI_S_PURSUE; n.node = ai::closestwaypoint(b.o, ai::SIGHTMIN, true); n.target = -(i+1); n.targtype = ai::AI_T_AFFINITY; n.score = pos.squaredist(b.o)/(d->tokens > 2 ? 1e3f : 1e2f); } } if(d->tokens < TOKENLIMIT) loopv(tokens) { token &t = tokens[i]; ai::interest &n = interests.add(); n.state = ai::AI_S_PURSUE; n.node = ai::closestwaypoint(t.o, ai::SIGHTMIN, true); n.target = t.id; n.targtype = ai::AI_T_AFFINITY; n.score = pos.squaredist(t.o)/(t.team != team && (t.team > 0 || -t.team == team) ? 10.0f : 1.0f); } } bool aipursue(fpsent *d, ai::aistate &b) { if(b.target < 0) { if(d->tokens <= 0 || !bases.inrange(-(b.target+1))) return false; base &g = bases[-(b.target+1)]; if(g.team == collectteambase(d->team)) return false; return ai::makeroute(d, b, g.o); } else if(b.target > 0) { token *t = findtoken(b.target); if(t) return ai::makeroute(d, b, t->o); } return false; } }; #endif #elif SERVMODE case N_INITTOKENS: if(smode==&collectmode) collectmode.parsebases(p, (ci->state.state!=CS_SPECTATOR || ci->privilege || ci->local) && !strcmp(ci->clientmap, smapname)); break; case N_TAKETOKEN: { int id = getint(p); if((ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege) && cq && smode==&collectmode) collectmode.taketoken(cq, id); break; } case N_DEPOSITTOKENS: { int id = getint(p); if((ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege) && cq && smode==&collectmode) collectmode.deposittokens(cq, id); break; } #else case N_INITTOKENS: collectmode.parsetokens(p, m_collect); break; case N_TAKETOKEN: { int ocn = getint(p), id = getint(p), total = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_collect) collectmode.taketoken(o, id, total); break; } case N_EXPIRETOKENS: for(;;) { int id = getint(p); if(p.overread() || id < 0) break; if(m_collect) collectmode.expiretoken(id); } break; case N_DROPTOKENS: { int ocn = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); vec droploc; loopk(3) droploc[k] = getint(p)/DMF; for(int n = 0;; n++) { int id = getint(p); if(id < 0) break; int team = getint(p), yaw = getint(p); if(p.overread()) break; if(o && m_collect) collectmode.droptoken(d, id, droploc, team, yaw, n); } break; } case N_DEPOSITTOKENS: { int ocn = getint(p), base = getint(p), deposited = getint(p), team = getint(p), score = getint(p), flags = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_collect) collectmode.deposittokens(o, base, deposited, team, score, flags); break; } #endif sandboxgamemaker-2.8.2+dfsg/src/fpsgame/render.cpp0000644000175000017500000003715012075407135021116 0ustar bofh80bofh80#include "game.h" namespace game { vector bestplayers; vector bestteams; VARP(ragdoll, 0, 1, 1); VARP(ragdollmillis, 0, 10000, 300000); VARP(ragdollfade, 0, 1000, 300000); VARFP(playermodel, 0, 0, 5, { if(player1->clientnum < 0) player1->playermodel = playermodel; }); VARP(forceplayermodels, 0, 0, 1); vector ragdolls; void saveragdoll(fpsent *d) { if(!d->ragdoll || !ragdollmillis || (!ragdollfade && lastmillis > d->lastpain + ragdollmillis)) return; fpsent *r = new fpsent(*d); r->lastupdate = ragdollfade && lastmillis > d->lastpain + max(ragdollmillis - ragdollfade, 0) ? lastmillis - max(ragdollmillis - ragdollfade, 0) : d->lastpain; 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) { fpsent *d = ragdolls[i]; if(lastmillis > d->lastupdate + ragdollmillis) { delete ragdolls.remove(i--); continue; } moveragdoll(d); } } static const playermodelinfo playermodels[] = { { "captaincannon", "captaincannon/blue", "captaincannon/red", "captaincannon/hudguns", NULL, NULL, { NULL, NULL, NULL }, "captaincannon", "captaincannon_blue", "captaincannon_red", true }, { "captaincannon/blue", "captaincannon/blue", "captaincannon/red", "captaincannon/hudguns", NULL, NULL, { NULL, NULL, NULL }, "captaincannon_blue", "captaincannon_blue", "captaincannon_red", true }, { "captaincannon/red", "captaincannon/blue", "captaincannon/red", "captaincannon/hudguns", NULL, NULL, { NULL, NULL, NULL }, "captaincannon_red", "captaincannon_blue", "captaincannon_red", true }, { "ogre", "ogre/blue", "ogre/red", NULL, NULL, NULL, { NULL, NULL, NULL }, "ogre", "ogre", "ogre", false }, { "ogre/blue", "ogre/blue", "ogre/red", NULL, NULL, NULL, { NULL, NULL, NULL }, "ogre", "ogre", "ogre", false }, { "ogre/red", "ogre/blue", "ogre/red", NULL, NULL, NULL, { NULL, NULL, NULL }, "ogre", "ogre", "ogre", false }, }; int chooserandomplayermodel(int seed) { return (seed&0xFFFF)%(sizeof(playermodels)/sizeof(playermodels[0])); } const playermodelinfo *getplayermodelinfo(int n) { if(size_t(n) >= sizeof(playermodels)/sizeof(playermodels[0])) return NULL; return &playermodels[n]; } const playermodelinfo &getplayermodelinfo(fpsent *d) { const playermodelinfo *mdl = getplayermodelinfo(d==player1 || forceplayermodels ? playermodel : d->playermodel); if(!mdl) mdl = getplayermodelinfo(playermodel); return *mdl; } void changedplayermodel() { if(player1->clientnum < 0) player1->playermodel = playermodel; if(player1->ragdoll) cleanragdoll(player1); loopv(ragdolls) { fpsent *d = ragdolls[i]; if(!d->ragdoll) continue; if(!forceplayermodels) { const playermodelinfo *mdl = getplayermodelinfo(d->playermodel); if(mdl) continue; } cleanragdoll(d); } loopv(players) { fpsent *d = players[i]; if(d == player1 || !d->ragdoll) continue; if(!forceplayermodels) { const playermodelinfo *mdl = getplayermodelinfo(d->playermodel); if(mdl) continue; } cleanragdoll(d); } } void preloadplayermodel() { loopi(sizeof(playermodels)/sizeof(playermodels[0])) { const playermodelinfo *mdl = getplayermodelinfo(i); if(!mdl) break; if(i != playermodel && (!multiplayer(false) || forceplayermodels)) continue; if(m_teammode) { preloadmodel(mdl->blueteam); preloadmodel(mdl->redteam); } else preloadmodel(mdl->ffa); if(mdl->vwep) preloadmodel(mdl->vwep); if(mdl->quad) preloadmodel(mdl->quad); loopj(3) if(mdl->armour[j]) preloadmodel(mdl->armour[j]); } } VAR(testquad, 0, 0, 1); VAR(testarmour, 0, 0, 1); VAR(testteam, 0, 0, 3); void renderplayer(fpsent *d, const playermodelinfo &mdl, int team, float fade, bool mainpass) { int lastaction = d->lastaction, hold = mdl.vwep || d->gunselect==GUN_PISTOL ? 0 : (ANIM_HOLD1+d->gunselect)|ANIM_LOOP, attack = ANIM_ATTACK1+d->gunselect, delay = mdl.vwep ? 300 : guns[d->gunselect].attackdelay+50; if(intermission && d->state!=CS_DEAD) { lastaction = 0; hold = attack = ANIM_LOSE|ANIM_LOOP; delay = 0; if(m_teammode) loopv(bestteams) { if(!strcmp(bestteams[i], d->team)) { hold = attack = ANIM_WIN|ANIM_LOOP; break; } } else if(bestplayers.find(d)>=0) hold = attack = ANIM_WIN|ANIM_LOOP; } else if(d->state==CS_ALIVE && d->lasttaunt && lastmillis-d->lasttaunt<1000 && lastmillis-d->lastaction>delay) { lastaction = d->lasttaunt; hold = attack = ANIM_TAUNT; delay = 1000; } static const char *vweps[] = {"vwep/fist", "vwep/shotg", "vwep/chaing", "vwep/rocket", "vwep/rifle", "vwep/gl", "vwep/pistol"}; //offtools: add attachments (clothes) int ai = 0; //modelattach a[d->attached.numattachments() + 5]; int num = d->attached.numattachments() + 5; modelattach* a = new modelattach[num]; attachlist &attachments = d->attached; loopv(attachments.list) { int animrule; int animtime; const char* tag = attachtag(attachments.list[i]->part); switch (attachments.list[i]->animrule) { 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[ai++] = modelattach(tag, attachments.list[i]->model, animrule, animtime); } if((!mdl.vwep || d->gunselect!=GUN_FIST) && d->gunselect<=GUN_PISTOL) { int vanim = ANIM_VWEP_IDLE|ANIM_LOOP, vtime = 0; if(lastaction && d->lastattackgun==d->gunselect && lastmillis < lastaction + delay) { vanim = ANIM_VWEP_SHOOT; vtime = lastaction; } a[ai++] = modelattach("tag_weapon", mdl.vwep ? mdl.vwep : vweps[d->gunselect], vanim, vtime); } if(d->state==CS_ALIVE) { if((testquad || d->quadmillis) && mdl.quad) a[ai++] = modelattach("tag_powerup", mdl.quad, ANIM_POWERUP|ANIM_LOOP, 0); if(testarmour || d->armour) { int type = clamp(d->armourtype, (int)A_BLUE, (int)A_YELLOW); if(mdl.armour[type]) a[ai++] = modelattach("tag_shield", mdl.armour[type], ANIM_SHIELD|ANIM_LOOP, 0); } } if(mainpass) { d->muzzle = vec(-1, -1, -1); a[ai++] = modelattach("tag_muzzle", &d->muzzle); } const char *mdlname = mdl.ffa; switch(testteam ? testteam-1 : team) { case 1: mdlname = mdl.blueteam; break; case 2: mdlname = mdl.redteam; break; } renderclient(d, mdlname, a[0].tag ? a : NULL, hold, attack, delay, lastaction, intermission && d->state!=CS_DEAD ? 0 : d->lastpain, fade, ragdoll && mdl.ragdoll); #if 0 if(d->state!=CS_DEAD && d->quadmillis) { entitylight light; rendermodel(&light, "quadrings", ANIM_MAPMODEL|ANIM_LOOP, vec(d->o).sub(vec(0, 0, d->eyeheight/2)), 360*lastmillis/1000.0f, 0, MDL_DYNSHADOW | MDL_CULL_VFC | MDL_CULL_DIST); } #endif DELETEA(a); } VARP(teamskins, 0, 0, 1); void rendergame(bool mainpass) { if(mainpass) ai::render(); if(intermission) { bestteams.shrink(0); bestplayers.shrink(0); if(m_teammode) getbestteams(bestteams); else getbestplayers(bestplayers); } startmodelbatches(); fpsent *exclude = isthirdperson() ? NULL : followingplayer(); loopv(players) { fpsent *d = players[i]; if(d == player1 || d->state==CS_SPECTATOR || d->state==CS_SPAWNING || d->lifesequence < 0 || d == exclude) continue; int team = 0; if(teamskins || m_teammode) team = isteam(player1->team, d->team) ? 1 : 2; renderplayer(d, getplayermodelinfo(d), team, 1, mainpass); copystring(d->info, colorname(d)); if(d->maxhealth>100) { defformatstring(sn)(" +%d", d->maxhealth-100); concatstring(d->info, sn); } if(d->state!=CS_DEAD) particle_text(d->abovehead(), d->info, PART_TEXT, 1, team ? (team==1 ? 0x6496FF : 0xFF4B19) : 0x1EC850, 2.0f); } loopv(ragdolls) { fpsent *d = ragdolls[i]; int team = 0; if(teamskins || m_teammode) team = isteam(player1->team, d->team) ? 1 : 2; 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, getplayermodelinfo(d), team, fade, mainpass); } if(isthirdperson() && !followingplayer()) renderplayer(player1, getplayermodelinfo(player1), teamskins || m_teammode ? 1 : 0, 1, mainpass); rendermonsters(); rendermovables(); entities::renderentities(); renderbouncers(); renderprojectiles(); if(cmode) cmode->rendergame(); endmodelbatches(); } VARP(hudgun, 0, 1, 1); VARP(hudgunsway, 0, 1, 1); VARP(teamhudguns, 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, -1, 0.05f, 1); float swayfade = 0, swayspeed = 0, swaydist = 0; vec swaydir(0, 0, 0); void swayhudgun(int curtime) { fpsent *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)))); } } struct hudent : dynent { hudent() { type = ENT_CAMERA; } } guninterp; SVARP(hudgunsdir, ""); void drawhudmodel(fpsent *d, int anim, float speed = 0, int base = 0) { if(d->gunselect>GUN_PISTOL) return; vec sway; vecfromyawpitch(d->yaw, 0, 0, 1, sway); float steps = swaydist/swaystep*M_PI; sway.mul(swayside*cosf(steps)); sway.z = swayup*(fabs(sinf(steps)) - 1); sway.add(swaydir).add(d->o); if(!hudgunsway) sway = d->o; #if 0 if(player1->state!=CS_DEAD && player1->quadmillis) { float t = 0.5f + 0.5f*sinf(2*M_PI*lastmillis/1000.0f); color.y = color.y*(1-t) + t; } #endif const playermodelinfo &mdl = getplayermodelinfo(d); defformatstring(gunname)("%s/%s", hudgunsdir[0] ? hudgunsdir : mdl.hudguns, guns[d->gunselect].file); if((m_teammode || teamskins) && teamhudguns) concatstring(gunname, d==player1 || isteam(d->team, player1->team) ? "/blue" : "/red"); else if(testteam > 1) concatstring(gunname, testteam==2 ? "/blue" : "/red"); modelattach a[2]; d->muzzle = vec(-1, -1, -1); a[0] = modelattach("tag_muzzle", &d->muzzle); dynent *interp = NULL; if(d->gunselect==GUN_FIST && chainsawhudgun) { anim |= ANIM_LOOP; base = 0; interp = &guninterp; } rendermodel(NULL, gunname, anim, sway, testhudgun ? 0 : d->yaw+90, testhudgun ? 0 : d->pitch, d->roll, MDL_LIGHT|MDL_HUD, interp, a, base, (int)ceil(speed)); } void drawhudgun() { fpsent *d = hudplayer(); if(d->state==CS_SPECTATOR || d->state==CS_EDITING || !hudgun || editmode) { d->muzzle = player1->muzzle = vec(-1, -1, -1); return; } int rtime = guns[d->gunselect].attackdelay; if(d->lastaction && d->lastattackgun==d->gunselect && lastmillis-d->lastactionlastaction); } else { drawhudmodel(d, ANIM_GUN_IDLE|ANIM_LOOP); } } void renderavatar() { drawhudgun(); } vec hudgunorigin(int gun, const vec &from, const vec &to, fpsent *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 preloadweapons() { const playermodelinfo &mdl = getplayermodelinfo(player1); loopi(NUMGUNS) { const char *file = guns[i].file; if(!file) continue; string fname; if((m_teammode || teamskins) && teamhudguns) { formatstring(fname)("%s/%s/blue", hudgunsdir[0] ? hudgunsdir : mdl.hudguns, file); preloadmodel(fname); } else { formatstring(fname)("%s/%s", hudgunsdir[0] ? hudgunsdir : mdl.hudguns, file); preloadmodel(fname); } formatstring(fname)("vwep/%s", file); preloadmodel(fname); } } void preload() { if(hudgun) preloadweapons(); preloadbouncers(); preloadplayermodel(); entities::preloadentities(); if(m_sp) preloadmonsters(); } const char *animname(int i) { i &= 0x7F; if(i >= NUMANIMS) return ""; return animnames[i]; } const int numanims() {return NUMANIMS;} } sandboxgamemaker-2.8.2+dfsg/src/fpsgame/extinfo.h0000644000175000017500000001175112045412564020756 0ustar bofh80bofh80 #define EXT_ACK -1 #define EXT_VERSION 105 #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, max((gamelimit - gamemillis)/1000, 0)); 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, totalsecs); //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.8.2+dfsg/src/fpsgame/fps.cpp0000644000175000017500000007246612056016245020435 0ustar bofh80bofh80#include "game.h" namespace game { bool intermission = false; int maptime = 0, maprealtime = 0, maplimit = -1; int respawnent = -1; int lasthit = 0, lastspawnattempt = 0; int moveentropy = 0; VARP(mouselook, 0, 1, 1); int following = -1, followdir = 0; fpsent *player1 = NULL; // our client vector players; // other clients int savedammo[NUMGUNS]; bool clientoption(const char *arg) { return false; } void setdynlightactivity(int *who, int *active) { if (*who > 32767 || *who <= 0) return; else if (!*active) entities::dynlightsactive[*who] = false; else entities::dynlightsactive[*who] = true; } COMMAND(setdynlightactivity, "ii"); void taunt() { if(player1->state!=CS_ALIVE || player1->physstatelasttaunt<1000) return; player1->lasttaunt = lastmillis; addmsg(N_TAUNT, "rc", player1); } COMMAND(taunt, ""); ICOMMAND(getfollow, "", (), { fpsent *f = followingplayer(); intret(f ? f->clientnum : -1); }); void follow(char *arg) { 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(); clearmonsters(); // all monsters back at their spawns for editing entities::resettriggers(); } clearprojectiles(); clearbouncers(); } fpsent *spawnstate(fpsent *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(N_TRYSPAWN, "rc", player1); player1->respawned = player1->lifesequence; } } else { spawnplayer(player1); showscores(false); // lasthit = 0; if(cmode) cmode->respawned(player1); } } fpsent *pointatplayer() { loopv(players) if(players[i] != player1 && intersect(players[i], player1->o, worldpos)) return players[i]; return NULL; } void stopfollowing() { if(following<0) return; following = -1; followdir = 0; conoutf("follow off"); } fpsent *followingplayer() { if(player1->state!=CS_SPECTATOR || following<0) return NULL; fpsent *target = getclient(following); if(target && target->state!=CS_SPECTATOR) return target; return NULL; } fpsent *hudplayer() { if(thirdperson) return player1; fpsent *target = followingplayer(); return target ? target : player1; } void setupcamera() { fpsent *target = followingplayer(); if(target) { player1->yaw = target->yaw; player1->pitch = target->state==CS_DEAD ? 0 : target->pitch; player1->o = target->o; player1->resetinterp(); } } bool detachcamera() { fpsent *d = hudplayer(); return d->state==CS_DEAD; } bool collidecamera() { switch(player1->state) { case CS_EDITING: return false; case CS_SPECTATOR: return followingplayer()!=NULL; } return true; } VARP(smoothmove, 0, 75, 100); VARP(smoothdist, 0, 32, 64); void predictplayer(fpsent *d, bool move) { d->o = d->newpos; d->yaw = d->newyaw; d->pitch = d->newpitch; d->roll = d->newroll; 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; d->roll += d->deltaroll*k; } } void otherplayers(int curtime) { loopv(players) { fpsent *d = players[i]; if(d == player1 || d->ai) continue; if(d->state==CS_DEAD && d->ragdoll) moveragdoll(d); else if(!intermission) { if(lastmillis - d->lastaction >= d->gunwait) d->gunwait = 0; if(d->quadmillis) entities::checkquad(curtime, d); } const int lagtime = totalmillis-d->lastupdate; if(!lagtime || intermission) continue; else if(lagtime>1000 && d->state==CS_ALIVE) { d->state = CS_LAGGED; continue; } if(d->state==CS_ALIVE || d->state==CS_EDITING) { if(smoothmove && d->smoothmillis>0) predictplayer(d, true); else moveplayer(d, 1, false); } else if(d->state==CS_DEAD && !d->ragdoll && lastmillis-d->lastpain<2000) moveplayer(d, 1, true); } } 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 updateworld() // main game update loop { if(!maptime) { maptime = lastmillis; maprealtime = totalmillis; return; } if(!curtime) { gets2c(); if(player1->clientnum>=0) c2sinfo(); return; } physicsframe(); ai::navigate(); if(player1->state != CS_DEAD && !intermission) { if(player1->quadmillis) entities::checkquad(curtime, player1); } updateweapons(curtime); otherplayers(curtime); ai::update(); moveragdolls(); gets2c(); updatemovables(curtime); updatemonsters(curtime); if(player1->state == CS_DEAD) { if(player1->ragdoll) moveragdoll(player1); else if(lastmillis-player1->lastpain<2000) { player1->move = player1->strafe = 0; moveplayer(player1, 10, true); } } else if(!intermission) { if(player1->ragdoll) cleanragdoll(player1); if(!mouselook) { player1->move = clamp(1, -1, moveentropy); if(moveentropy < 0) moveentropy += min(-moveentropy, curtime); else moveentropy -= min(moveentropy, curtime); } moveplayer(player1, 10, true); swayhudgun(curtime); entities::checkitems(player1); if(m_sp) { if(slowmosp) checkslowmo(); if(m_classicsp) entities::checktriggers(); } else if(cmode) cmode->checkitems(player1); } if(player1->clientnum>=0) c2sinfo(); // do this last, to reduce the effective frame lag } void spawnplayer(fpsent *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) { player1->attacking = false; 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(); } } // inputs void doattack(bool on) { if(intermission) return; if((player1->attacking = on)) respawn(); } ICOMMAND(attack, "D", (int *down), { doattack(*down!=0); }); bool canjump() { if(!intermission) respawn(); return player1->state!=CS_DEAD && !intermission; } bool allowmove(physent *d) { if(d->type!=ENT_PLAYER) return true; return !((fpsent *)d)->lasttaunt || lastmillis-((fpsent *)d)->lasttaunt>=1000; } VARP(hitsound, 0, 0, 1); void damaged(int damage, fpsent *d, fpsent *actor, bool local) { if((d->state!=CS_ALIVE && d->state != CS_LAGGED && d->state != CS_SPAWNING) || intermission) return; if(local) damage = d->dodamage(damage); else if(actor==player1) return; fpsent *h = hudplayer(); if(h!=player1 && actor==h && d!=actor) { if(hitsound && lasthit != lastmillis) playsound(S_HIT); lasthit = lastmillis; } if(d==h) { damageblend(damage); damagecompass(damage, actor->o); } damageeffect(damage, d, d!=h); ai::damaged(d, actor); if(m_sp && slowmosp && d==player1 && d->health < 1) d->health = 1; if(d->health<=0) { if(local) killed(d, actor); } else if(d==h) playsound(S_PAIN); else playsound(S_PAIN, &d->o); } VARP(deathscore, 0, 1, 1); void deathstate(fpsent *d, bool restore) { d->state = CS_DEAD; d->lastpain = lastmillis; if(!restore) gibeffect(max(-d->health, 0), d->vel, d); if(d==player1) { if(deathscore) showscores(true); disablezoom(); if(!restore) loopi(NUMGUNS) savedammo[i] = player1->ammo[i]; d->attacking = false; if(!restore) d->deaths++; //d->pitch = 0; d->roll = 0; playsound(S_DIE); } else { d->move = d->strafe = 0; d->resetinterp(); d->smoothmillis = 0; playsound(S_DIE, &d->o); } } void killed(fpsent *d, fpsent *actor) { if(d->state==CS_EDITING) { d->editstate = CS_DEAD; if(d==player1) d->deaths++; else d->resetinterp(); return; } else if((d->state!=CS_ALIVE && d->state != CS_LAGGED && d->state != CS_SPAWNING) || intermission) return; fpsent *h = followingplayer(); if(!h) h = player1; int contype = d==h || actor==h ? CON_FRAG_SELF : CON_FRAG_OTHER; string dname, aname; copystring(dname, d==player1 ? "you" : colorname(d)); copystring(aname, actor==player1 ? "you" : colorname(actor)); if(d==actor || actor->type==ENT_INANIMATE) conoutf(contype, "\f2%s did something very dangerous%s", dname, d==player1 ? "!" : ""); deathstate(d); ai::killed(d, actor); } void timeupdate(int secs) { if(secs > 0) { maplimit = lastmillis + secs*1000; } else { intermission = true; player1->attacking = false; if(cmode) cmode->gameover(); conoutf(CON_GAMEINFO, "\f2intermission:"); conoutf(CON_GAMEINFO, "\f2game has ended!"); showscores(true); disablezoom(); if(identexists("intermission")) execute("intermission"); } } ICOMMAND(getfrags, "", (), intret(player1->frags)); ICOMMAND(getflags, "", (), intret(player1->flags)); ICOMMAND(getdeaths, "", (), intret(player1->deaths)); ICOMMAND(getaccuracy, "", (), intret((player1->totaldamage*100)/max(player1->totalshots, 1))); ICOMMAND(gettotaldamage, "", (), intret(player1->totaldamage)); ICOMMAND(gettotalshots, "", (), intret(player1->totalshots)); vector clients; fpsent *newclient(int cn) // ensure valid entity { 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]) { fpsent *d = new fpsent; d->clientnum = cn; clients[cn] = d; players.add(d); } return clients[cn]; } fpsent *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) { if(!clients.inrange(cn)) return; if(following==cn) { if(followdir) nextfollow(followdir); else stopfollowing(); } unignore(cn); fpsent *d = clients[cn]; if(!d) return; if(notify && d->name[0]) conoutf("player %s disconnected", colorname(d)); removeweapons(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 fpsent); players.add(player1); } 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() { clearmovables(); clearmonsters(); clearprojectiles(); clearbouncers(); clearragdolls(); // reset perma-state loopv(players) { fpsent *d = players[i]; d->frags = d->flags = 0; d->deaths = 0; d->totaldamage = 0; d->totalshots = 0; d->maxhealth = 100; d->lifesequence = -1; d->respawned = d->suicided = -2; } setclientmode(); intermission = false; maptime = maprealtime = 0; maplimit = -1; 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 != playermodel) switchplayermodel(playermodel); showscores(false); disablezoom(); lasthit = 0; if(identexists("mapstart")) execute("mapstart"); } void startmap(const char *name) // called just after a map load { ai::savewaypoints(); ai::clearwaypoints(true); for(int i = 0; i != 32767; i++) { entities::dynlightsactive[i] = true; } respawnent = -1; // so we don't respawn at an old spot if(!m_mp(gamemode)) spawnplayer(player1); else findplayerspawn(player1, -1); entities::resetspawns(); 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(o->type) { case ENT_AI: if(dir.z > 0) stackmonster((monster *)o, d); break; case ENT_INANIMATE: if(dir.z > 0) stackmovable((movable *)o, d); break; } } void msgsound(int n, physent *d) { if(!d || d==player1) { addmsg(N_SOUND, "ci", d, n); playsound(n); } else { if(d->type==ENT_PLAYER && ((fpsent *)d)->ai) addmsg(N_SOUND, "ci", d, n); playsound(n, &d->o); } } int numdynents() { return players.length()+monsters.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(fpsent *d, const char *name, const char *prefix) { if(!name) name = d->name; if(name[0] && !duplicatename(d, name) && d->aitype == AI_NONE) return name; static string cname[3]; static int cidx = 0; cidx = (cidx+1)%3; formatstring(cname[cidx])(d->aitype == AI_NONE ? "%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 && ((fpsent *)d)->ai)) { if(d->state!=CS_ALIVE) return; fpsent *pl = (fpsent *)d; if(!m_mp(gamemode)) killed(pl, pl); else if(pl->suicided!=pl->lifesequence) { addmsg(N_SUICIDE, "rc", pl); pl->suicided = pl->lifesequence; } } else if(d->type==ENT_AI) suicidemonster((monster *)d); else if(d->type==ENT_INANIMATE) suicidemovable((movable *)d); } ICOMMAND(nap, "", (), suicide(player1)); bool needminimap() { return m_ctf || m_protect || m_hold || m_capture || m_collect; } void drawicon(int icon, float x, float y, float sz) { settexture("data/fps/hud/items"); glBegin(GL_TRIANGLE_STRIP); 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, ty+tsz); glVertex2f(x, y+sz); glTexCoord2f(tx+tsz, ty+tsz); glVertex2f(x+sz, 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; } } int ammohudup[3] = { GUN_CG, GUN_RL, GUN_GL }, ammohuddown[3] = { GUN_RIFLE, GUN_SG, GUN_PISTOL }, ammohudcycle[7] = { -1, -1, -1, -1, -1, -1, -1 }; ICOMMAND(ammohudup, "V", (tagval *args, int numargs), { loopi(3) ammohudup[i] = i < numargs ? getweapon(args[i].getstr()) : -1; }); ICOMMAND(ammohuddown, "V", (tagval *args, int numargs), { loopi(3) ammohuddown[i] = i < numargs ? getweapon(args[i].getstr()) : -1; }); ICOMMAND(ammohudcycle, "V", (tagval *args, int numargs), { loopi(7) ammohudcycle[i] = i < numargs ? getweapon(args[i].getstr()) : -1; }); VARP(ammohud, 0, 1, 1); void drawammohud(fpsent *d) { float x = HICON_X + 2*HICON_STEP, y = HICON_Y, sz = HICON_SIZE; glPushMatrix(); glScalef(1/3.2f, 1/3.2f, 1); float xup = (x+sz)*3.2f, yup = y*3.2f + 0.1f*sz; loopi(3) { int gun = ammohudup[i]; if(gun < GUN_FIST || gun > GUN_PISTOL || gun == d->gunselect || !d->ammo[gun]) continue; drawicon(HICON_FIST+gun, xup, yup, sz); yup += sz; } float xdown = x*3.2f - sz, ydown = (y+sz)*3.2f - 0.1f*sz; loopi(3) { int gun = ammohuddown[3-i-1]; if(gun < GUN_FIST || gun > GUN_PISTOL || gun == d->gunselect || !d->ammo[gun]) continue; ydown -= sz; drawicon(HICON_FIST+gun, xdown, ydown, sz); } int offset = 0, num = 0; loopi(7) { int gun = ammohudcycle[i]; if(gun < GUN_FIST || gun > GUN_PISTOL) continue; if(gun == d->gunselect) offset = i + 1; else if(d->ammo[gun]) num++; } float xcycle = (x+sz/2)*3.2f + 0.5f*num*sz, ycycle = y*3.2f-sz; loopi(7) { int gun = ammohudcycle[(i + offset)%7]; if(gun < GUN_FIST || gun > GUN_PISTOL || gun == d->gunselect || !d->ammo[gun]) continue; xcycle -= sz; drawicon(HICON_FIST+gun, xcycle, ycycle, sz); } glPopMatrix(); } void drawhudicons(fpsent *d) { glPushMatrix(); glScalef(2, 2, 1); draw_textf("%d", (HICON_X + HICON_SIZE + HICON_SPACE)/2, HICON_TEXTY/2, d->state==CS_DEAD ? 0 : d->health); if(d->state!=CS_DEAD) { if(d->armour) draw_textf("%d", (HICON_X + HICON_STEP + HICON_SIZE + HICON_SPACE)/2, HICON_TEXTY/2, d->armour); draw_textf("%d", (HICON_X + 2*HICON_STEP + HICON_SIZE + HICON_SPACE)/2, HICON_TEXTY/2, d->ammo[d->gunselect]); } glPopMatrix(); drawicon(HICON_HEALTH, HICON_X, HICON_Y); if(d->state!=CS_DEAD) { if(d->armour) drawicon(HICON_BLUE_ARMOUR+d->armourtype, HICON_X + HICON_STEP, HICON_Y); drawicon(HICON_FIST+d->gunselect, HICON_X + 2*HICON_STEP, HICON_Y); if(d->quadmillis) drawicon(HICON_QUAD, HICON_X + 3*HICON_STEP, HICON_Y); if(ammohud) drawammohud(d); } } void gameplayhud(int w, int 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); fpsent *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); } fpsent *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) { fpsent *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; else if(teamcrosshair) { dynent *o = intersectclosest(d->o, worldpos, d); if(o && o->type==ENT_PLAYER && isteam(((fpsent *)o)->team, d->team)) { crosshair = 1; r = g = 0; } } if(crosshair!=1 && !editmode && !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 fpsent *d = (fpsent *)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 } bool showenthelpers() { if(m_edit || editmode) return true; return false; } bool allowdoublejump(physent *d) {return false;} void updatecamera() {} bool mousemove(int &dx, int &dy, float &cursens) { if(!mouselook) { //remember, vertical coordinates are flipped moveentropy -= dy * cursens; moveentropy = clamp(500, -500, moveentropy); dy = 0; } //we return false since we don't want to do yaw manipulation here return false; } bool recomputecamera(physent *&camera1, physent &tempcamera, bool &detachedcamera, float &thirdpersondistance) {return false;} void writemapdata(stream *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 *autoexec() { return "autoexec.cfg"; } const char *savedservers() { return "data/fps/servers.cfg"; } void loadconfigs() { execfile("auth.cfg", false); } 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(N_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 *dir, char* anim, int num) {} } sandboxgamemaker-2.8.2+dfsg/src/fpsgame/movable.cpp0000644000175000017500000001460512045412564021263 0ustar bofh80bofh80// movable.cpp: implements physics for inanimate models #include "game.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 = e.attr[0]; 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, fpsent *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, (fpsent *)at, o, this, guns[GUN_BARREL].damage, GUN_BARREL); } void damaged(int damage, fpsent *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); loopv(entities::ents) { const entity &e = *entities::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, fpsent *at, const vec &vel, int gun) { m->hitpush(damage, vel, at, gun); m->damaged(damage, at, gun); } } sandboxgamemaker-2.8.2+dfsg/src/fpsgame/game.h0000644000175000017500000010514212045412564020211 0ustar bofh80bofh80#ifndef __GAME_H__ #define __GAME_H__ #include "cube.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, CON_TEAMKILL = 1<<13 }; 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 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, attr2 = model, attr3 = tag 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 DYNLIGHT, MAXENTTYPES }; enum { TRIGGER_RESET = 0, TRIGGERING, TRIGGERED, TRIGGER_RESETTING, TRIGGER_DISAPPEARED }; struct fpsentity : extentity { int triggerstate, lasttrigger; fpsentity() : triggerstate(TRIGGER_RESET), lasttrigger(0) {} }; enum { GUN_FIST = 0, GUN_SG, GUN_CG, GUN_RL, GUN_RIFLE, GUN_GL, GUN_PISTOL, GUN_FIREBALL, GUN_ICEBALL, GUN_SLIMEBALL, GUN_BITE, GUN_BARREL, NUMGUNS }; enum { A_BLUE, A_GREEN, A_YELLOW }; // armour types... take 20/40/60 % off enum { M_NONE = 0, M_SEARCH, M_HOME, M_ATTACKING, M_PAIN, M_SLEEP, M_AIMING }; // monster states enum { M_TEAM = 1<<0, M_NOITEMS = 1<<1, M_NOAMMO = 1<<2, M_INSTA = 1<<3, M_EFFICIENCY = 1<<4, M_TACTICS = 1<<5, M_CAPTURE = 1<<6, M_REGEN = 1<<7, M_CTF = 1<<8, M_PROTECT = 1<<9, M_HOLD = 1<<10, M_OVERTIME = 1<<11, M_EDIT = 1<<12, M_DEMO = 1<<13, M_LOCAL = 1<<14, M_LOBBY = 1<<15, M_DMSP = 1<<16, M_CLASSICSP = 1<<17, M_SLOWMO = 1<<18, M_COLLECT = 1<<19 }; static struct gamemodeinfo { const char *name; int flags; const char *info; } gamemodes[] = { { "DMSP", M_LOCAL | M_DMSP, NULL }, { "SP", M_LOCAL | M_CLASSICSP, "enable single player options" }, { "demo", M_DEMO | M_LOCAL, "playback recorded demos" }, { "default", M_LOBBY, "Run around freely without a care in the world" }, { "coop edit", M_EDIT, "Edit cooperatively with friends over the LAN or internet" }, { "banana relay", M_NOAMMO | M_TACTICS | M_CAPTURE | M_TEAM, "Capture bananas, robochimp is hungry" }, { "capture the banana (ctf)", M_CTF | M_TEAM, "Capture the other team's banana, and add it to your own"}, { "team drenchmatch", M_TEAM | M_OVERTIME, "Teamplay: Collect items for ammo. Drench \fs\f3the enemy team\fr to score points for \fs\f1your team\fr." }, { "instadrench", M_NOITEMS | M_INSTA, "Instadrench: You spawn with full rifle ammo and drench instantly from one shot. There are no items. Drench everyone to score points." }, { "instadrench team", M_NOITEMS | M_INSTA | M_TEAM | M_OVERTIME, "Instadrench Team: You spawn with full rifle ammo and drench instantly from one shot. There are no items. Drench \fs\f3the enemy team\fr to score points for \fs\f1your team\fr." } }; #define STARTGAMEMODE (-3) #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_insta (m_check(gamemode, M_INSTA)) #define m_tactics (m_check(gamemode, M_TACTICS)) #define m_efficiency (m_check(gamemode, M_EFFICIENCY)) #define m_capture (m_check(gamemode, M_CAPTURE)) #define m_regencapture (m_checkall(gamemode, M_CAPTURE | M_REGEN)) #define m_ctf (m_check(gamemode, M_CTF)) #define m_protect (m_checkall(gamemode, M_CTF | M_PROTECT)) #define m_hold (m_checkall(gamemode, M_CTF | M_HOLD)) #define m_collect (m_check(gamemode, M_COLLECT)) #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)) 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" }; static const char * const mastermodecolors[] = { "", "\f0", "\f2", "\f2", "\f3", "\f3" }; static const char * const mastermodeicons[] = { "server", "server", "serverlock", "serverlock", "serverpriv", "serverpriv" }; // 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_PAIN, S_DIE, 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 { N_CONNECT = 0, N_SERVINFO, N_WELCOME, N_INITCLIENT, N_POS, N_TEXT, N_SOUND, N_CDIS, N_SHOOT, N_EXPLODE, N_SUICIDE, N_DIED, N_DAMAGE, N_HITPUSH, N_SHOTFX, N_EXPLODEFX, N_TRYSPAWN, N_SPAWNSTATE, N_SPAWN, N_FORCEDEATH, N_GUNSELECT, N_TAUNT, N_MAPCHANGE, N_MAPVOTE, N_ITEMSPAWN, N_ITEMPICKUP, N_ITEMACC, N_TELEPORT, N_JUMPPAD, N_PING, N_PONG, N_CLIENTPING, N_TIMEUP, N_MAPRELOAD, N_FORCEINTERMISSION, N_SERVMSG, N_ITEMLIST, N_RESUME, N_EDITMODE, N_EDITENT, N_EDITF, N_EDITT, N_EDITM, N_FLIP, N_COPY, N_PASTE, N_ROTATE, N_REPLACE, N_DELCUBE, N_REMIP, N_NEWMAP, N_GETMAP, N_SENDMAP, N_SENDCFG, N_UPLOADMAP, N_UPLOADCFG, N_SENDTEXTURE, N_TEXTUREREQUEST, N_CLIPBOARD, N_EDITVAR, N_MASTERMODE, N_KICK, N_CLEARBANS, N_CURRENTMASTER, N_SPECTATOR, N_SETMASTER, N_SETTEAM, N_BASES, N_BASEINFO, N_BASESCORE, N_REPAMMO, N_BASEREGEN, N_ANNOUNCE, N_LISTDEMOS, N_SENDDEMOLIST, N_GETDEMO, N_SENDDEMO, N_DEMOPLAYBACK, N_RECORDDEMO, N_STOPDEMO, N_CLEARDEMOS, N_TAKEFLAG, N_RETURNFLAG, N_RESETFLAG, N_INVISFLAG, N_TRYDROPFLAG, N_DROPFLAG, N_SCOREFLAG, N_INITFLAGS, N_CLIENT, N_AUTHTRY, N_AUTHCHAL, N_AUTHANS, N_REQAUTH, N_PAUSEGAME, N_ADDBOT, N_DELBOT, N_INITAI, N_FROMAI, N_BOTLIMIT, N_BOTBALANCE, N_MAPCRC, N_CHECKMAPS, N_SWITCHNAME, N_SWITCHMODEL, N_SWITCHTEAM, N_INITTOKENS, N_TAKETOKEN, N_EXPIRETOKENS, N_DROPTOKENS, N_DEPOSITTOKENS, N_SERVCMD, N_ATTACH, N_DETACH, NUMSV }; static const int msgsizes[] = // size inclusive message token, 0 for variable or not-checked sizes { N_CONNECT, 0, N_SERVINFO, 0, N_WELCOME, 2, N_INITCLIENT, 0, N_POS, 0, N_TEXT, 0, N_SOUND, 2, N_CDIS, 2, N_SHOOT, 0, N_EXPLODE, 0, N_SUICIDE, 1, N_DIED, 4, N_DAMAGE, 6, N_HITPUSH, 7, N_SHOTFX, 10, N_EXPLODEFX, 4, N_TRYSPAWN, 1, N_SPAWNSTATE, 14, N_SPAWN, 3, N_FORCEDEATH, 2, N_GUNSELECT, 2, N_TAUNT, 1, N_MAPCHANGE, 0, N_MAPVOTE, 0, N_ITEMSPAWN, 2, N_ITEMPICKUP, 2, N_ITEMACC, 3, N_PING, 2, N_PONG, 2, N_CLIENTPING, 2, N_TIMEUP, 2, N_MAPRELOAD, 1, N_FORCEINTERMISSION, 1, N_SERVMSG, 0, N_ITEMLIST, 0, N_RESUME, 0, N_EDITMODE, 2, N_EDITENT, 0, N_EDITF, 16, N_EDITT, 16, N_EDITM, 16, N_FLIP, 14, N_COPY, 14, N_PASTE, 14, N_ROTATE, 15, N_REPLACE, 17, N_DELCUBE, 14, N_REMIP, 1, N_NEWMAP, 2, N_GETMAP, 1, N_SENDMAP, 0, N_SENDCFG, 0, N_UPLOADMAP, 0, N_UPLOADCFG, 0, N_SENDTEXTURE, 0, N_TEXTUREREQUEST, 0, N_EDITVAR, 0, N_MASTERMODE, 2, N_KICK, 2, N_CLEARBANS, 1, N_CURRENTMASTER, 4, N_SPECTATOR, 3, N_SETMASTER, 0, N_SETTEAM, 0, N_BASES, 0, N_BASEINFO, 0, N_BASESCORE, 0, N_REPAMMO, 1, N_BASEREGEN, 6, N_ANNOUNCE, 2, N_LISTDEMOS, 1, N_SENDDEMOLIST, 0, N_GETDEMO, 2, N_SENDDEMO, 0, N_DEMOPLAYBACK, 3, N_RECORDDEMO, 2, N_STOPDEMO, 1, N_CLEARDEMOS, 2, N_TAKEFLAG, 3, N_RETURNFLAG, 4, N_RESETFLAG, 6, N_INVISFLAG, 3, N_TRYDROPFLAG, 1, N_DROPFLAG, 7, N_SCOREFLAG, 10, N_INITFLAGS, 0, N_CLIENT, 0, N_AUTHTRY, 0, N_AUTHCHAL, 0, N_AUTHANS, 0, N_REQAUTH, 0, N_PAUSEGAME, 2, N_ADDBOT, 2, N_DELBOT, 1, N_INITAI, 0, N_FROMAI, 2, N_BOTLIMIT, 2, N_BOTBALANCE, 2, N_MAPCRC, 0, N_CHECKMAPS, 1, N_SWITCHNAME, 0, N_SWITCHMODEL, 2, N_SWITCHTEAM, 0, N_INITTOKENS, 0, N_TAKETOKEN, 2, N_EXPIRETOKENS, 0, N_DROPTOKENS, 0, N_DEPOSITTOKENS, 2, N_SERVCMD, 0, N_ATTACH, 0, N_DETACH, 0, -1 }; #define SANDBOX_LANINFO_PORT 28784 #define SANDBOX_SERVER_PORT 28785 #define SANDBOX_SERVINFO_PORT 28786 #define SANDBOX_MASTER_PORT 28787 #define PROTOCOL_VERSION 9 // bump when protocol changes #define DEMO_VERSION 1 // bump when demo format changes #define DEMO_MAGIC "SAUERBRATEN_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; // } //}; #define MAXNAMELEN 15 #define MAXTEAMLEN 4 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_NEUTRAL_FLAG, HICON_TOKEN, HICON_X = 20, HICON_Y = 1650, HICON_TEXTY = 1644, HICON_STEP = 490, HICON_SIZE = 120, HICON_SPACE = 40 }; static struct itemstat { int add, max, sound; const char *name; int icon, info; } itemstats[] = { {10, 30, S_ITEMAMMO, "SG", HICON_SG, GUN_SG}, {40, 100, S_ITEMAMMO, "CG", HICON_CG, GUN_CG}, {5, 15, S_ITEMAMMO, "RL", HICON_RL, GUN_RL}, {5, 15, S_ITEMAMMO, "RI", HICON_RIFLE, GUN_RIFLE}, {4, 8, S_ITEMAMMO, "GL", HICON_GL, GUN_GL}, {30, 120, S_ITEMAMMO, "PI", HICON_PISTOL, GUN_PISTOL}, {25, 100, S_ITEMHEALTH, "H", HICON_HEALTH}, {10, 1000, S_ITEMHEALTH, "MH", HICON_HEALTH}, {100, 100, S_ITEMARMOUR, "GA", HICON_GREEN_ARMOUR, A_GREEN}, {200, 200, S_ITEMARMOUR, "YA", HICON_YELLOW_ARMOUR, A_YELLOW}, {20000, 30000, S_ITEMPUP, "Q", HICON_QUAD}, }; /* original values cal edit { {10, 30, S_ITEMAMMO, "SG", HICON_SG, GUN_SG}, {20, 60, S_ITEMAMMO, "CG", HICON_CG, GUN_CG}, {5, 15, S_ITEMAMMO, "RL", HICON_RL, GUN_RL}, {5, 15, S_ITEMAMMO, "RI", HICON_RIFLE, GUN_RIFLE}, {10, 30, S_ITEMAMMO, "GL", HICON_GL, GUN_GL}, {30, 120, S_ITEMAMMO, "PI", HICON_PISTOL, GUN_PISTOL}, {25, 100, S_ITEMHEALTH, "H", HICON_HEALTH}, {10, 1000, S_ITEMHEALTH, "MH", HICON_HEALTH}, {100, 100, S_ITEMARMOUR, "GA", HICON_GREEN_ARMOUR, A_GREEN}, {200, 200, S_ITEMARMOUR, "YA", HICON_YELLOW_ARMOUR, A_YELLOW}, {20000, 30000, S_ITEMPUP, "Q", HICON_QUAD}, }; */ #define SGRAYS 20 #define RL_DAMRAD 40 #define RL_SELFDAMDIV 2 #define RL_DISTSCALE 1.5f static const struct guninfo { short sound, attackdelay, damage, spread, projspeed, part, kickamount, range; const char *name, *file; } guns[NUMGUNS] = { { S_PUNCH1, 250, 50, 0, 0, 0, 0, 14, "fist", "fist" }, { S_SG, 1400, 15, 400, 0, 0, 20, 1024, "shotgun", "shotg" }, // *SGRAYS { S_CG, 100, 20, 100, 0, 0, 7, 1024, "chaingun", "chaing"}, { S_RLFIRE, 1800, 120, 0, 180, 0, 10, 1024, "rocketlauncher", "rocket"}, { S_RIFLE, 1500, 75, 0, 0, 0, 30, 2048, "rifle", "rifle" }, { S_FLAUNCH, 2000, 175, 0, 300, 0, 10, 25, "grenadelauncher", "gl" }, { S_PISTOL, 500, 20, 50, 0, 0, 7, 1024, "pistol", "pistol" }, { S_FLAUNCH, 200, 20, 0, 50, PART_FIREBALL1, 1, 1024, "fireball", NULL }, { S_ICEBALL, 200, 40, 0, 30, PART_FIREBALL2, 1, 1024, "iceball", NULL }, { S_SLIMEBALL, 200, 30, 0, 160, PART_FIREBALL3, 1, 1024, "slimeball", NULL }, { S_PIGR1, 250, 50, 0, 0, 0, 1, 12, "bite", NULL }, { -1, 0, 120, 0, 0, 0, 0, 0, "barrel", NULL } }; /* Original weapon values cal edit { { S_PUNCH1, 250, 50, 0, 0, 0, 0, 14, "fist", "fist" }, { S_SG, 1400, 10, 400, 0, 0, 20, 1024, "shotgun", "shotg" }, // *SGRAYS { S_CG, 100, 30, 100, 0, 0, 7, 1024, "chaingun", "chaing"}, { S_RLFIRE, 800, 120, 0, 80, 0, 10, 1024, "rocketlauncher", "rocket"}, { S_RIFLE, 1500, 100, 0, 0, 0, 30, 2048, "rifle", "rifle" }, { S_FLAUNCH, 500, 75, 0, 270, 0, 10, 1024, "grenadelauncher", "gl" }, { S_PISTOL, 500, 35, 50, 0, 0, 7, 1024, "pistol", "pistol" }, { S_FLAUNCH, 200, 20, 0, 50, PART_FIREBALL1, 1, 1024, "fireball", NULL }, { S_ICEBALL, 200, 40, 0, 30, PART_FIREBALL2, 1, 1024, "iceball", NULL }, { S_SLIMEBALL, 200, 30, 0, 160, PART_FIREBALL3, 1, 1024, "slimeball", NULL }, { S_PIGR1, 250, 50, 0, 0, 0, 1, 12, "bite", NULL }, { -1, 0, 120, 0, 0, 0, 0, 0, "barrel", NULL } }; */ #include "ai.h" // inherited by fpsent and server clients struct fpsstate { int health, maxhealth; int armour, armourtype; int quadmillis; int gunselect, gunwait; int ammo[NUMGUNS]; int aitype, skill; fpsstate() : maxhealth(100), aitype(AI_NONE), skill(0) {} void baseammo(int gun, int k = 2, int scale = 1) { ammo[gun] = (itemstats[gun-GUN_SG].add*k)/scale; } void addammo(int gun, int k = 1, int scale = 1) { itemstat &is = itemstats[gun-GUN_SG]; ammo[gun] = min(ammo[gun] + (is.add*k)/scale, is.max); } bool hasmaxammo(int type) { const itemstat &is = itemstats[type-I_SHELLS]; return ammo[type-I_SHELLS+GUN_SG]>=is.max; } bool canpickup(int type) { if(typeI_QUAD) return false; itemstat &is = itemstats[type-I_SHELLS]; switch(type) { case I_BOOST: return maxhealth=100) return false; case I_YELLOWARMOUR: return !armourtype || armourI_QUAD) return; itemstat &is = itemstats[type-I_SHELLS]; switch(type) { case I_BOOST: maxhealth = min(maxhealth+is.add, is.max); case I_HEALTH: // boost also adds to health health = min(health+is.add, maxhealth); break; case I_GREENARMOUR: case I_YELLOWARMOUR: armour = min(armour+is.add, is.max); armourtype = is.info; break; case I_QUAD: quadmillis = min(quadmillis+is.add, is.max); break; default: ammo[is.info] = min(ammo[is.info]+is.add, is.max); break; } } void respawn() { health = maxhealth; armour = 0; armourtype = A_BLUE; quadmillis = 0; gunselect = GUN_PISTOL; gunwait = 0; loopi(NUMGUNS) ammo[i] = 0; ammo[GUN_FIST] = 1; } void spawnstate(int gamemode) { if(m_demo) { gunselect = GUN_FIST; } else if(m_insta) { armour = 0; health = 1; gunselect = GUN_RIFLE; ammo[GUN_RIFLE] = 100; } else if(m_regencapture) { armourtype = A_GREEN; armour = 0; gunselect = GUN_PISTOL; ammo[GUN_PISTOL] = 40; ammo[GUN_GL] = 1; } else if(m_tactics) { armourtype = A_GREEN; armour = 100; ammo[GUN_PISTOL] = 40; int spawngun1 = rnd(5)+1, spawngun2; gunselect = spawngun1; baseammo(spawngun1, m_noitems ? 2 : 1); do spawngun2 = rnd(5)+1; while(spawngun1==spawngun2); baseammo(spawngun2, m_noitems ? 2 : 1); if(m_noitems) ammo[GUN_GL] += 1; } else if(m_efficiency) { armourtype = A_GREEN; armour = 100; loopi(5) baseammo(i+1); gunselect = GUN_CG; ammo[GUN_CG] /= 2; } else if(m_ctf || m_collect) { armourtype = A_BLUE; armour = 50; ammo[GUN_PISTOL] = 40; ammo[GUN_GL] = 1; } else { ammo[GUN_PISTOL] = m_sp ? 80 : 40; ammo[GUN_GL] = 1; } } // just subtract damage here, can set death, etc. later in code calling this int dodamage(int damage) { int ad = damage*(armourtype+1)*25/100; // let armour absorb when possible if(ad>armour) ad = armour; armour -= ad; damage -= ad; health -= damage; return damage; } int hasammo(int gun, int exclude = -1) { return gun >= 0 && gun <= NUMGUNS && gun != exclude && ammo[gun] > 0; } }; /* * offtools: attachments (clothes ...) * documentation: * 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_PARTS }; static const struct attachinfo { const char* part; const char* tag; } body[ATTACH_PARTS] = { { "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" } }; /* * 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: * attachlist - manages the player / entity attachments */ struct attachlist { struct attachment { int part; int animrule; int ao; string model; attachment() : part(-1), animrule(ATTACH_ANIM_NONE), ao(-1) { model[0] = 0; } }; vector list; bool hasattachment(int part) { loopv(list) { if(list[i]->part == part) return true; } return false; } int numattachments() { return list.length(); } const char* gettag(int i) { if(i < ATTACH_PARTS || i >= 0) return body[i].tag; else return NULL; } void add(int part, char* model, int animrule) { if (part < 0 || part > ATTACH_PARTS) return; if (hasattachment(part)) remove(part); attachment* a = list.add(new attachment); if(animrule > ATTACH_ANIM_NONE || animrule <= ATTACH_ANIM_NUMRULES) a->animrule = animrule; copystring(a->model, model); a->part = part; } void remove(int part) { loopv(list) { if(list[i]->part == part) { list.remove(i); return; } } } }; struct fpsent : dynent, fpsstate { int weight; // affects the effectiveness of hitpush int clientnum, privilege, lastupdate, plag, ping; int lifesequence; // sequence id for each respawn, used in damage test int respawned, suicided; int lastpain; int lastaction, lastattackgun; bool attacking; int attacksound, attackchan, idlesound, idlechan; int lasttaunt; int lastpickup, lastpickupmillis, lastbase, lastrepammo, flagpickup, tokens; vec lastcollect; int frags, flags, deaths, totaldamage, totalshots; editinfo *edit; float deltayaw, deltapitch, deltaroll, newyaw, newpitch, newroll; int smoothmillis; string name, team, info; int playermodel; ai::aiinfo *ai; int ownernum, lastnode; attachlist attached; vec muzzle; fpsent() : weight(100), clientnum(-1), privilege(PRIV_NONE), lastupdate(0), plag(0), ping(0), lifesequence(0), respawned(-1), suicided(-1), lastpain(0), attacksound(-1), attackchan(-1), idlesound(-1), idlechan(-1), frags(0), flags(0), deaths(0), totaldamage(0), totalshots(0), edit(NULL), smoothmillis(-1), playermodel(-1), ai(NULL), ownernum(-1), muzzle(-1, -1, -1) { name[0] = team[0] = info[0] = 0; respawn(); } ~fpsent() { freeeditinfo(edit); if(attackchan >= 0) stopsound(attacksound, attackchan); if(idlechan >= 0) stopsound(idlesound, idlechan); if(ai) delete ai; } void hitpush(int damage, const vec &dir, fpsent *actor, int gun) { vec push(dir); push.mul(80*damage/weight); if(gun==GUN_RL || gun==GUN_GL) push.mul(actor==this ? 5 : (type==ENT_AI ? 3 : 2)); vel.add(push); } void stopattacksound() { if(attackchan >= 0) stopsound(attacksound, attackchan, 250); attacksound = attackchan = -1; } void stopidlesound() { if(idlechan >= 0) stopsound(idlesound, idlechan, 100); idlesound = idlechan = -1; } void respawn() { dynent::reset(); fpsstate::respawn(); respawned = suicided = -1; lastaction = 0; lastattackgun = gunselect; attacking = false; lasttaunt = 0; lastpickup = -1; lastpickupmillis = 0; lastbase = lastrepammo = -1; flagpickup = 0; tokens = 0; lastcollect = vec(-1e10f, -1e10f, -1e10f); stopattacksound(); lastnode = -1; } }; struct teamscore { const char *team; int score; teamscore() {} teamscore(const char *s, int n) : team(s), score(n) {} static bool compare(const teamscore &x, const teamscore &y) { if(x.score > y.score) return true; if(x.score < y.score) return false; return strcmp(x.team, y.team) < 0; } }; enum { ANIM_HOLD1 = ANIM_GAMESPECIFIC, 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_TAUNT, ANIM_WIN, ANIM_LOSE, ANIM_GUN_IDLE, ANIM_GUN_SHOOT, ANIM_VWEP_IDLE, ANIM_VWEP_SHOOT, ANIM_SHIELD, ANIM_POWERUP, NUMANIMS }; static const char * const animnames[] = { ANIMNAMES, "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", "taunt", "win", "lose", "gun idle", "gun shoot", "vwep idle", "vwep shoot", "shield", "powerup", }; namespace entities { extern vector ents; extern bool dynlightsactive[32767]; extern void adddynlights(); extern const char *entmdlname(int type); extern const char *itemname(int i); extern int itemicon(int i); extern void preloadentities(); extern void renderentities(); extern void resettriggers(); extern void checktriggers(); extern void checkitems(fpsent *d); extern void checkquad(int time, fpsent *d); extern void resetspawns(); extern void spawnitems(bool force = false); extern void putitems(packetbuf &p); extern void setspawn(int i, bool on); extern void teleport(int n, fpsent *d); extern void pickupeffects(int n, fpsent *d); extern void teleporteffects(fpsent *d, int tp, int td, bool local = true); extern void jumppadeffects(fpsent *d, int jp, bool local = true); extern void repammo(fpsent *d, int type, bool local = true); } namespace game { struct clientmode { virtual ~clientmode() {} virtual void preload() {} virtual int clipconsole(int w, int h) { return 0; } virtual void drawhud(fpsent *d, int w, int h) {} virtual void rendergame() {} virtual void respawned(fpsent *d) {} virtual void setup() {} virtual void checkitems(fpsent *d) {} virtual int respawnwait(fpsent *d) { return 0; } virtual void pickspawn(fpsent *d) { findplayerspawn(d); } virtual void senditems(packetbuf &p) {} virtual const char *prefixnextmap() { return ""; } virtual void removeplayer(fpsent *d) {} virtual void gameover() {} virtual bool hidefrags() { return false; } virtual int getteamscore(const char *team) { return 0; } virtual void getteamscores(vector &scores) {} virtual void aifind(fpsent *d, ai::aistate &b, vector &interests) {} virtual bool aicheck(fpsent *d, ai::aistate &b) { return false; } virtual bool aidefend(fpsent *d, ai::aistate &b) { return false; } virtual bool aipursue(fpsent *d, ai::aistate &b) { return false; } }; extern clientmode *cmode; extern void setclientmode(); // fps extern int gamemode, nextmode; extern string clientmap; extern bool intermission; extern int maptime, maprealtime, maplimit; extern fpsent *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 fpsent *getclient(int cn); extern fpsent *newclient(int cn); extern const char *colorname(fpsent *d, const char *name = NULL, const char *prefix = ""); extern fpsent *pointatplayer(); extern fpsent *hudplayer(); extern fpsent *followingplayer(); extern void stopfollowing(); extern void clientdisconnected(int cn, bool notify = true); extern void clearclients(bool notify = true); extern void startgame(); extern void spawnplayer(fpsent *); extern void deathstate(fpsent *d, bool restore = false); extern void damaged(int damage, fpsent *d, fpsent *actor, bool local = true); extern void killed(fpsent *d, fpsent *actor); extern void timeupdate(int timeremain); extern void msgsound(int n, physent *d = NULL); struct monstertype // see docs for how these values modify behaviour { short gun, speed, health, freq, lag, rate, pain, loyalty, bscale, weight; short painsound, diesound; const char *name, *mdlname, *vwepname; }; extern void drawicon(int icon, float x, float y, float sz = 120); const char *mastermodecolor(int n, const char *unknown); const char *mastermodeicon(int n, const char *unknown); // client extern bool connected, remote, demoplayback; extern string servinfo; extern int parseplayer(const char *arg); extern void ignore(int cn); extern void unignore(int cn); extern bool isignored(int cn); extern void addmsg(int type, const char *fmt = NULL, ...); extern void switchname(const char *name); extern void switchteam(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(bool force = false); extern void sendposition(fpsent *d, bool reliable = false); extern const char* attachtag(int i); extern int attachnumbypart(char* part); // monster struct monster; extern vector monsters; extern const int NUMMONSTERTYPES; extern const monstertype monstertypes[]; extern void clearmonsters(); extern void preloadmonsters(); extern void stackmonster(monster *d, physent *o); extern void updatemonsters(int curtime); extern void rendermonsters(); extern void suicidemonster(monster *m); extern void hitmonster(int damage, monster *m, fpsent *at, const vec &vel, int gun); extern void monsterkilled(); extern void endsp(bool allkilled); extern void spsummary(int accuracy); // 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, fpsent *at, const vec &vel, int gun); // weapon extern int getweapon(const char *name); extern void shoot(fpsent *d, const vec &targ); extern void shoteffects(int gun, const vec &from, const vec &to, fpsent *d, bool local, int id, int prevaction); extern void explode(bool local, fpsent *owner, const vec &v, dynent *safe, int dam, int gun); extern void explodeeffects(int gun, fpsent *d, bool local, int id = 0); extern void damageeffect(int damage, fpsent *d, bool thirdperson = true); extern void gibeffect(int damage, const vec &vel, fpsent *d); extern float intersectdist; extern bool intersect(dynent *d, const vec &from, const vec &to, float &dist = intersectdist); extern dynent *intersectclosest(const vec &from, const vec &to, fpsent *at, float &dist = intersectdist); extern void clearbouncers(); extern void updatebouncers(int curtime); extern void removebouncers(fpsent *owner); extern void renderbouncers(); extern void clearprojectiles(); extern void updateprojectiles(int curtime); extern void removeprojectiles(fpsent *owner); extern void renderprojectiles(); extern void preloadbouncers(); extern void removeweapons(fpsent *owner); extern void updateweapons(int curtime); extern void gunselect(int gun, fpsent *d); extern void weaponswitch(fpsent *d); extern void avoidweapons(ai::avoidset &obstacles, float radius); // scoreboard extern void showscores(bool on); extern void getbestplayers(vector &best); extern void getbestteams(vector &best); // render struct playermodelinfo { const char *ffa, *blueteam, *redteam, *hudguns, *vwep, *quad, *armour[3], *ffaicon, *blueicon, *redicon; bool ragdoll; }; extern int playermodel, teamskins, testteam; extern void saveragdoll(fpsent *d); extern void clearragdolls(); extern void moveragdolls(); extern void changedplayermodel(); extern const playermodelinfo &getplayermodelinfo(fpsent *d); extern int chooserandomplayermodel(int seed); extern void swayhudgun(int curtime); extern vec hudgunorigin(int gun, const vec &from, const vec &to, fpsent *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); extern bool delayspawn(int type); } #endif sandboxgamemaker-2.8.2+dfsg/src/fpsgame/capture.h0000644000175000017500000011232412047626771020754 0ustar bofh80bofh80// capture.h: client and server state for capture gamemode #ifndef PARSEMESSAGES #ifdef SERVMODE struct captureservmode : servmode #else VARP(capturetether, 0, 1, 1); VARP(autorepammo, 0, 1, 1); VARP(basenumbers, 0, 0, 1); struct captureclientmode : clientmode #endif { static const int CAPTURERADIUS = 64; static const int CAPTUREHEIGHT = 24; static const int OCCUPYBONUS = 1; static const int OCCUPYPOINTS = 1; static const int OCCUPYENEMYLIMIT = 28; static const int OCCUPYNEUTRALLIMIT = 14; static const int SCORESECS = 10; static const int AMMOSECS = 15; static const int REGENSECS = 1; static const int REGENHEALTH = 10; static const int REGENARMOUR = 10; static const int REGENAMMO = 20; static const int MAXAMMO = 5; static const int REPAMMODIST = 32; static const int RESPAWNSECS = 5; static const int MAXBASES = 100; struct baseinfo { vec o; string owner, enemy; #ifndef SERVMODE vec ammopos; string name, info; entitylight light; #endif int ammogroup, ammotype, ammo, owners, enemies, converted, capturetime; baseinfo() { reset(); } void noenemy() { enemy[0] = '\0'; enemies = 0; converted = 0; } void reset() { noenemy(); owner[0] = '\0'; capturetime = -1; ammogroup = 0; ammotype = 0; ammo = 0; owners = 0; } bool enter(const char *team) { if(!strcmp(owner, team)) { owners++; return false; } if(!enemies) { if(strcmp(enemy, team)) { converted = 0; copystring(enemy, team); } enemies++; return true; } else if(strcmp(enemy, team)) return false; else enemies++; return false; } bool steal(const char *team) { return !enemies && strcmp(owner, team); } bool leave(const char *team) { if(!strcmp(owner, team) && owners > 0) { owners--; return false; } if(strcmp(enemy, team) || enemies <= 0) return false; enemies--; return !enemies; } int occupy(const char *team, int units) { if(strcmp(enemy, team)) return -1; converted += units; if(units<0) { if(converted<=0) noenemy(); return -1; } else if(converted<(owner[0] ? int(OCCUPYENEMYLIMIT) : int(OCCUPYNEUTRALLIMIT))) return -1; if(owner[0]) { owner[0] = '\0'; converted = 0; copystring(enemy, team); return 0; } else { copystring(owner, team); ammo = 0; capturetime = 0; owners = enemies; noenemy(); return 1; } } bool addammo(int i) { if(ammo>=MAXAMMO) return false; ammo = min(ammo+i, int(MAXAMMO)); return true; } bool takeammo(const char *team) { if(strcmp(owner, team) || ammo<=0) return false; ammo--; return true; } }; vector bases; struct score { string team; int total; }; vector scores; int captures; void resetbases() { bases.shrink(0); scores.shrink(0); captures = 0; } bool hidefrags() { return true; } int getteamscore(const char *team) { loopv(scores) { score &cs = scores[i]; if(!strcmp(cs.team, team)) return cs.total; } return 0; } void getteamscores(vector &teamscores) { loopv(scores) teamscores.add(teamscore(scores[i].team, scores[i].total)); } score &findscore(const char *team) { loopv(scores) { score &cs = scores[i]; if(!strcmp(cs.team, team)) return cs; } score &cs = scores.add(); copystring(cs.team, team); cs.total = 0; return cs; } void addbase(int ammotype, const vec &o) { if(bases.length() >= MAXBASES) return; baseinfo &b = bases.add(); b.ammogroup = min(ammotype, 0); b.ammotype = ammotype > 0 ? ammotype : rnd(5)+1; b.o = o; if(b.ammogroup) { loopi(bases.length()-1) if(b.ammogroup == bases[i].ammogroup) { b.ammotype = bases[i].ammotype; return; } int uses[5] = { 0, 0, 0, 0, 0 }; loopi(bases.length()-1) if(bases[i].ammogroup) { loopj(i) if(bases[j].ammogroup == bases[i].ammogroup) goto nextbase; uses[bases[i].ammotype-1]++; nextbase:; } int mintype = 0; loopi(5) if(uses[i] < uses[mintype]) mintype = i; int numavail = 0, avail[5]; loopi(5) if(uses[i] == uses[mintype]) avail[numavail++] = i+1; b.ammotype = avail[rnd(numavail)]; } } void initbase(int i, int ammotype, const char *owner, const char *enemy, int converted, int ammo) { if(!bases.inrange(i)) return; baseinfo &b = bases[i]; b.ammotype = ammotype; copystring(b.owner, owner); copystring(b.enemy, enemy); b.converted = converted; b.ammo = ammo; } bool hasbases(const char *team) { loopv(bases) { baseinfo &b = bases[i]; if(b.owner[0] && !strcmp(b.owner, team)) return true; } return false; } float disttoenemy(baseinfo &b) { float dist = 1e10f; loopv(bases) { baseinfo &e = bases[i]; if(e.owner[0] && strcmp(b.owner, e.owner)) dist = min(dist, b.o.dist(e.o)); } return dist; } bool insidebase(const baseinfo &b, const vec &o) { float dx = (b.o.x-o.x), dy = (b.o.y-o.y), dz = (b.o.z-o.z); return dx*dx + dy*dy <= CAPTURERADIUS*CAPTURERADIUS && fabs(dz) <= CAPTUREHEIGHT; } #ifndef SERVMODE static const int AMMOHEIGHT = 5; captureclientmode() : captures(0) { } void respawned(fpsent *d) { } void replenishammo() { if(!m_capture || m_regencapture) return; loopv(bases) { baseinfo &b = bases[i]; if(b.ammotype>0 && b.ammotype<=I_CARTRIDGES-I_SHELLS+1 && insidebase(b, player1->feetpos()) && player1->hasmaxammo(b.ammotype-1+I_SHELLS)) return; } addmsg(N_REPAMMO, "rc", player1); } void receiveammo(fpsent *d, int type) { type += I_SHELLS-1; if(typeI_CARTRIDGES) return; entities::repammo(d, type, d==player1); int icon = itemstats[type-I_SHELLS].icon; if(icon >= 0) particle_icon(d->abovehead(), icon%4, icon/4, PART_HUD_ICON_GREY, 2000, 0xFFFFFF, 2.0f, -8); } void checkitems(fpsent *d) { if(m_regencapture || !autorepammo || d!=player1 || d->state!=CS_ALIVE) return; vec o = d->feetpos(); loopv(bases) { baseinfo &b = bases[i]; if(b.ammotype>0 && b.ammotype<=I_CARTRIDGES-I_SHELLS+1 && insidebase(b, d->feetpos()) && !strcmp(b.owner, d->team) && b.o.dist(o) < 12) { if(d->lastrepammo!=i) { if(b.ammo > 0 && !player1->hasmaxammo(b.ammotype-1+I_SHELLS)) addmsg(N_REPAMMO, "rc", d); d->lastrepammo = i; } return; } } d->lastrepammo = -1; } void rendertether(fpsent *d) { int oldbase = d->lastbase; d->lastbase = -1; vec pos(d->o.x, d->o.y, d->o.z + (d->aboveeye - d->eyeheight)/2); if(d->state==CS_ALIVE) { loopv(bases) { baseinfo &b = bases[i]; if(!insidebase(b, d->feetpos()) || (strcmp(b.owner, d->team) && strcmp(b.enemy, d->team))) continue; if(d->lastbase < 0 && (lookupmaterial(d->feetpos())&MATF_CLIP) == MAT_GAMECLIP) break; particle_flare(pos, vec(b.ammopos.x, b.ammopos.y, b.ammopos.z - AMMOHEIGHT - 4.4f), 0, PART_LIGHTNING, strcmp(d->team, player1->team) ? 0xFF2222 : 0x2222FF, 1.0f); if(oldbase < 0) { particle_fireball(pos, 4.8f, PART_EXPLOSION, 250, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 4.8f); particle_splash(PART_SPARK, 50, 250, pos, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 0.24f); } d->lastbase = i; } } if(d->lastbase < 0 && oldbase >= 0) { particle_fireball(pos, 4.8f, PART_EXPLOSION, 250, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 4.8f); particle_splash(PART_SPARK, 50, 250, pos, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 0.24f); } } void preload() { static const char *basemodels[3] = { "banana", "banana/red", "banana/blue" }; loopi(3) preloadmodel(basemodels[i]); } void rendergame() { if(capturetether && canaddparticles()) { loopv(players) { fpsent *d = players[i]; if(d) rendertether(d); } rendertether(player1); } loopv(bases) { baseinfo &b = bases[i]; const char *flagname = b.owner[0] ? (strcmp(b.owner, player1->team) ? "banana/red" : "banana/blue") : "banana"; rendermodel(&b.light, flagname, ANIM_MAPMODEL|ANIM_LOOP, b.o, 0, 0, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED); float fradius = 1.0f, fheight = 0.5f; regular_particle_flame(PART_FLAME, vec(b.ammopos.x, b.ammopos.y, b.ammopos.z - 4.5f), fradius, fheight, b.owner[0] ? (strcmp(b.owner, player1->team) ? 0x802020 : 0x2020FF) : 0x208020, 3, 2.0f); //regular_particle_flame(PART_SMOKE, vec(b.ammopos.x, b.ammopos.y, b.ammopos.z - 4.5f + 4.0f*min(fradius, fheight)), fradius, fheight, 0x303020, 1, 4.0f, 100.0f, 2000.0f, -20); // particle_fireball(b.ammopos, 4.8f, PART_EXPLOSION, 0, b.owner[0] ? (strcmp(b.owner, player1->team) ? 0x802020 : 0x2020FF) : 0x208020, 4.8f); if(b.ammotype>0 && b.ammotype<=I_CARTRIDGES-I_SHELLS+1) { const char *ammoname = entities::entmdlname(I_SHELLS+b.ammotype-1); if(m_regencapture) { vec height(0, 0, 0); abovemodel(height, ammoname); vec ammopos(b.ammopos); ammopos.z -= height.z/2 + sinf(lastmillis/100.0f)/20; rendermodel(&b.light, ammoname, ANIM_MAPMODEL|ANIM_LOOP, ammopos, lastmillis/10.0f, 0, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED); } else loopj(b.ammo) { float angle = 2*M_PI*(lastmillis/4000.0f + j/float(MAXAMMO)); vec ammopos(b.o); ammopos.x += 10*cosf(angle); ammopos.y += 10*sinf(angle); ammopos.z += 4; rendermodel(&b.light, entities::entmdlname(I_SHELLS+b.ammotype-1), ANIM_MAPMODEL|ANIM_LOOP, ammopos, 0, 0, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED); } } int tcolor = 0x1EC850, mtype = -1, mcolor = 0xFFFFFF, mcolor2 = 0; if(b.owner[0]) { bool isowner = !strcmp(b.owner, player1->team); if(b.enemy[0]) { mtype = PART_METER_VS; mcolor = 0xFF1932; mcolor2 = 0x3219FF; if(!isowner) swap(mcolor, mcolor2); } if(!b.name[0]) formatstring(b.info)("base %d: %s", i+1, b.owner); else if(basenumbers) formatstring(b.info)("%s (%d): %s", b.name, i+1, b.owner); else formatstring(b.info)("%s: %s", b.name, b.owner); tcolor = isowner ? 0x6496FF : 0xFF4B19; } else if(b.enemy[0]) { if(!b.name[0]) formatstring(b.info)("base %d: %s", i+1, b.enemy); else if(basenumbers) formatstring(b.info)("%s (%d): %s", b.name, i+1, b.enemy); else formatstring(b.info)("%s: %s", b.name, b.enemy); if(strcmp(b.enemy, player1->team)) { tcolor = 0xFF4B19; mtype = PART_METER; mcolor = 0xFF1932; } else { tcolor = 0x6496FF; mtype = PART_METER; mcolor = 0x3219FF; } } else if(!b.name[0]) formatstring(b.info)("base %d", i+1); else if(basenumbers) formatstring(b.info)("%s (%d)", b.name, i+1); else copystring(b.info, b.name); vec above(b.ammopos); above.z += AMMOHEIGHT; if(b.info[0]) particle_text(above, b.info, PART_TEXT, 1, tcolor, 2.0f); if(mtype>=0) { above.z += 3.0f; particle_meter(above, b.converted/float((b.owner[0] ? int(OCCUPYENEMYLIMIT) : int(OCCUPYNEUTRALLIMIT))), mtype, 1, mcolor, mcolor2, 2.0f); } } } void drawblips(fpsent *d, float blipsize, int fw, int fh, int type, bool skipenemy = false) { float scale = calcradarscale(); int blips = 0; loopv(bases) { baseinfo &b = bases[i]; if(skipenemy && b.enemy[0]) continue; switch(type) { case 1: if(!b.owner[0] || strcmp(b.owner, player1->team)) continue; break; case 0: if(b.owner[0]) continue; break; case -1: if(!b.owner[0] || !strcmp(b.owner, player1->team)) continue; break; case -2: if(!b.enemy[0] || !strcmp(b.enemy, player1->team)) continue; break; } vec dir(d->o); dir.sub(b.o).div(scale); float dist = dir.magnitude2(), maxdist = 1 - 0.05f - blipsize; if(dist >= maxdist) dir.mul(maxdist/dist); dir.rotate_around_z(-camera1->yaw*RAD); if(basenumbers) { static string blip; formatstring(blip)("%d", i+1); int tw, th; text_bounds(blip, tw, th); draw_text(blip, int(0.5f*(dir.x*fw/blipsize - tw)), int(0.5f*(dir.y*fh/blipsize - th))); } else { if(!blips) glBegin(GL_QUADS); float x = 0.5f*(dir.x*fw/blipsize - fw), y = 0.5f*(dir.y*fh/blipsize - fh); glTexCoord2f(0.0f, 0.0f); glVertex2f(x, y); glTexCoord2f(1.0f, 0.0f); glVertex2f(x+fw, y); glTexCoord2f(1.0f, 1.0f); glVertex2f(x+fw, y+fh); glTexCoord2f(0.0f, 1.0f); glVertex2f(x, y+fh); } blips++; } if(blips && !basenumbers) glEnd(); } int respawnwait(fpsent *d) { if(m_regencapture) return -1; return max(0, RESPAWNSECS-(lastmillis-d->lastpain)/1000); } int clipconsole(int w, int h) { return (h*(1 + 1 + 10))/(4*10); } void drawhud(fpsent *d, int w, int h) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int s = 1800/4, x = 1800*w/h - s - s/10, y = s/10; glColor4f(1, 1, 1, minimapalpha); if(minimapalpha >= 1) glDisable(GL_BLEND); bindminimap(); drawminimap(d, x, y, s); if(minimapalpha >= 1) glEnable(GL_BLEND); glColor3f(1, 1, 1); float margin = 0.04f, roffset = s*margin, rsize = s + 2*roffset; settexture("data/fps/hud/radar.png", 3); drawradar(x - roffset, y - roffset, rsize); #if 0 settexture("data/fps/hud/compass.png", 3); glPushMatrix(); glTranslatef(x - roffset + 0.5f*rsize, y - roffset + 0.5f*rsize, 0); glRotatef(camera1->yaw + 180, 0, 0, -1); drawradar(-0.5f*rsize, -0.5f*rsize, rsize); glPopMatrix(); #endif bool showenemies = lastmillis%1000 >= 500; int fw = 1, fh = 1; if(basenumbers) { pushfont(); setfont("digit_blue"); text_bounds(" ", fw, fh); } else settexture("data/fps/hud/blip_blue.png", 3); glPushMatrix(); glTranslatef(x + 0.5f*s, y + 0.5f*s, 0); float blipsize = basenumbers ? 0.1f : 0.05f; glScalef((s*blipsize)/fw, (s*blipsize)/fh, 1.0f); drawblips(d, blipsize, fw, fh, 1, showenemies); if(basenumbers) setfont("digit_grey"); else settexture("data/fps/hud/blip_grey.png", 3); drawblips(d, blipsize, fw, fh, 0, showenemies); if(basenumbers) setfont("digit_red"); else settexture("data/fps/hud/blip_red.png", 3); drawblips(d, blipsize, fw, fh, -1, showenemies); if(showenemies) drawblips(d, blipsize, fw, fh, -2); glPopMatrix(); if(basenumbers) popfont(); if(d->state == CS_DEAD) { int wait = respawnwait(d); if(wait>=0) { glPushMatrix(); glScalef(2, 2, 1); bool flash = wait>0 && d==player1 && lastspawnattempt>=d->lastpain && lastmillis < lastspawnattempt+100; draw_textf("%s%d", (x+s/2)/2-(wait>=10 ? 28 : 16), (y+s/2)/2-32, flash ? "\f3" : "", wait); glPopMatrix(); } } } void setup() { resetbases(); loopv(entities::ents) { extentity *e = entities::ents[i]; if(e->type!=BASE) continue; baseinfo &b = bases.add(); b.o = e->o; b.ammopos = b.o; abovemodel(b.ammopos, "banana"); b.ammopos.z += AMMOHEIGHT-2; b.ammotype = e->attr[0]; defformatstring(alias)("base_%d", e->attr[1]); const char *name = getalias(alias); copystring(b.name, name); b.light = e->light; } } void senditems(packetbuf &p) { putint(p, N_BASES); putint(p, bases.length()); loopv(bases) { baseinfo &b = bases[i]; putint(p, b.ammotype); putint(p, int(b.o.x*DMF)); putint(p, int(b.o.y*DMF)); putint(p, int(b.o.z*DMF)); } } void updatebase(int i, const char *owner, const char *enemy, int converted, int ammo) { if(!bases.inrange(i)) return; baseinfo &b = bases[i]; if(owner[0]) { if(strcmp(b.owner, owner)) { if(!b.name[0]) conoutf(CON_GAMEINFO, "%s captured base %d", owner, i+1); else if(basenumbers) conoutf(CON_GAMEINFO, "%s captured %s (%d)", owner, b.name, i+1); else conoutf(CON_GAMEINFO, "%s captured %s", owner, b.name); if(!strcmp(owner, player1->team)) playsound(S_V_BASECAP); } } else if(b.owner[0]) { if(!b.name[0]) conoutf(CON_GAMEINFO, "%s lost base %d", b.owner, i+1); else if(basenumbers) conoutf(CON_GAMEINFO, "%s lost %s (%d)", b.owner, b.name, i+1); else conoutf(CON_GAMEINFO, "%s lost %s", b.owner, b.name); if(!strcmp(b.owner, player1->team)) playsound(S_V_BASELOST); } if(strcmp(b.owner, owner)) particle_splash(PART_SPARK, 200, 250, b.ammopos, owner[0] ? (strcmp(owner, player1->team) ? 0x802020 : 0x2020FF) : 0x208020, 0.24f); copystring(b.owner, owner); copystring(b.enemy, enemy); b.converted = converted; if(ammo>b.ammo) { playsound(S_ITEMSPAWN, &b.o); int icon = b.ammotype>0 && b.ammotype<=I_CARTRIDGES-I_SHELLS+1 ? itemstats[b.ammotype-1].icon : -1; if(icon >= 0) particle_icon(vec(b.ammopos.x, b.ammopos.y, b.ammopos.z + AMMOHEIGHT + 1.0f), icon%4, icon/4, PART_HUD_ICON, 2000, 0xFFFFFF, 2.0f, -8); } b.ammo = ammo; } void setscore(int base, const char *team, int total) { findscore(team).total = total; if(total>=10000) conoutf(CON_GAMEINFO, "team %s captured all bases", team); else if(bases.inrange(base)) { baseinfo &b = bases[base]; if(!strcmp(b.owner, team)) { defformatstring(msg)("%d", total); vec above(b.ammopos); above.z += AMMOHEIGHT+1.0f; particle_textcopy(above, msg, PART_TEXT, 2000, isteam(team, player1->team) ? 0x6496FF : 0xFF4B19, 4.0f, -8); } } } int closesttoenemy(const char *team, bool noattacked = false, bool farthest = false) { float bestdist = farthest ? -1e10f : 1e10f; int best = -1; int attackers = INT_MAX, attacked = -1; loopv(bases) { baseinfo &b = bases[i]; if(!b.owner[0] || strcmp(b.owner, team)) continue; if(noattacked && b.enemy[0]) continue; float dist = disttoenemy(b); if(farthest ? dist > bestdist : dist < bestdist) { best = i; bestdist = dist; } else if(b.enemy[0] && b.enemies < attackers) { attacked = i; attackers = b.enemies; } } if(best < 0) return attacked; return best; } int pickteamspawn(const char *team) { int closest = closesttoenemy(team, true, m_regencapture); if(!m_regencapture && closest < 0) closest = closesttoenemy(team, false); if(closest < 0) return -1; baseinfo &b = bases[closest]; float bestdist = 1e10f, altdist = 1e10f; int best = -1, alt = -1; loopv(entities::ents) { extentity *e = entities::ents[i]; if(e->type!=PLAYERSTART || e->attr[1]) continue; float dist = e->o.dist(b.o); if(dist < bestdist) { alt = best; altdist = bestdist; best = i; bestdist = dist; } else if(dist < altdist) { alt = i; altdist = dist; } } return rnd(2) ? best : alt; } void pickspawn(fpsent *d) { findplayerspawn(d, pickteamspawn(d->team)); } const char *prefixnextmap() { return "capture_"; } bool aicheck(fpsent *d, ai::aistate &b) { return false; } void aifind(fpsent *d, ai::aistate &b, vector &interests) { vec pos = d->feetpos(); loopvj(bases) { baseinfo &f = bases[j]; static vector targets; // build a list of others who are interested in this targets.setsize(0); ai::checkothers(targets, d, ai::AI_S_DEFEND, ai::AI_T_AFFINITY, j, true); fpsent *e = NULL; int regen = !m_regencapture || d->health >= 100 ? 0 : 1; if(m_regencapture) { int gun = f.ammotype-1+I_SHELLS; if(f.ammo > 0 && f.ammotype > 0 && f.ammotype <= I_CARTRIDGES-I_SHELLS+1 && !d->hasmaxammo(gun)) regen = gun != d->ai->weappref ? 2 : 4; } loopi(numdynents()) if((e = (fpsent *)iterdynents(i)) && !e->ai && e->state == CS_ALIVE && isteam(d->team, e->team)) { // try to guess what non ai are doing vec ep = e->feetpos(); if(targets.find(e->clientnum) < 0 && ep.squaredist(f.o) <= (CAPTURERADIUS*CAPTURERADIUS)) targets.add(e->clientnum); } if((regen && f.owner[0] && !strcmp(f.owner, d->team)) || (targets.empty() && (!f.owner[0] || strcmp(f.owner, d->team) || f.enemy[0]))) { ai::interest &n = interests.add(); n.state = ai::AI_S_DEFEND; n.node = ai::closestwaypoint(f.o, ai::SIGHTMIN, false); n.target = j; n.targtype = ai::AI_T_AFFINITY; n.score = pos.squaredist(f.o)/(regen ? float(100*regen) : 1.f); } } } bool aidefend(fpsent *d, ai::aistate &b) { if(bases.inrange(b.target)) { baseinfo &f = bases[b.target]; bool regen = !m_regencapture || d->health >= 100 ? false : true; if(!regen && m_regencapture) { int gun = f.ammotype-1+I_SHELLS; if(f.ammo > 0 && f.ammotype > 0 && f.ammotype <= I_CARTRIDGES-I_SHELLS+1 && !d->hasmaxammo(gun)) regen = true; } int walk = 0; if(!regen && !f.enemy[0] && f.owner[0] && !strcmp(f.owner, d->team)) { static vector targets; // build a list of others who are interested in this targets.setsize(0); ai::checkothers(targets, d, ai::AI_S_DEFEND, ai::AI_T_AFFINITY, b.target, true); fpsent *e = NULL; loopi(numdynents()) if((e = (fpsent *)iterdynents(i)) && !e->ai && e->state == CS_ALIVE && isteam(d->team, e->team)) { // try to guess what non ai are doing vec ep = e->feetpos(); if(targets.find(e->clientnum) < 0 && (ep.squaredist(f.o) <= (CAPTURERADIUS*CAPTURERADIUS*4))) targets.add(e->clientnum); } if(!targets.empty()) { if(lastmillis-b.millis >= (201-d->skill)*33) { d->ai->trywipe = true; // re-evaluate so as not to herd return true; } else walk = 2; } else walk = 1; b.millis = lastmillis; } return ai::defend(d, b, f.o, float(CAPTURERADIUS), float(CAPTURERADIUS*(2+(walk*2))), walk); // less wander than ctf } return false; } bool aipursue(fpsent *d, ai::aistate &b) { b.type = ai::AI_S_DEFEND; return aidefend(d, b); } }; extern captureclientmode capturemode; ICOMMAND(repammo, "", (), capturemode.replenishammo()); ICOMMAND(insidebases, "", (), { vector buf; if(m_capture && player1->state == CS_ALIVE) loopv(capturemode.bases) { if(capturemode.insidebase(capturemode.bases[i], player1->feetpos())) { if(buf.length()) buf.add(' '); defformatstring(basenum)("%d", i+1); buf.put(basenum, strlen(basenum)); } } buf.add('\0'); result(buf.getbuf()); }); #else bool notgotbases; captureservmode() : captures(0), notgotbases(false) {} void reset(bool empty) { resetbases(); notgotbases = !empty; } void cleanup() { reset(false); } void setup() { reset(false); if(notgotitems || ments.empty()) return; loopv(ments) { entity &e = ments[i]; if(e.type != BASE) continue; int ammotype = e.attr[0]; addbase(ammotype>=GUN_SG && ammotype<=GUN_PISTOL ? ammotype : min(ammotype, 0), e.o); } notgotbases = false; sendbases(); loopv(clients) if(clients[i]->state.state==CS_ALIVE) entergame(clients[i]); } void newmap() { reset(true); } void stealbase(int n, const char *team) { baseinfo &b = bases[n]; loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_ALIVE && ci->team[0] && !strcmp(ci->team, team) && insidebase(b, ci->state.o)) b.enter(ci->team); } sendbaseinfo(n); } void replenishammo(clientinfo *ci) { if(m_noitems || notgotbases || ci->state.state!=CS_ALIVE || !ci->team[0]) return; loopv(bases) { baseinfo &b = bases[i]; if(b.ammotype>0 && b.ammotype<=I_CARTRIDGES-I_SHELLS+1 && insidebase(b, ci->state.o) && !ci->state.hasmaxammo(b.ammotype-1+I_SHELLS) && b.takeammo(ci->team)) { sendbaseinfo(i); sendf(-1, 1, "riii", N_REPAMMO, ci->clientnum, b.ammotype); ci->state.addammo(b.ammotype); break; } } } void movebases(const char *team, const vec &oldpos, bool oldclip, const vec &newpos, bool newclip) { if(!team[0] || gamemillis>=gamelimit) return; loopv(bases) { baseinfo &b = bases[i]; bool leave = !oldclip && insidebase(b, oldpos), enter = !newclip && insidebase(b, newpos); if(leave && !enter && b.leave(team)) sendbaseinfo(i); else if(enter && !leave && b.enter(team)) sendbaseinfo(i); else if(leave && enter && b.steal(team)) stealbase(i, team); } } void leavebases(const char *team, const vec &o) { movebases(team, o, false, vec(-1e10f, -1e10f, -1e10f), true); } void enterbases(const char *team, const vec &o) { movebases(team, vec(-1e10f, -1e10f, -1e10f), true, o, false); } void addscore(int base, const char *team, int n) { if(!n) return; score &cs = findscore(team); cs.total += n; sendf(-1, 1, "riisi", N_BASESCORE, base, team, cs.total); } void regenowners(baseinfo &b, int ticks) { loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_ALIVE && ci->team[0] && !strcmp(ci->team, b.owner) && insidebase(b, ci->state.o)) { bool notify = false; if(ci->state.health < ci->state.maxhealth) { ci->state.health = min(ci->state.health + ticks*REGENHEALTH, ci->state.maxhealth); notify = true; } if(ci->state.armour < itemstats[I_GREENARMOUR-I_SHELLS].max) { ci->state.armour = min(ci->state.armour + ticks*REGENARMOUR, itemstats[I_GREENARMOUR-I_SHELLS].max); notify = true; } if(b.ammotype>0) { int ammotype = b.ammotype-1+I_SHELLS; if(ammotype<=I_CARTRIDGES && !ci->state.hasmaxammo(ammotype)) { ci->state.addammo(b.ammotype, ticks*REGENAMMO, 100); notify = true; } } if(notify) sendf(-1, 1, "ri6", N_BASEREGEN, ci->clientnum, ci->state.health, ci->state.armour, b.ammotype, b.ammotype>0 ? ci->state.ammo[b.ammotype] : 0); } } } void update() { if(gamemillis>=gamelimit) return; endcheck(); int t = gamemillis/1000 - (gamemillis-curtime)/1000; if(t<1) return; loopv(bases) { baseinfo &b = bases[i]; if(b.enemy[0]) { if(!b.owners || !b.enemies) b.occupy(b.enemy, OCCUPYBONUS*(b.enemies ? 1 : -1) + OCCUPYPOINTS*(b.enemies ? b.enemies : -(1+b.owners))*t); sendbaseinfo(i); } else if(b.owner[0]) { b.capturetime += t; int score = b.capturetime/SCORESECS - (b.capturetime-t)/SCORESECS; if(score) addscore(i, b.owner, score); if(m_regencapture) { int regen = b.capturetime/REGENSECS - (b.capturetime-t)/REGENSECS; if(regen) regenowners(b, regen); } else { int ammo = b.capturetime/AMMOSECS - (b.capturetime-t)/AMMOSECS; if(ammo && b.addammo(ammo)) sendbaseinfo(i); } } } } void sendbaseinfo(int i) { baseinfo &b = bases[i]; sendf(-1, 1, "riissii", N_BASEINFO, i, b.owner, b.enemy, b.enemy[0] ? b.converted : 0, b.owner[0] ? b.ammo : 0); } void sendbases() { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); initclient(NULL, p, false); sendpacket(-1, 1, p.finalize()); } void initclient(clientinfo *ci, packetbuf &p, bool connecting) { if(connecting) { loopv(scores) { score &cs = scores[i]; putint(p, N_BASESCORE); putint(p, -1); sendstring(cs.team, p); putint(p, cs.total); } } putint(p, N_BASES); putint(p, bases.length()); loopv(bases) { baseinfo &b = bases[i]; putint(p, min(max(b.ammotype, 1), I_CARTRIDGES+1)); sendstring(b.owner, p); sendstring(b.enemy, p); putint(p, b.converted); putint(p, b.ammo); } } void endcheck() { const char *lastteam = NULL; loopv(bases) { baseinfo &b = bases[i]; if(b.owner[0]) { if(!lastteam) lastteam = b.owner; else if(strcmp(lastteam, b.owner)) { lastteam = NULL; break; } } else { lastteam = NULL; break; } } if(!lastteam) return; findscore(lastteam).total = 10000; sendf(-1, 1, "riisi", N_BASESCORE, -1, lastteam, 10000); startintermission(); } void entergame(clientinfo *ci) { if(notgotbases || ci->state.state!=CS_ALIVE || ci->gameclip) return; enterbases(ci->team, ci->state.o); } void spawned(clientinfo *ci) { if(notgotbases || ci->gameclip) return; enterbases(ci->team, ci->state.o); } void leavegame(clientinfo *ci, bool disconnecting = false) { if(notgotbases || ci->state.state!=CS_ALIVE || ci->gameclip) return; leavebases(ci->team, ci->state.o); } void died(clientinfo *ci, clientinfo *actor) { if(notgotbases || ci->gameclip) return; leavebases(ci->team, ci->state.o); } void moved(clientinfo *ci, const vec &oldpos, bool oldclip, const vec &newpos, bool newclip) { if(notgotbases) return; movebases(ci->team, oldpos, oldclip, newpos, newclip); } void changeteam(clientinfo *ci, const char *oldteam, const char *newteam) { if(notgotbases || ci->gameclip) return; leavebases(oldteam, ci->state.o); enterbases(newteam, ci->state.o); } void parsebases(ucharbuf &p, bool commit) { int numbases = getint(p); loopi(numbases) { int ammotype = getint(p); vec o; loopk(3) o[k] = max(getint(p)/DMF, 0.0f); if(p.overread()) break; if(commit && notgotbases) addbase(ammotype>=GUN_SG && ammotype<=GUN_PISTOL ? ammotype : min(ammotype, 0), o); } if(commit && notgotbases) { notgotbases = false; sendbases(); loopv(clients) if(clients[i]->state.state==CS_ALIVE) entergame(clients[i]); } } bool extinfoteam(const char *team, ucharbuf &p) { int numbases = 0; loopvj(bases) if(!strcmp(bases[j].owner, team)) numbases++; putint(p, numbases); loopvj(bases) if(!strcmp(bases[j].owner, team)) putint(p, j); return true; } }; #endif #elif SERVMODE case N_BASES: if(smode==&capturemode) capturemode.parsebases(p, (ci->state.state!=CS_SPECTATOR || ci->privilege || ci->local) && !strcmp(ci->clientmap, smapname)); break; case N_REPAMMO: if((ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege) && cq && smode==&capturemode) capturemode.replenishammo(cq); break; #else case N_BASEINFO: { int base = getint(p); string owner, enemy; getstring(text, p); copystring(owner, text); getstring(text, p); copystring(enemy, text); int converted = getint(p), ammo = getint(p); if(m_capture) capturemode.updatebase(base, owner, enemy, converted, ammo); break; } case N_BASEREGEN: { int rcn = getint(p), health = getint(p), armour = getint(p), ammotype = getint(p), ammo = getint(p); fpsent *regen = rcn==player1->clientnum ? player1 : getclient(rcn); if(regen && m_capture) { regen->health = health; regen->armour = armour; if(ammotype>=GUN_SG && ammotype<=GUN_PISTOL) regen->ammo[ammotype] = ammo; } break; } case N_BASES: { int numbases = getint(p); loopi(numbases) { int ammotype = getint(p); string owner, enemy; getstring(text, p); copystring(owner, text); getstring(text, p); copystring(enemy, text); int converted = getint(p), ammo = getint(p); capturemode.initbase(i, ammotype, owner, enemy, converted, ammo); } break; } case N_BASESCORE: { int base = getint(p); getstring(text, p); int total = getint(p); if(m_capture) capturemode.setscore(base, text, total); break; } case N_REPAMMO: { int rcn = getint(p), ammotype = getint(p); fpsent *r = rcn==player1->clientnum ? player1 : getclient(rcn); if(r && m_capture) capturemode.receiveammo(r, ammotype); break; } #endif sandboxgamemaker-2.8.2+dfsg/src/fpsgame/ai.cpp0000644000175000017500000014411412045412564020226 0ustar bofh80bofh80#include "game.h" extern int fog; namespace ai { using namespace game; avoidset obstacles; int updatemillis = 0, iteration = 0, itermillis = 0, forcegun = -1; vec aitarget(0, 0, 0); VAR(aidebug, 0, 0, 6); VAR(aiforcegun, -1, -1, NUMGUNS-1); ICOMMAND(addbot, "s", (char *s), addmsg(N_ADDBOT, "ri", *s ? clamp(parseint(s), 1, 101) : -1)); ICOMMAND(delbot, "", (), addmsg(N_DELBOT, "r")); ICOMMAND(botlimit, "i", (int *n), addmsg(N_BOTLIMIT, "ri", *n)); ICOMMAND(botbalance, "i", (int *n), addmsg(N_BOTBALANCE, "ri", *n)); float viewdist(int x) { return x <= 100 ? clamp((SIGHTMIN+(SIGHTMAX-SIGHTMIN))/100.f*float(x), float(SIGHTMIN), float(fog)) : float(fog); } float viewfieldx(int x) { return x <= 100 ? clamp((VIEWMIN+(VIEWMAX-VIEWMIN))/100.f*float(x), float(VIEWMIN), float(VIEWMAX)) : float(VIEWMAX); } float viewfieldy(int x) { return viewfieldx(x)*3.f/4.f; } bool canmove(fpsent *d) { return d->state != CS_DEAD && !intermission; } float weapmindist(int weap) { return guns[weap].projspeed ? RL_DAMRAD : 2; } float weapmaxdist(int weap) { return guns[weap].range + 4; } bool weaprange(fpsent *d, int weap, float dist) { float mindist = weapmindist(weap), maxdist = weapmaxdist(weap); return dist >= mindist*mindist && dist <= maxdist*maxdist; } bool targetable(fpsent *d, fpsent *e) { if(d == e || !canmove(d)) return false; return e->state == CS_ALIVE && !isteam(d->team, e->team); } bool getsight(vec &o, float yaw, float pitch, vec &q, vec &v, float mdist, float fovx, float fovy) { float dist = o.dist(q); if(dist <= mdist) { float x = fmod(fabs(asin((q.z-o.z)/dist)/RAD-pitch), 360); float y = fmod(fabs(-atan2(q.x-o.x, q.y-o.y)/RAD-yaw), 360); if(min(x, 360-x) <= fovx && min(y, 360-y) <= fovy) return raycubelos(o, q, v); } return false; } bool cansee(fpsent *d, vec &x, vec &y, vec &targ) { aistate &b = d->ai->getstate(); if(canmove(d) && b.type != AI_S_WAIT) return getsight(x, d->yaw, d->pitch, y, targ, d->ai->views[2], d->ai->views[0], d->ai->views[1]); return false; } bool canshoot(fpsent *d, fpsent *e) { if(weaprange(d, d->gunselect, e->o.squaredist(d->o)) && targetable(d, e)) return d->ammo[d->gunselect] > 0 && lastmillis - d->lastaction >= d->gunwait; return false; } bool canshoot(fpsent *d) { return !d->ai->becareful && d->ammo[d->gunselect] > 0 && lastmillis - d->lastaction >= d->gunwait; } bool hastarget(fpsent *d, aistate &b, fpsent *e, float yaw, float pitch, float dist) { // add margins of error if(weaprange(d, d->gunselect, dist) || (d->skill <= 100 && !rnd(d->skill))) { if(d->gunselect == GUN_FIST) return true; float skew = clamp(float(lastmillis-d->ai->enemymillis)/float((d->skill*guns[d->gunselect].attackdelay/200.f)), 0.f, guns[d->gunselect].projspeed ? 0.25f : 1e16f), offy = yaw-d->yaw, offp = pitch-d->pitch; if(offy > 180) offy -= 360; else if(offy < -180) offy += 360; if(fabs(offy) <= d->ai->views[0]*skew && fabs(offp) <= d->ai->views[1]*skew) return true; } return false; } vec getaimpos(fpsent *d, fpsent *e) { vec o = e->o; if(d->gunselect == GUN_RL) o.z += (e->aboveeye*0.2f)-(0.8f*d->eyeheight); else if(d->gunselect != GUN_GL) o.z += (e->aboveeye-e->eyeheight)*0.5f; if(d->skill <= 100) { if(lastmillis >= d->ai->lastaimrnd) { const int aiskew[NUMGUNS] = { 1, 10, 50, 5, 20, 1, 100, 10, 10, 10, 1, 1 }; #define rndaioffset(r) ((rnd(int(r*aiskew[d->gunselect]*2)+1)-(r*aiskew[d->gunselect]))*(1.f/float(max(d->skill, 1)))) loopk(3) d->ai->aimrnd[k] = rndaioffset(e->radius); int dur = (d->skill+10)*10; d->ai->lastaimrnd = lastmillis+dur+rnd(dur); } loopk(3) o[k] += d->ai->aimrnd[k]; } return o; } void create(fpsent *d) { if(!d->ai) d->ai = new aiinfo; } void destroy(fpsent *d) { if(d->ai) DELETEP(d->ai); } void init(fpsent *d, int at, int ocn, int sk, int bn, int pm, const char *name, const char *team) { loadwaypoints(); fpsent *o = newclient(ocn); d->aitype = at; bool resetthisguy = false; if(!d->name[0]) { if(aidebug) conoutf("%s assigned to %s at skill %d", colorname(d, name), o ? colorname(o) : "?", sk); else conoutf("connected: %s", colorname(d, name)); resetthisguy = true; } else { if(d->ownernum != ocn) { if(aidebug) conoutf("%s reassigned to %s", colorname(d, name), o ? colorname(o) : "?"); resetthisguy = true; } if(d->skill != sk && aidebug) conoutf("%s changed skill to %d", colorname(d, name), sk); } copystring(d->name, name, MAXNAMELEN+1); copystring(d->team, team, MAXTEAMLEN+1); d->ownernum = ocn; d->skill = sk; d->playermodel = chooserandomplayermodel(pm); if(resetthisguy) removeweapons(d); if(d->ownernum >= 0 && player1->clientnum == d->ownernum) { create(d); if(d->ai) { d->ai->views[0] = viewfieldx(d->skill); d->ai->views[1] = viewfieldy(d->skill); d->ai->views[2] = viewdist(d->skill); } } else if(d->ai) destroy(d); } void update() { if(intermission) { loopv(players) if(players[i]->ai) players[i]->stopmoving(); } else // fixed rate logic done out-of-sequence at 1 frame per second for each ai { if(totalmillis-updatemillis > 1000) { avoid(); forcegun = multiplayer(false) ? -1 : aiforcegun; updatemillis = totalmillis; } if(!iteration && totalmillis-itermillis > 1000) { iteration = 1; itermillis = totalmillis; } int count = 0; loopv(players) if(players[i]->ai) think(players[i], ++count == iteration ? true : false); if(++iteration > count) iteration = 0; } } bool checkothers(vector &targets, fpsent *d, int state, int targtype, int target, bool teams) { // checks the states of other ai for a match targets.setsize(0); loopv(players) { fpsent *e = players[i]; if(e == d || !e->ai || e->state != CS_ALIVE) continue; if(targets.find(e->clientnum) >= 0) continue; if(teams && d && !isteam(d->team, e->team)) continue; aistate &b = e->ai->getstate(); if(state >= 0 && b.type != state) continue; if(target >= 0 && b.target != target) continue; if(targtype >=0 && b.targtype != targtype) continue; targets.add(e->clientnum); } return !targets.empty(); } bool makeroute(fpsent *d, aistate &b, int node, bool changed, int retries) { if(!iswaypoint(d->lastnode)) return false; if(changed && d->ai->route.length() > 1 && d->ai->route[0] == node) return true; // retry fails: 0 = first attempt, 1 = try ignoring obstacles, 2 = try ignoring prevnodes too if(route(d, d->lastnode, node, d->ai->route, obstacles, retries)) { b.override = false; return true; } d->ai->clear(true); if(retries <= 1) return makeroute(d, b, node, false, retries+1); return false; } bool makeroute(fpsent *d, aistate &b, const vec &pos, bool changed, int retries) { int node = closestwaypoint(pos, SIGHTMIN, true); return makeroute(d, b, node, changed, retries); } bool randomnode(fpsent *d, aistate &b, const vec &pos, float guard, float wander) { static vector candidates; candidates.setsize(0); findwaypointswithin(pos, guard, wander, candidates); while(!candidates.empty()) { int w = rnd(candidates.length()), n = candidates.removeunordered(w); if(n != d->lastnode && !d->ai->hasprevnode(n) && !obstacles.find(n, d) && makeroute(d, b, n)) return true; } return false; } bool randomnode(fpsent *d, aistate &b, float guard, float wander) { return randomnode(d, b, d->feetpos(), guard, wander); } bool badhealth(fpsent *d) { if(d->skill <= 100) return d->health <= (111-d->skill)/4; return false; } bool enemy(fpsent *d, aistate &b, const vec &pos, float guard = SIGHTMIN, int pursue = 0) { fpsent *t = NULL; vec dp = d->headpos(); float mindist = guard*guard, bestdist = 1e16f; loopv(players) { fpsent *e = players[i]; if(e == d || !targetable(d, e)) continue; vec ep = getaimpos(d, e); float dist = ep.squaredist(dp); if(dist < bestdist && (cansee(d, dp, ep) || dist <= mindist)) { t = e; bestdist = dist; } } if(t && violence(d, b, t, pursue)) return true; return false; } bool patrol(fpsent *d, aistate &b, const vec &pos, float guard, float wander, int walk, bool retry) { vec feet = d->feetpos(); if(walk == 2 || b.override || (walk && feet.squaredist(pos) <= guard*guard) || !makeroute(d, b, pos)) { // run away and back to keep ourselves busy if(!b.override && randomnode(d, b, pos, guard, wander)) { b.override = true; return true; } else if(d->ai->route.empty()) { if(!retry) { b.override = false; return patrol(d, b, pos, guard, wander, walk, true); } b.override = false; return false; } } b.override = false; return true; } bool defend(fpsent *d, aistate &b, const vec &pos, float guard, float wander, int walk) { bool hasenemy = enemy(d, b, pos, wander, d->gunselect == GUN_FIST ? 1 : 0); if(!walk) { if(d->feetpos().squaredist(pos) <= guard*guard) { b.idle = hasenemy ? 2 : 1; return true; } walk++; } return patrol(d, b, pos, guard, wander, walk); } bool violence(fpsent *d, aistate &b, fpsent *e, int pursue) { if(e && targetable(d, e)) { if(pursue) { if((b.targtype != AI_T_AFFINITY || !(pursue%2)) && makeroute(d, b, e->lastnode)) d->ai->switchstate(b, AI_S_PURSUE, AI_T_PLAYER, e->clientnum); else if(pursue >= 3) return false; // can't pursue } if(d->ai->enemy != e->clientnum) { d->ai->enemyseen = d->ai->enemymillis = lastmillis; d->ai->enemy = e->clientnum; } return true; } return false; } bool target(fpsent *d, aistate &b, int pursue = 0, bool force = false, float mindist = 0.f) { static vector hastried; hastried.setsize(0); vec dp = d->headpos(); while(true) { float dist = 1e16f; fpsent *t = NULL; loopv(players) { fpsent *e = players[i]; if(e == d || hastried.find(e) >= 0 || !targetable(d, e)) continue; vec ep = getaimpos(d, e); float v = ep.squaredist(dp); if((!t || v < dist) && (mindist <= 0 || v <= mindist) && (force || cansee(d, dp, ep))) { t = e; dist = v; } } if(t) { if(violence(d, b, t, pursue)) return true; hastried.add(t); } else break; } return false; } int isgoodammo(int gun) { return gun >= GUN_SG && gun <= GUN_GL; } bool hasgoodammo(fpsent *d) { static const int goodguns[] = { GUN_CG, GUN_RL, GUN_SG, GUN_RIFLE }; loopi(sizeof(goodguns)/sizeof(goodguns[0])) if(d->hasammo(goodguns[0])) return true; if(d->ammo[GUN_GL] > 5) return true; return false; } void assist(fpsent *d, aistate &b, vector &interests, bool all, bool force) { loopv(players) { fpsent *e = players[i]; if(e == d || (!all && e->aitype != AI_NONE) || !isteam(d->team, e->team)) continue; interest &n = interests.add(); n.state = AI_S_DEFEND; n.node = e->lastnode; n.target = e->clientnum; n.targtype = AI_T_PLAYER; n.score = e->o.squaredist(d->o)/(hasgoodammo(d) ? 1e8f : (force ? 1e4f : 1e2f)); } } static void tryitem(fpsent *d, extentity &e, int id, aistate &b, vector &interests, bool force = false) { float score = 0; switch(e.type) { case I_HEALTH: if(d->health < min(d->skill, 75)) score = 1e3f; break; case I_QUAD: score = 1e3f; break; case I_BOOST: score = 1e2f; break; case I_GREENARMOUR: case I_YELLOWARMOUR: { int atype = A_GREEN + e.type - I_GREENARMOUR; if(atype > d->armourtype) score = atype == A_YELLOW ? 1e2f : 1e1f; else if(d->armour < 50) score = 1e1f; break; } default: { if(e.type >= I_SHELLS && e.type <= I_CARTRIDGES && !d->hasmaxammo(e.type)) { int gun = e.type - I_SHELLS + GUN_SG; // go get a weapon upgrade if(gun == d->ai->weappref) score = 1e8f; else if(isgoodammo(gun)) score = hasgoodammo(d) ? 1e2f : 1e4f; } break; } } if(score != 0) { interest &n = interests.add(); n.state = AI_S_INTEREST; n.node = closestwaypoint(e.o, SIGHTMIN, true); n.target = id; n.targtype = AI_T_ENTITY; n.score = d->feetpos().squaredist(e.o)/(force ? -1 : score); } } void items(fpsent *d, aistate &b, vector &interests, bool force = false) { loopv(entities::ents) { extentity &e = *(extentity *)entities::ents[i]; if(!e.spawned || !d->canpickup(e.type)) continue; tryitem(d, e, i, b, interests, force); } } static vector targets; bool parseinterests(fpsent *d, aistate &b, vector &interests, bool override, bool ignore) { while(!interests.empty()) { int q = interests.length()-1; loopi(interests.length()-1) if(interests[i].score < interests[q].score) q = i; interest n = interests.removeunordered(q); bool proceed = true; if(!ignore) switch(n.state) { case AI_S_DEFEND: // don't get into herds proceed = !checkothers(targets, d, n.state, n.targtype, n.target, true); break; default: break; } if(proceed && makeroute(d, b, n.node)) { d->ai->switchstate(b, n.state, n.targtype, n.target); return true; } } return false; } bool find(fpsent *d, aistate &b, bool override = false) { static vector interests; interests.setsize(0); if(!m_noitems) { if((!m_noammo && !hasgoodammo(d)) || d->health < min(d->skill - 15, 75)) items(d, b, interests); else { static vector nearby; nearby.setsize(0); findents(I_SHELLS, I_QUAD, false, d->feetpos(), vec(32, 32, 24), nearby); loopv(nearby) { int id = nearby[i]; extentity &e = *(extentity *)entities::ents[id]; if(d->canpickup(e.type)) tryitem(d, e, id, b, interests); } } } if(cmode) cmode->aifind(d, b, interests); if(m_teammode) assist(d, b, interests); return parseinterests(d, b, interests, override); } bool findassist(fpsent *d, aistate &b, bool override = false) { static vector interests; interests.setsize(0); assist(d, b, interests); while(!interests.empty()) { int q = interests.length()-1; loopi(interests.length()-1) if(interests[i].score < interests[q].score) q = i; interest n = interests.removeunordered(q); bool proceed = true; switch(n.state) { case AI_S_DEFEND: // don't get into herds proceed = !checkothers(targets, d, n.state, n.targtype, n.target, true); break; default: break; } if(proceed && makeroute(d, b, n.node)) { d->ai->switchstate(b, n.state, n.targtype, n.target); return true; } } return false; } void damaged(fpsent *d, fpsent *e) { if(d->ai && canmove(d) && targetable(d, e)) // see if this ai is interested in a grudge { aistate &b = d->ai->getstate(); if(violence(d, b, e, d->gunselect == GUN_FIST ? 1 : 0)) return; } if(checkothers(targets, d, AI_S_DEFEND, AI_T_PLAYER, d->clientnum, true)) { loopv(targets) { fpsent *t = getclient(targets[i]); if(!t->ai || !canmove(t) || !targetable(t, e)) continue; aistate &c = t->ai->getstate(); if(violence(t, c, e, d->gunselect == GUN_FIST ? 1 : 0)) return; } } } void findorientation(vec &o, float yaw, float pitch, vec &pos) { vec dir; vecfromyawpitch(yaw, pitch, 1, 0, dir); if(raycubepos(o, dir, pos, 0, RAY_CLIPMAT|RAY_SKIPFIRST) == -1) pos = dir.mul(2*getworldsize()).add(o); //otherwise 3dgui won't work when outside of map } void setup(fpsent *d) { d->ai->clearsetup(); d->ai->reset(true); d->ai->lastrun = lastmillis; if(m_insta) d->ai->weappref = GUN_RIFLE; else { if(forcegun >= 0 && forcegun < NUMGUNS) d->ai->weappref = forcegun; else if(m_noammo) d->ai->weappref = -1; else d->ai->weappref = rnd(GUN_GL-GUN_SG+1)+GUN_SG; } vec dp = d->headpos(); findorientation(dp, d->yaw, d->pitch, d->ai->target); } void spawned(fpsent *d) { if(d->ai) setup(d); } void killed(fpsent *d, fpsent *e) { if(d->ai) d->ai->reset(); } void itemspawned(int ent) { if(entities::ents.inrange(ent) && entities::ents[ent]->type >= I_SHELLS && entities::ents[ent]->type <= I_QUAD) { loopv(players) if(players[i] && players[i]->ai && players[i]->aitype == AI_BOT && players[i]->canpickup(entities::ents[ent]->type)) { fpsent *d = players[i]; bool wantsitem = false; switch(entities::ents[ent]->type) { case I_BOOST: case I_HEALTH: wantsitem = badhealth(d); break; case I_GREENARMOUR: case I_YELLOWARMOUR: case I_QUAD: break; default: { itemstat &is = itemstats[entities::ents[ent]->type-I_SHELLS]; wantsitem = isgoodammo(is.info) && d->ammo[is.info] <= (d->ai->weappref == is.info ? is.add : is.add/2); break; } } if(wantsitem) { aistate &b = d->ai->getstate(); if(b.targtype == AI_T_AFFINITY) continue; if(b.type == AI_S_INTEREST && b.targtype == AI_T_ENTITY) { if(entities::ents.inrange(b.target)) { if(d->o.squaredist(entities::ents[ent]->o) < d->o.squaredist(entities::ents[b.target]->o)) d->ai->switchstate(b, AI_S_INTEREST, AI_T_ENTITY, ent); } continue; } d->ai->switchstate(b, AI_S_INTEREST, AI_T_ENTITY, ent); } } } } bool check(fpsent *d, aistate &b) { if(cmode && cmode->aicheck(d, b)) return true; return false; } int dowait(fpsent *d, aistate &b) { d->ai->clear(true); // ensure they're clean if(check(d, b) || find(d, b)) return 1; if(target(d, b, 4, false)) return 1; if(target(d, b, 4, true)) return 1; if(randomnode(d, b, SIGHTMIN, 1e16f)) { d->ai->switchstate(b, AI_S_INTEREST, AI_T_NODE, d->ai->route[0]); return 1; } return 0; // but don't pop the state } int dodefend(fpsent *d, aistate &b) { if(d->state == CS_ALIVE) { switch(b.targtype) { case AI_T_NODE: if(check(d, b)) return 1; if(iswaypoint(b.target)) return defend(d, b, waypoints[b.target].o) ? 1 : 0; break; case AI_T_ENTITY: if(check(d, b)) return 1; if(entities::ents.inrange(b.target)) return defend(d, b, entities::ents[b.target]->o) ? 1 : 0; break; case AI_T_AFFINITY: if(cmode) return cmode->aidefend(d, b) ? 1 : 0; break; case AI_T_PLAYER: { if(check(d, b)) return 1; fpsent *e = getclient(b.target); if(e && e->state == CS_ALIVE) return defend(d, b, e->feetpos()) ? 1 : 0; break; } default: break; } } return 0; } int dointerest(fpsent *d, aistate &b) { if(d->state != CS_ALIVE) return 0; switch(b.targtype) { case AI_T_NODE: // this is like a wait state without sitting still.. if(check(d, b) || find(d, b)) return 1; if(target(d, b, 4, true)) return 1; if(iswaypoint(b.target) && vec(waypoints[b.target].o).sub(d->feetpos()).magnitude() > CLOSEDIST) return makeroute(d, b, waypoints[b.target].o) ? 1 : 0; break; case AI_T_ENTITY: if(entities::ents.inrange(b.target)) { extentity &e = *(extentity *)entities::ents[b.target]; if(!e.spawned || e.type < I_SHELLS || e.type > I_CARTRIDGES || d->hasmaxammo(e.type)) return 0; //if(d->feetpos().squaredist(e.o) <= CLOSEDIST*CLOSEDIST) //{ // b.idle = 1; // return true; //} return makeroute(d, b, e.o) ? 1 : 0; } break; } return 0; } int dopursue(fpsent *d, aistate &b) { if(d->state == CS_ALIVE) { switch(b.targtype) { case AI_T_NODE: { if(check(d, b)) return 1; if(iswaypoint(b.target)) return defend(d, b, waypoints[b.target].o) ? 1 : 0; break; } case AI_T_AFFINITY: { if(cmode) return cmode->aipursue(d, b) ? 1 : 0; break; } case AI_T_PLAYER: { //if(check(d, b)) return 1; fpsent *e = getclient(b.target); if(e && e->state == CS_ALIVE) { float guard = SIGHTMIN, wander = guns[d->gunselect].range; if(d->gunselect == GUN_FIST) guard = 0.f; return patrol(d, b, e->feetpos(), guard, wander) ? 1 : 0; } break; } default: break; } } return 0; } int closenode(fpsent *d) { vec pos = d->feetpos(); int node1 = -1, node2 = -1; float mindist1 = CLOSEDIST*CLOSEDIST, mindist2 = CLOSEDIST*CLOSEDIST; loopv(d->ai->route) if(iswaypoint(d->ai->route[i])) { vec epos = waypoints[d->ai->route[i]].o; float dist = epos.squaredist(pos); if(dist > FARDIST*FARDIST) continue; int entid = obstacles.remap(d, d->ai->route[i], epos); if(entid >= 0) { if(entid != i) dist = epos.squaredist(pos); if(dist < mindist1) { node1 = i; mindist1 = dist; } } else if(dist < mindist2) { node2 = i; mindist2 = dist; } } return node1 >= 0 ? node1 : node2; } int wpspot(fpsent *d, int n, bool check = false) { if(iswaypoint(n)) loopk(2) { vec epos = waypoints[n].o; int entid = obstacles.remap(d, n, epos, k!=0); if(iswaypoint(entid)) { d->ai->spot = epos; d->ai->targnode = entid; return !check || d->feetpos().squaredist(epos) > MINWPDIST*MINWPDIST ? 1 : 2; } } return 0; } int randomlink(fpsent *d, int n) { if(iswaypoint(n) && waypoints[n].haslinks()) { waypoint &w = waypoints[n]; static vector linkmap; linkmap.setsize(0); loopi(MAXWAYPOINTLINKS) { if(!w.links[i]) break; if(iswaypoint(w.links[i]) && !d->ai->hasprevnode(w.links[i]) && d->ai->route.find(w.links[i]) < 0) linkmap.add(w.links[i]); } if(!linkmap.empty()) return linkmap[rnd(linkmap.length())]; } return -1; } bool anynode(fpsent *d, aistate &b, int len = NUMPREVNODES) { if(iswaypoint(d->lastnode)) loopk(2) { d->ai->clear(k ? true : false); int n = randomlink(d, d->lastnode); if(wpspot(d, n)) { d->ai->route.add(n); d->ai->route.add(d->lastnode); loopi(len) { n = randomlink(d, n); if(iswaypoint(n)) d->ai->route.insert(0, n); else break; } return true; } } return false; } bool checkroute(fpsent *d, int n) { if(d->ai->route.empty() || !d->ai->route.inrange(n)) return false; int last = d->ai->lastcheck ? lastmillis-d->ai->lastcheck : 0; if(last < 500 || n < 3) return false; // route length is too short d->ai->lastcheck = lastmillis; int w = iswaypoint(d->lastnode) ? d->lastnode : d->ai->route[n], c = min(n-1, NUMPREVNODES); loopj(c) // check ahead to see if we need to go around something { int p = n-j-1, v = d->ai->route[p]; if(d->ai->hasprevnode(v) || obstacles.find(v, d)) // something is in the way, try to remap around it { int m = p-1; if(m < 3) return false; // route length is too short from this point loopirev(m) { int t = d->ai->route[i]; if(!d->ai->hasprevnode(t) && !obstacles.find(t, d)) { static vector remap; remap.setsize(0); if(route(d, w, t, remap, obstacles)) { // kill what we don't want and put the remap in while(d->ai->route.length() > i) d->ai->route.pop(); loopvk(remap) d->ai->route.add(remap[k]); return true; } return false; // we failed } } return false; } } return false; } bool hunt(fpsent *d, aistate &b) { if(!d->ai->route.empty()) { int n = closenode(d); if(d->ai->route.inrange(n) && checkroute(d, n)) n = closenode(d); if(d->ai->route.inrange(n)) { if(!n) { switch(wpspot(d, d->ai->route[n], true)) { case 2: d->ai->clear(false); case 1: return true; // not close enough to pop it yet case 0: default: break; } } else { while(d->ai->route.length() > n+1) d->ai->route.pop(); // waka-waka-waka-waka int m = n-1; // next, please! if(d->ai->route.inrange(m) && wpspot(d, d->ai->route[m])) return true; } } } b.override = false; return anynode(d, b); } void jumpto(fpsent *d, aistate &b, const vec &pos) { vec off = vec(pos).sub(d->feetpos()), dir(off.x, off.y, 0); bool sequenced = d->ai->blockseq || d->ai->targseq, offground = d->timeinair && !d->inwater, jump = !offground && lastmillis >= d->ai->jumpseed && (sequenced || off.z >= JUMPMIN || lastmillis >= d->ai->jumprand); if(jump) { vec old = d->o; d->o = vec(pos).add(vec(0, 0, d->eyeheight)); if(!collide(d, vec(0, 0, 1))) jump = false; d->o = old; if(jump) { float radius = 18*18; loopv(entities::ents) if(entities::ents[i]->type == JUMPPAD) { fpsentity &e = *(fpsentity *)entities::ents[i]; if(e.o.squaredist(pos) <= radius) { jump = false; break; } } } } if(jump) { d->jumping = true; int seed = (111-d->skill)*(d->inwater ? 3 : 5); d->ai->jumpseed = lastmillis+seed+rnd(seed); seed *= b.idle ? 50 : 25; d->ai->jumprand = lastmillis+seed+rnd(seed); } } void fixfullrange(float &yaw, float &pitch, float &roll, bool full) { if(full) { while(pitch < -180.0f) pitch += 360.0f; while(pitch >= 180.0f) pitch -= 360.0f; while(roll < -180.0f) roll += 360.0f; while(roll >= 180.0f) roll -= 360.0f; } else { if(pitch > 89.9f) pitch = 89.9f; if(pitch < -89.9f) pitch = -89.9f; if(roll > 89.9f) roll = 89.9f; if(roll < -89.9f) roll = -89.9f; } while(yaw < 0.0f) yaw += 360.0f; while(yaw >= 360.0f) yaw -= 360.0f; } void fixrange(float &yaw, float &pitch) { float r = 0.f; fixfullrange(yaw, pitch, r, false); } void getyawpitch(const vec &from, const vec &pos, float &yaw, float &pitch) { float dist = from.dist(pos); yaw = -atan2(pos.x-from.x, pos.y-from.y)/RAD; pitch = asin((pos.z-from.z)/dist)/RAD; } void scaleyawpitch(float &yaw, float &pitch, float targyaw, float targpitch, float frame, float scale) { if(yaw < targyaw-180.0f) yaw += 360.0f; if(yaw > targyaw+180.0f) yaw -= 360.0f; float offyaw = fabs(targyaw-yaw)*frame, offpitch = fabs(targpitch-pitch)*frame*scale; if(targyaw > yaw) { yaw += offyaw; if(targyaw < yaw) yaw = targyaw; } else if(targyaw < yaw) { yaw -= offyaw; if(targyaw > yaw) yaw = targyaw; } if(targpitch > pitch) { pitch += offpitch; if(targpitch < pitch) pitch = targpitch; } else if(targpitch < pitch) { pitch -= offpitch; if(targpitch > pitch) pitch = targpitch; } fixrange(yaw, pitch); } bool lockon(fpsent *d, fpsent *e, float maxdist) { if(d->gunselect == GUN_FIST && !d->blocked && !d->timeinair) { vec dir = vec(e->o).sub(d->o); float xydist = dir.x*dir.x+dir.y*dir.y, zdist = dir.z*dir.z, mdist = maxdist*maxdist, ddist = d->radius*d->radius+e->radius*e->radius; if(zdist <= ddist && xydist >= ddist+4 && xydist <= mdist+ddist) return true; } return false; } int process(fpsent *d, aistate &b) { int result = 0, stupify = d->skill <= 10+rnd(15) ? rnd(d->skill*1000) : 0, skmod = 101-d->skill; float frame = d->skill <= 100 ? float(lastmillis-d->ai->lastrun)/float(max(skmod,1)*10) : 1; vec dp = d->headpos(); bool idle = b.idle == 1 || (stupify && stupify <= skmod); d->ai->dontmove = false; if(idle) { d->ai->lastaction = d->ai->lasthunt = lastmillis; d->ai->dontmove = true; d->ai->spot = vec(0, 0, 0); } else if(hunt(d, b)) { getyawpitch(dp, vec(d->ai->spot).add(vec(0, 0, d->eyeheight)), d->ai->targyaw, d->ai->targpitch); d->ai->lasthunt = lastmillis; } else { idle = d->ai->dontmove = true; d->ai->spot = vec(0, 0, 0); } if(!d->ai->dontmove) jumpto(d, b, d->ai->spot); fpsent *e = getclient(d->ai->enemy); bool enemyok = e && targetable(d, e); if(!enemyok || d->skill >= 50) { fpsent *f = (fpsent *)intersectclosest(dp, d->ai->target, d); if(f) { if(targetable(d, f)) { if(!enemyok) violence(d, b, f, d->gunselect == GUN_FIST ? 1 : 0); enemyok = true; e = f; } else enemyok = false; } else if(!enemyok && target(d, b, d->gunselect == GUN_FIST ? 1 : 0, false, SIGHTMIN)) enemyok = (e = getclient(d->ai->enemy)) != NULL; } if(enemyok) { vec ep = getaimpos(d, e); float yaw, pitch; getyawpitch(dp, ep, yaw, pitch); fixrange(yaw, pitch); bool insight = cansee(d, dp, ep), hasseen = d->ai->enemyseen && lastmillis-d->ai->enemyseen <= (d->skill*10)+3000, quick = d->ai->enemyseen && lastmillis-d->ai->enemyseen <= (d->gunselect == GUN_CG ? 300 : skmod)+30; if(insight) d->ai->enemyseen = lastmillis; if(idle || insight || hasseen || quick) { float sskew = insight || d->skill > 100 ? 1.5f : (hasseen ? 1.f : 0.5f); if(insight && lockon(d, e, 16)) { d->ai->targyaw = yaw; d->ai->targpitch = pitch; if(!idle) frame *= 2; d->ai->becareful = false; } scaleyawpitch(d->yaw, d->pitch, yaw, pitch, frame, sskew); if(insight || quick) { if(canshoot(d, e) && hastarget(d, b, e, yaw, pitch, dp.squaredist(ep))) { d->attacking = true; d->ai->lastaction = lastmillis; result = 3; } else result = 2; } else result = 1; } else { if(!d->ai->enemyseen || lastmillis-d->ai->enemyseen > (d->skill*50)+3000) { d->ai->enemy = -1; d->ai->enemyseen = d->ai->enemymillis = 0; } enemyok = false; result = 0; } } else { if(!enemyok) { d->ai->enemy = -1; d->ai->enemyseen = d->ai->enemymillis = 0; } enemyok = false; result = 0; } fixrange(d->ai->targyaw, d->ai->targpitch); if(!result) scaleyawpitch(d->yaw, d->pitch, d->ai->targyaw, d->ai->targpitch, frame*0.25f, 1.f); if(d->ai->becareful && d->physstate == PHYS_FALL) { float offyaw, offpitch; vec v = vec(d->vel).normalize(); vectoyawpitch(v, offyaw, offpitch); offyaw -= d->yaw; offpitch -= d->pitch; if(fabs(offyaw)+fabs(offpitch) >= 135) d->ai->becareful = false; else if(d->ai->becareful) d->ai->dontmove = true; } else d->ai->becareful = false; if(d->ai->dontmove) d->move = d->strafe = 0; else { // our guys move one way.. but turn another?! :) const struct aimdir { int move, strafe, offset; } aimdirs[8] = { { 1, 0, 0 }, { 1, -1, 45 }, { 0, -1, 90 }, { -1, -1, 135 }, { -1, 0, 180 }, { -1, 1, 225 }, { 0, 1, 270 }, { 1, 1, 315 } }; float yaw = d->ai->targyaw-d->yaw; while(yaw < 0.0f) yaw += 360.0f; while(yaw >= 360.0f) yaw -= 360.0f; int r = clamp(((int)floor((yaw+22.5f)/45.0f))&7, 0, 7); const aimdir &ad = aimdirs[r]; d->move = ad.move; d->strafe = ad.strafe; } findorientation(dp, d->yaw, d->pitch, d->ai->target); return result; } bool hasrange(fpsent *d, fpsent *e, int weap) { if(!e) return true; if(targetable(d, e)) { vec ep = getaimpos(d, e); float dist = ep.squaredist(d->headpos()); if(weaprange(d, weap, dist)) return true; } return false; } bool request(fpsent *d, aistate &b) { fpsent *e = getclient(d->ai->enemy); if(!d->hasammo(d->gunselect) || !hasrange(d, e, d->gunselect) || (d->gunselect != d->ai->weappref && (!isgoodammo(d->gunselect) || d->hasammo(d->ai->weappref)))) { static const int gunprefs[] = { GUN_CG, GUN_RL, GUN_SG, GUN_RIFLE, GUN_GL, GUN_PISTOL, GUN_FIST }; int gun = -1; if(d->hasammo(d->ai->weappref) && hasrange(d, e, d->ai->weappref)) gun = d->ai->weappref; else { loopi(sizeof(gunprefs)/sizeof(gunprefs[0])) if(d->hasammo(gunprefs[i]) && hasrange(d, e, gunprefs[i])) { gun = gunprefs[i]; break; } } if(gun >= 0 && gun != d->gunselect) gunselect(gun, d); } return process(d, b) >= 2; } void timeouts(fpsent *d, aistate &b) { if(d->blocked) { d->ai->blocktime += lastmillis-d->ai->lastrun; if(d->ai->blocktime > (d->ai->blockseq+1)*1000) { d->ai->blockseq++; switch(d->ai->blockseq) { case 1: case 2: case 3: if(entities::ents.inrange(d->ai->targnode)) d->ai->addprevnode(d->ai->targnode); d->ai->clear(false); break; case 4: d->ai->reset(true); break; case 5: d->ai->reset(false); break; case 6: default: suicide(d); return; break; // this is our last resort.. } } } else d->ai->blocktime = d->ai->blockseq = 0; if(d->ai->targnode == d->ai->targlast) { d->ai->targtime += lastmillis-d->ai->lastrun; if(d->ai->targtime > (d->ai->targseq+1)*1000) { d->ai->targseq++; switch(d->ai->targseq) { case 1: case 2: case 3: if(entities::ents.inrange(d->ai->targnode)) d->ai->addprevnode(d->ai->targnode); d->ai->clear(false); break; case 4: d->ai->reset(true); break; case 5: d->ai->reset(false); break; case 6: default: suicide(d); return; break; // this is our last resort.. } } } else { d->ai->targtime = d->ai->targseq = 0; d->ai->targlast = d->ai->targnode; } if(d->ai->lasthunt) { int millis = lastmillis-d->ai->lasthunt; if(millis <= 1000) { d->ai->tryreset = false; d->ai->huntseq = 0; } else if(millis > (d->ai->huntseq+1)*1000) { d->ai->huntseq++; switch(d->ai->huntseq) { case 1: d->ai->reset(true); break; case 2: d->ai->reset(false); break; case 3: default: suicide(d); return; break; // this is our last resort.. } } } } void logic(fpsent *d, aistate &b, bool run) { bool allowmove = canmove(d) && b.type != AI_S_WAIT; if(d->state != CS_ALIVE || !allowmove) d->stopmoving(); if(d->state == CS_ALIVE) { if(allowmove) { if(!request(d, b)) target(d, b, d->gunselect == GUN_FIST ? 1 : 0, b.idle ? true : false); shoot(d, d->ai->target); } if(!intermission) { if(d->ragdoll) cleanragdoll(d); moveplayer(d, 10, true); if(allowmove && !b.idle) timeouts(d, b); if(d->quadmillis) entities::checkquad(curtime, d); entities::checkitems(d); if(cmode) cmode->checkitems(d); } } else if(d->state == CS_DEAD) { if(d->ragdoll) moveragdoll(d); else if(lastmillis-d->lastpain<2000) { d->move = d->strafe = 0; moveplayer(d, 10, false); } } d->attacking = d->jumping = false; } void avoid() { // guess as to the radius of ai and other critters relying on the avoid set for now float guessradius = player1->radius; obstacles.clear(); loopv(players) { dynent *d = players[i]; if(d->state != CS_ALIVE) continue; obstacles.avoidnear(d, d->o.z + d->aboveeye + 1, d->feetpos(), guessradius + d->radius); } extern avoidset wpavoid; obstacles.add(wpavoid); avoidweapons(obstacles, guessradius); } void think(fpsent *d, bool run) { // the state stack works like a chain of commands, certain commands simply replace each other // others spawn new commands to the stack the ai reads the top command from the stack and executes // it or pops the stack and goes back along the history until it finds a suitable command to execute bool cleannext = false; if(d->ai->state.empty()) d->ai->addstate(AI_S_WAIT); loopvrev(d->ai->state) { aistate &c = d->ai->state[i]; if(cleannext) { c.millis = lastmillis; c.override = false; cleannext = false; } if(d->state == CS_DEAD && d->respawned!=d->lifesequence && (!cmode || cmode->respawnwait(d) <= 0) && lastmillis - d->lastpain >= 500) { addmsg(N_TRYSPAWN, "rc", d); d->respawned = d->lifesequence; } else if(d->state == CS_ALIVE && run) { int result = 0; c.idle = 0; switch(c.type) { case AI_S_WAIT: result = dowait(d, c); break; case AI_S_DEFEND: result = dodefend(d, c); break; case AI_S_PURSUE: result = dopursue(d, c); break; case AI_S_INTEREST: result = dointerest(d, c); break; default: result = 0; break; } if(result <= 0) { if(c.type != AI_S_WAIT) { switch(result) { case 0: default: d->ai->removestate(i); cleannext = true; break; case -1: i = d->ai->state.length()-1; break; } continue; // shouldn't interfere } } } logic(d, c, run); break; } if(d->ai->trywipe) d->ai->wipe(); d->ai->lastrun = lastmillis; } void drawroute(fpsent *d, float amt = 1.f) { int last = -1; loopvrev(d->ai->route) { if(d->ai->route.inrange(last)) { int index = d->ai->route[i], prev = d->ai->route[last]; if(iswaypoint(index) && iswaypoint(prev)) { waypoint &e = waypoints[index], &f = waypoints[prev]; vec fr = f.o, dr = e.o; fr.z += amt; dr.z += amt; particle_flare(fr, dr, 1, PART_STREAK, 0xFFFFFF); } } last = i; } if(aidebug >= 5) { vec pos = d->feetpos(); if(d->ai->spot != vec(0, 0, 0)) particle_flare(pos, d->ai->spot, 1, PART_LIGHTNING, 0x00FFFF); if(iswaypoint(d->ai->targnode)) particle_flare(pos, waypoints[d->ai->targnode].o, 1, PART_LIGHTNING, 0xFF00FF); if(iswaypoint(d->lastnode)) particle_flare(pos, waypoints[d->lastnode].o, 1, PART_LIGHTNING, 0xFFFF00); loopi(NUMPREVNODES) if(iswaypoint(d->ai->prevnodes[i])) { particle_flare(pos, waypoints[d->ai->prevnodes[i]].o, 1, PART_LIGHTNING, 0x884400); pos = waypoints[d->ai->prevnodes[i]].o; } } } VAR(showwaypoints, 0, 0, 1); VAR(showwaypointsradius, 0, 200, 10000); const char *stnames[AI_S_MAX] = { "wait", "defend", "pursue", "interest" }, *sttypes[AI_T_MAX+1] = { "none", "node", "player", "affinity", "entity" }; void render() { if(aidebug > 1) { int total = 0, alive = 0; loopv(players) if(players[i]->ai) total++; loopv(players) if(players[i]->state == CS_ALIVE && players[i]->ai) { fpsent *d = players[i]; vec pos = d->abovehead(); pos.z += 3; alive++; if(aidebug >= 4) drawroute(d, 4.f*(float(alive)/float(total))); if(aidebug >= 3) { defformatstring(q)("node: %d route: %d (%d)", d->lastnode, !d->ai->route.empty() ? d->ai->route[0] : -1, d->ai->route.length() ); particle_textcopy(pos, q, PART_TEXT, 1); pos.z += 2; } bool top = true; loopvrev(d->ai->state) { aistate &b = d->ai->state[i]; defformatstring(s)("%s%s (%d ms) %s:%d", top ? "\fg" : "\fy", stnames[b.type], lastmillis-b.millis, sttypes[b.targtype+1], b.target ); particle_textcopy(pos, s, PART_TEXT, 1); pos.z += 2; if(top) { if(aidebug >= 3) top = false; else break; } } if(aidebug >= 3) { if(d->ai->weappref >= 0 && d->ai->weappref < NUMGUNS) { particle_textcopy(pos, guns[d->ai->weappref].name, PART_TEXT, 1); pos.z += 2; } fpsent *e = getclient(d->ai->enemy); if(e) { particle_textcopy(pos, colorname(e), PART_TEXT, 1); pos.z += 2; } } } if(aidebug >= 4) { int cur = 0; loopv(obstacles.obstacles) { const avoidset::obstacle &ob = obstacles.obstacles[i]; int next = cur + ob.numwaypoints; for(; cur < next; cur++) { int ent = obstacles.waypoints[cur]; if(iswaypoint(ent)) regular_particle_splash(PART_EDIT, 2, 40, waypoints[ent].o, 0xFF6600, 1.5f); } cur = next; } } } if(showwaypoints || aidebug >= 6) { vector close; int len = waypoints.length(); if(showwaypointsradius) { findwaypointswithin(camera1->o, 0, showwaypointsradius, close); len = close.length(); } loopi(len) { waypoint &w = waypoints[showwaypointsradius ? close[i] : i]; loopj(MAXWAYPOINTLINKS) { int link = w.links[j]; if(!link) break; particle_flare(w.o, waypoints[link].o, 1, PART_STREAK, 0x0000FF); } } } } } sandboxgamemaker-2.8.2+dfsg/src/fpsgame/aiman.h0000644000175000017500000002076712045412564020376 0ustar bofh80bofh80// server-side ai manager namespace aiman { bool dorefresh = false; VARN(serverbotlimit, botlimit, 0, 8, MAXBOTS); VARN(serverbotbalance, botbalance, 0, 1, 1); void calcteams(vector &teams) { const char *defaults[2] = { "good", "evil" }; loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_SPECTATOR || !ci->team[0]) continue; teamscore *t = NULL; loopvj(teams) if(!strcmp(teams[j].team, ci->team)) { t = &teams[j]; break; } if(t) t->score++; else teams.add(teamscore(ci->team, 1)); } teams.sort(teamscore::compare); if(teams.length() < int(sizeof(defaults)/sizeof(defaults[0]))) { loopi(sizeof(defaults)/sizeof(defaults[0])) { loopvj(teams) if(!strcmp(teams[j].team, defaults[i])) goto nextteam; teams.add(teamscore(defaults[i], 0)); nextteam:; } } } void balanceteams() { vector teams; calcteams(teams); vector reassign; loopv(bots) if(bots[i]) reassign.add(bots[i]); while(reassign.length() && teams.length() && teams[0].score > teams.last().score + 1) { teamscore &t = teams.last(); clientinfo *bot = NULL; loopv(reassign) if(reassign[i] && !strcmp(reassign[i]->team, teams[0].team)) { bot = reassign.removeunordered(i); teams[0].score--; t.score++; for(int j = teams.length() - 2; j >= 0; j--) { if(teams[j].score >= teams[j+1].score) break; swap(teams[j], teams[j+1]); } break; } if(bot) { if(smode && bot->state.state==CS_ALIVE) smode->changeteam(bot, bot->team, t.team); copystring(bot->team, t.team, MAXTEAMLEN+1); sendf(-1, 1, "riisi", N_SETTEAM, bot->clientnum, bot->team, 0); } else teams.remove(0, 1); } } const char *chooseteam() { vector teams; calcteams(teams); return teams.length() ? teams.last().team : ""; } static inline bool validaiclient(clientinfo *ci) { return ci->clientnum >= 0 && ci->state.aitype == AI_NONE && (ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege); } clientinfo *findaiclient(clientinfo *exclude = NULL) { clientinfo *least = NULL; loopv(clients) { clientinfo *ci = clients[i]; if(!validaiclient(ci) || ci==exclude) continue; if(!least || ci->bots.length() < least->bots.length()) least = ci; } return least; } bool addai(int skill, int limit) { int numai = 0, cn = -1, maxai = limit >= 0 ? min(limit, MAXBOTS) : MAXBOTS; loopv(bots) { clientinfo *ci = bots[i]; if(!ci || ci->ownernum < 0) { if(cn < 0) cn = i; continue; } numai++; } if(numai >= maxai) return false; if(bots.inrange(cn)) { clientinfo *ci = bots[cn]; if(ci) { // reuse a slot that was going to removed clientinfo *owner = findaiclient(); ci->ownernum = owner ? owner->clientnum : -1; ci->aireinit = 2; dorefresh = true; return true; } } else { cn = bots.length(); bots.add(NULL); } const char *team = m_teammode ? chooseteam() : ""; if(!bots[cn]) bots[cn] = new clientinfo; clientinfo *ci = bots[cn]; ci->clientnum = MAXCLIENTS + cn; ci->state.aitype = AI_BOT; clientinfo *owner = findaiclient(); ci->ownernum = owner ? owner->clientnum : -1; if(owner) owner->bots.add(ci); ci->state.skill = skill <= 0 ? rnd(50) + 51 : clamp(skill, 1, 101); clients.add(ci); ci->state.lasttimeplayed = lastmillis; copystring(ci->name, "bot", MAXNAMELEN+1); ci->state.state = CS_DEAD; copystring(ci->team, team, MAXTEAMLEN+1); ci->playermodel = rnd(128); ci->aireinit = 2; ci->connected = true; dorefresh = true; return true; } void deleteai(clientinfo *ci) { int cn = ci->clientnum - MAXCLIENTS; if(!bots.inrange(cn)) return; if(smode) smode->leavegame(ci, true); sendf(-1, 1, "ri2", N_CDIS, ci->clientnum); clientinfo *owner = (clientinfo *)getclientinfo(ci->ownernum); if(owner) owner->bots.removeobj(ci); clients.removeobj(ci); DELETEP(bots[cn]); dorefresh = true; } bool deleteai() { loopvrev(bots) if(bots[i] && bots[i]->ownernum >= 0) { deleteai(bots[i]); return true; } return false; } void reinitai(clientinfo *ci) { if(ci->ownernum < 0) deleteai(ci); else if(ci->aireinit >= 1) { sendf(-1, 1, "ri6ss", N_INITAI, ci->clientnum, ci->ownernum, ci->state.aitype, ci->state.skill, ci->playermodel, ci->name, ci->team); if(ci->aireinit == 2) { ci->reassign(); if(ci->state.state==CS_ALIVE) sendspawn(ci); else sendresume(ci); } ci->aireinit = 0; } } void shiftai(clientinfo *ci, clientinfo *owner) { clientinfo *prevowner = (clientinfo *)getclientinfo(ci->ownernum); if(prevowner) prevowner->bots.removeobj(ci); if(!owner) { ci->aireinit = 0; ci->ownernum = -1; } else { ci->aireinit = 2; ci->ownernum = owner->clientnum; owner->bots.add(ci); } dorefresh = true; } void removeai(clientinfo *ci) { // either schedules a removal, or someone else to assign to loopvrev(ci->bots) shiftai(ci->bots[i], findaiclient(ci)); } bool reassignai() { clientinfo *hi = NULL, *lo = NULL; loopv(clients) { clientinfo *ci = clients[i]; if(!validaiclient(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) { shiftai(hi->bots[i], lo); return true; } } return false; } void checksetup() { if(m_teammode && botbalance) balanceteams(); loopvrev(bots) if(bots[i]) reinitai(bots[i]); } void clearai() { // clear and remove all ai immediately loopvrev(bots) if(bots[i]) deleteai(bots[i]); } void checkai() { if(!dorefresh) return; dorefresh = false; if(m_botmode && numclients(-1, false, true)) { checksetup(); while(reassignai()); } else clearai(); } void reqadd(clientinfo *ci, int skill) { if(!ci->local && !ci->privilege) return; if(!addai(skill, !ci->local && ci->privilege < PRIV_ADMIN ? botlimit : -1)) sendf(ci->clientnum, 1, "ris", N_SERVMSG, "failed to create or assign bot"); } void reqdel(clientinfo *ci) { if(!ci->local && !ci->privilege) return; if(!deleteai()) sendf(ci->clientnum, 1, "ris", N_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.aitype == AI_NONE) dorefresh = true; } void changeteam(clientinfo *ci) { if(ci->state.aitype == AI_NONE) dorefresh = true; } } sandboxgamemaker-2.8.2+dfsg/src/fpsgame/server.cpp0000644000175000017500000030727712045412564021156 0ustar bofh80bofh80#include "game.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]); } } const char *gameident() { return "fps"; } } 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; 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 suicideevent : gameevent { void process(clientinfo *ci); }; struct pickupevent : gameevent { int ent; void process(clientinfo *ci); }; template struct projectilestate { int projs[N]; int numprojs; projectilestate() : numprojs(0) {} void reset() { numprojs = 0; } void add(int val) { if(numprojs>=N) numprojs = 0; projs[numprojs++] = val; } bool remove(int val) { loopi(numprojs) if(projs[i]==val) { projs[i] = projs[--numprojs]; return true; } return false; } }; struct gamestate : fpsstate { vec o; int state, editstate; int lastdeath, lastspawn, lifesequence; int lastshot; projectilestate<8> rockets, grenades; int frags, flags, deaths, teamkills, shotdamage, damage, tokens; int lasttimeplayed, timeplayed; float effectiveness; 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 gamemillis - lastshot >= gunwait; } void reset() { if(state!=CS_SPECTATOR) state = editstate = CS_DEAD; maxhealth = 100; rockets.reset(); grenades.reset(); timeplayed = 0; effectiveness = 0; frags = flags = deaths = teamkills = shotdamage = damage = tokens = 0; respawn(); } void respawn() { fpsstate::respawn(); o = vec(-1e10f, -1e10f, -1e10f); lastdeath = 0; lastspawn = -1; lastshot = 0; tokens = 0; } void reassign() { respawn(); rockets.reset(); grenades.reset(); } }; struct savedscore { uint ip; string name; int maxhealth, frags, flags, deaths, teamkills, shotdamage, damage; int timeplayed; float effectiveness; void save(gamestate &gs) { maxhealth = gs.maxhealth; frags = gs.frags; flags = gs.flags; deaths = gs.deaths; teamkills = gs.teamkills; shotdamage = gs.shotdamage; damage = gs.damage; timeplayed = gs.timeplayed; effectiveness = gs.effectiveness; } void restore(gamestate &gs) { if(gs.health==gs.maxhealth) gs.health = maxhealth; gs.maxhealth = maxhealth; gs.frags = frags; gs.flags = flags; gs.deaths = deaths; gs.teamkills = teamkills; gs.shotdamage = shotdamage; gs.damage = damage; gs.timeplayed = timeplayed; gs.effectiveness = effectiveness; } }; extern int gamemillis, nextexceeded; struct clientinfo { int clientnum, ownernum, connectmillis, sessionid, overflow; string name, team, mapvote; int playermodel; int modevote; int privilege; bool connected, local, timesync; int gameoffset, lastevent, pushed, exceeded; gamestate state; vector events; vector position, messages; int posoff, poslen, msgoff, msglen; vector bots; uint authreq; string authname; int ping, aireinit; string clientmap; int mapcrc; bool warned, gameclip; ENetPacket *getdemo, *getmap, *getcfg, *clipboard; int lastclipboard, needclipboard; clientinfo() : getdemo(NULL), getmap(NULL), getcfg(NULL), clipboard(NULL) { reset(); } ~clientinfo() { events.deletecontents(); cleanclipboard(); } void addevent(gameevent *e) { if(state.state==CS_SPECTATOR || events.length()>100) delete e; else events.add(e); } enum { PUSHMILLIS = 2500 }; int calcpushrange() { ENetPeer *peer = getclientpeer(ownernum); return PUSHMILLIS + (peer ? peer->roundTripTime + peer->roundTripTimeVariance : ENET_PEER_DEFAULT_ROUND_TRIP_TIME); } bool checkpushed(int millis, int range) { return millis >= pushed - range && millis <= pushed + range; } void scheduleexceeded() { if(state.state!=CS_ALIVE || !exceeded) return; int range = calcpushrange(); if(!nextexceeded || exceeded + range < nextexceeded) nextexceeded = exceeded + range; } void setexceeded() { if(state.state==CS_ALIVE && !exceeded && !checkpushed(gamemillis, calcpushrange())) exceeded = gamemillis; scheduleexceeded(); } void setpushed() { pushed = max(pushed, gamemillis); if(exceeded && checkpushed(exceeded, calcpushrange())) exceeded = 0; } bool checkexceeded() { return state.state==CS_ALIVE && exceeded && gamemillis > exceeded + calcpushrange(); } void mapchange() { mapvote[0] = 0; state.reset(); events.deletecontents(); overflow = 0; timesync = false; lastevent = 0; exceeded = 0; pushed = 0; clientmap[0] = '\0'; mapcrc = 0; warned = false; gameclip = false; } void reassign() { state.reassign(); events.deletecontents(); timesync = false; lastevent = 0; } void cleanclipboard(bool fullclean = true) { if(clipboard) { if(--clipboard->referenceCount <= 0) enet_packet_destroy(clipboard); clipboard = NULL; } if(fullclean) lastclipboard = 0; } void reset() { name[0] = team[0] = 0; playermodel = -1; privilege = PRIV_NONE; connected = local = false; authreq = 0; position.setsize(0); messages.setsize(0); ping = 0; aireinit = 0; needclipboard = 0; cleanclipboard(); 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 aiman { extern void removeai(clientinfo *ci); extern void clearai(); extern void checkai(); extern void reqadd(clientinfo *ci, int skill); extern void reqdel(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; }; vector demos; bool demonextmatch = false; stream *demotmp = NULL, *demorecord = NULL, *demoplayback = NULL; int nextplayback = 0, demomillis = 0; VAR(maxdemos, 0, 5, 25); VAR(maxdemosize, 0, 16, 64); VAR(restrictdemos, 0, 1, 1); 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; } uint mcrc = 0; vector ments; vector sents; vector scores; 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; } #ifndef STANDALONE ICOMMAND(modename, "i", (int *n), result(modename(*n, "unknown"))); #endif const char *mastermodename(int n, const char *unknown) { return (n>=MM_START && size_t(n-MM_START)clientnum!=exclude && (!nospec || ci->state.state!=CS_SPECTATOR || (priv && (ci->privilege || ci->local))) && (!noai || ci->state.aitype == AI_NONE)) 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.aitype == AI_NONE) return name; static string cname[3]; static int cidx = 0; cidx = (cidx+1)%3; formatstring(cname[cidx])(ci->state.aitype == AI_NONE ? "%s \fs\f5(%d)\fr" : "%s \fs\f5[%d]\fr", name, ci->clientnum); return cname[cidx]; } 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) { if(victim==actor || isteam(victim->team, actor->team)) return -1; return 1; } virtual void died(clientinfo *victim, clientinfo *actor) {} virtual bool canchangeteam(clientinfo *ci, const char *oldteam, const char *newteam) { return true; } 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 cleanup() {} virtual void setup() {} virtual void newmap() {} virtual void intermission() {} virtual bool hidefrags() { return false; } virtual int getteamscore(const char *team) { return 0; } virtual void getteamscores(vector &scores) {} virtual bool extinfoteam(const char *team, ucharbuf &p) { return false; } }; #define SERVMODE 1 #include "capture.h" #include "ctf.h" #include "collect.h" captureservmode capturemode; ctfservmode ctfmode; collectservmode collectmode; servmode *smode = NULL; bool canspawnitem(int type) { return !m_noitems && (type>=I_SHELLS && type<=I_QUAD && (!m_noammo || typeI_CARTRIDGES)); } 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: sec = 20; break; case I_YELLOWARMOUR: sec = 20 + rnd(6); break; case I_BOOST: case I_QUAD: sec = 40+rnd(40); break; } return sec*1000; } bool delayspawn(int type) { switch(type) { case I_GREENARMOUR: case I_YELLOWARMOUR: return !m_classicsp; case I_BOOST: case I_QUAD: return true; default: return false; } } bool pickup(int i, int sender) // server side item pickup, acknowledge first client that gets it { if((m_timed && gamemillis>=gamelimit) || !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", N_ITEMACC, i, sender); ci->state.pickup(sents[i].type); return true; } clientinfo *choosebestclient(float &bestrank) { clientinfo *best = NULL; bestrank = -1; loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.timeplayed<0) continue; float rank = ci->state.state!=CS_SPECTATOR ? ci->state.effectiveness/max(ci->state.timeplayed, 1) : -1; if(!best || rank > bestrank) { best = ci; bestrank = rank; } } return best; } void autoteam() { static const char *teamnames[2] = {"good", "evil"}; vector team[2]; float teamrank[2] = {0, 0}; for(int round = 0, remaining = clients.length(); remaining>=0; round++) { int first = round&1, second = (round+1)&1, selected = 0; while(teamrank[first] <= teamrank[second]) { float rank; clientinfo *ci = choosebestclient(rank); if(!ci) break; if(smode && smode->hidefrags()) rank = 1; else if(selected && rank<=0) break; ci->state.timeplayed = -1; team[first].add(ci); if(rank>0) teamrank[first] += rank; selected++; if(rank<=0) break; } if(!selected) break; remaining -= selected; } loopi(sizeof(team)/sizeof(team[0])) { loopvj(team[i]) { clientinfo *ci = team[i][j]; if(!strcmp(ci->team, teamnames[i])) continue; copystring(ci->team, teamnames[i], MAXTEAMLEN+1); sendf(-1, 1, "riisi", N_SETTEAM, ci->clientnum, teamnames[i], -1); } } } struct teamrank { const char *name; float rank; int clients; teamrank(const char *name) : name(name), rank(0), clients(0) {} }; const char *chooseworstteam(const char *suggest = NULL, clientinfo *exclude = NULL) { teamrank teamranks[2] = { teamrank("good"), teamrank("evil") }; const int numteams = sizeof(teamranks)/sizeof(teamranks[0]); loopv(clients) { clientinfo *ci = clients[i]; if(ci==exclude || ci->state.aitype!=AI_NONE || ci->state.state==CS_SPECTATOR || !ci->team[0]) continue; ci->state.timeplayed += lastmillis - ci->state.lasttimeplayed; ci->state.lasttimeplayed = lastmillis; loopj(numteams) if(!strcmp(ci->team, teamranks[j].name)) { teamrank &ts = teamranks[j]; ts.rank += ci->state.effectiveness/max(ci->state.timeplayed, 1); ts.clients++; break; } } teamrank *worst = &teamranks[numteams-1]; loopi(numteams-1) { teamrank &ts = teamranks[i]; if(smode && smode->hidefrags()) { if(ts.clients < worst->clients || (ts.clients == worst->clients && ts.rank < worst->rank)) worst = &ts; } else if(ts.rank < worst->rank || (ts.rank == worst->rank && ts.clients < worst->clients)) worst = &ts; } return worst->name; } void prunedemos(int extra = 0) { int n = clamp(demos.length() + extra - maxdemos, 0, demos.length()); if(n <= 0) return; loopi(n) delete[] demos[n].data; demos.remove(0, n); } void adddemo() { if(!demotmp) return; int len = (int)min(demotmp->size(), stream::offset((maxdemosize<<20) + 0x10000)); demofile &d = demos.add(); time_t t = time(NULL); char *timestr = ctime(&t), *trim = timestr + strlen(timestr); while(trim>timestr && iscubespace(*--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); } void enddemorecord() { if(!demorecord) return; DELETEP(demorecord); if(!demotmp) return; if(!maxdemos || !maxdemosize) { DELETEP(demotmp); return; } prunedemos(1); adddemo(); } 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); if(demorecord->rawtell() >= (maxdemosize<<20)) enddemorecord(); } void recordpacket(int chan, void *data, int len) { writedemo(chan, data, len); } 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, N_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); } } static void freegetmap(ENetPacket *packet) { loopv(clients) { clientinfo *ci = clients[i]; if(ci->getmap == packet) ci->getmap = NULL; } } static void freegetcfg(ENetPacket *packet) { loopv(clients) { clientinfo *ci = clients[i]; if(ci->getmap == packet) ci->getmap = NULL; } } static void freegetdemo(ENetPacket *packet) { loopv(clients) { clientinfo *ci = clients[i]; if(ci->getdemo == packet) ci->getdemo = NULL; } } void senddemo(clientinfo *ci, int num) { if(ci->getdemo) return; if(!num) num = demos.length(); if(!demos.inrange(num-1)) return; demofile &d = demos[num-1]; if((ci->getdemo = sendf(ci->clientnum, 2, "rim", N_SENDDEMO, d.len, d.data))) ci->getdemo->freeCallback = freegetdemo; } void enddemoplayback() { if(!demoplayback) return; DELETEP(demoplayback); loopv(clients) sendf(clients[i]->clientnum, 1, "ri3", N_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) break; 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", N_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) aiman::removeai(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", N_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; sendf(-1, 1, "ri4", N_CURRENTMASTER, currentmaster, currentmaster >= 0 ? ci->privilege : 0, mastermode); if(gamepaused) { int admins = 0; loopv(clients) if(clients[i]->privilege >= PRIV_ADMIN || clients[i]->local) admins++; if(!admins) pausegame(false); } } savedscore *findscore(clientinfo *ci, bool insert) { uint ip = getclientip(ci->clientnum); if(!ip && !ci->local) return 0; if(!insert) { loopv(clients) { clientinfo *oi = clients[i]; if(oi->clientnum != ci->clientnum && getclientip(oi->clientnum) == ip && !strcmp(oi->name, ci->name)) { oi->state.timeplayed += lastmillis - oi->state.lasttimeplayed; oi->state.lasttimeplayed = lastmillis; static savedscore curscore; curscore.save(oi->state); return &curscore; } } } loopv(scores) { savedscore &sc = scores[i]; if(sc.ip == ip && !strcmp(sc.name, ci->name)) return ≻ } if(!insert) return 0; savedscore &sc = scores.add(); sc.ip = ip; copystring(sc.name, ci->name); return ≻ } void savescore(clientinfo *ci) { savedscore *sc = findscore(ci, true); if(sc) sc->save(ci->state); } int checktype(int type, clientinfo *ci) { if(ci && ci->local) return type; // only allow edit messages in coop-edit mode if(type>=N_EDITENT && type<=N_EDITVAR && !m_edit) return -1; // server only messages static const int servtypes[] = { N_SERVINFO, N_INITCLIENT, N_WELCOME, N_MAPRELOAD, N_SERVMSG, N_DAMAGE, N_HITPUSH, N_SHOTFX, N_EXPLODEFX, N_DIED, N_SPAWNSTATE, N_FORCEDEATH, N_ITEMACC, N_ITEMSPAWN, N_TIMEUP, N_CDIS, N_CURRENTMASTER, N_PONG, N_RESUME, N_BASESCORE, N_BASEINFO, N_BASEREGEN, N_ANNOUNCE, N_SENDDEMOLIST, N_SENDDEMO, N_DEMOPLAYBACK, N_SENDMAP, N_SENDCFG, N_DROPFLAG, N_SCOREFLAG, N_RETURNFLAG, N_RESETFLAG, N_INVISFLAG, N_CLIENT, N_AUTHCHAL, N_INITAI, N_EXPIRETOKENS, N_DROPTOKENS }; if(ci) { loopi(sizeof(servtypes)/sizeof(int)) if(type == servtypes[i]) return -1; if(type < N_EDITENT || type > N_EDITVAR || !m_edit) { if(type != N_POS && ++ci->overflow >= 200) return -2; } } 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 flushclientposition(clientinfo &ci) { if(ci.position.empty() || (!hasnonlocalclients() && !demorecord)) return; packetbuf p(ci.position.length(), 0); p.put(ci.position.getbuf(), ci.position.length()); ci.position.setsize(0); sendpacket(-1, 0, p.finalize(), ci.ownernum); } void addclientstate(worldstate &ws, clientinfo &ci) { if(ci.position.empty()) ci.posoff = -1; else { ci.posoff = ws.positions.length(); ws.positions.put(ci.position.getbuf(), ci.position.length()); ci.poslen = ws.positions.length() - ci.posoff; ci.position.setsize(0); } if(ci.messages.empty()) ci.msgoff = -1; else { ci.msgoff = ws.messages.length(); putint(ws.messages, N_CLIENT); putint(ws.messages, ci.clientnum); putuint(ws.messages, ci.messages.length()); ws.messages.put(ci.messages.getbuf(), ci.messages.length()); 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.aitype != AI_NONE) continue; ci.overflow = 0; 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); ucharbuf p = ws.positions.reserve(psize); p.put(ws.positions.getbuf(), psize); ws.positions.addbuf(p); } if(msize) { recordpacket(1, ws.messages.getbuf(), msize); ucharbuf p = ws.messages.reserve(msize); p.put(ws.messages.getbuf(), msize); ws.messages.addbuf(p); } ws.uses = 0; if(psize || msize) loopv(clients) { clientinfo &ci = *clients[i]; if(ci.state.aitype != AI_NONE) 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) { putint(p, gs.lifesequence); putint(p, gs.health); putint(p, gs.maxhealth); putint(p, gs.armour); putint(p, gs.armourtype); putint(p, gs.gunselect); loopi(GUN_PISTOL-GUN_SG+1) putint(p, gs.ammo[GUN_SG+i]); } void spawnstate(clientinfo *ci) { gamestate &gs = ci->state; gs.spawnstate(gamemode); gs.lifesequence = (gs.lifesequence + 1)&0x7F; } void sendspawn(clientinfo *ci) { gamestate &gs = ci->state; spawnstate(ci); sendf(ci->ownernum, 1, "rii7v", N_SPAWNSTATE, ci->clientnum, gs.lifesequence, gs.health, gs.maxhealth, gs.armour, gs.armourtype, gs.gunselect, GUN_PISTOL-GUN_SG+1, &gs.ammo[GUN_SG]); 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()); } void putinitclient(clientinfo *ci, packetbuf &p) { if(ci->state.aitype != AI_NONE) { putint(p, N_INITAI); putint(p, ci->clientnum); putint(p, ci->ownernum); putint(p, ci->state.aitype); putint(p, ci->state.skill); putint(p, ci->playermodel); sendstring(ci->name, p); sendstring(ci->team, p); } else { putint(p, N_INITCLIENT); putint(p, ci->clientnum); sendstring(ci->name, p); sendstring(ci->team, p); putint(p, ci->playermodel); } } void welcomeinitclient(packetbuf &p, int exclude = -1) { loopv(clients) { clientinfo *ci = clients[i]; if(!ci->connected || ci->clientnum == exclude) continue; putinitclient(ci, p); } } int welcomepacket(packetbuf &p, clientinfo *ci) { int hasmap = (m_edit && (clients.length()>1 || (ci && ci->local))) || (smapname[0] && (!m_timed || gamemillisstate.state==CS_SPECTATOR && !ci->privilege && !ci->local) || numclients(ci ? ci->clientnum : -1, true, true, true))); putint(p, N_WELCOME); putint(p, hasmap); if(hasmap) { putint(p, N_MAPCHANGE); sendstring(smapname, p); putint(p, gamemode); putint(p, notgotitems ? 1 : 0); if(!ci || (m_timed && smapname[0])) { putint(p, N_TIMEUP); putint(p, gamemillis < gamelimit && !interm ? max((gamelimit - gamemillis)/1000, 1) : 0); } if(!notgotitems) { putint(p, N_ITEMLIST); loopv(sents) if(sents[i].spawned) { putint(p, i); putint(p, sents[i].type); } putint(p, -1); } } if(currentmaster >= 0 || mastermode != MM_OPEN) { putint(p, N_CURRENTMASTER); putint(p, currentmaster); clientinfo *m = currentmaster >= 0 ? getinfo(currentmaster) : NULL; putint(p, m ? m->privilege : 0); putint(p, mastermode); } if(gamepaused) { putint(p, N_PAUSEGAME); putint(p, 1); } if(ci) { putint(p, N_SETTEAM); putint(p, ci->clientnum); sendstring(ci->team, p); 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, N_FORCEDEATH); putint(p, ci->clientnum); sendf(-1, 1, "ri2x", N_FORCEDEATH, ci->clientnum, ci->clientnum); } else { gamestate &gs = ci->state; spawnstate(ci); putint(p, N_SPAWNSTATE); putint(p, ci->clientnum); sendstate(gs, p); gs.lastspawn = gamemillis; } } if(ci && ci->state.state==CS_SPECTATOR) { putint(p, N_SPECTATOR); putint(p, ci->clientnum); putint(p, 1); sendf(-1, 1, "ri3x", N_SPECTATOR, ci->clientnum, 1, ci->clientnum); } if(!ci || clients.length()>1) { putint(p, N_RESUME); loopv(clients) { clientinfo *oi = clients[i]; 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.flags); putint(p, oi->state.quadmillis); sendstate(oi->state, p); } putint(p, -1); welcomeinitclient(p, ci ? ci->clientnum : -1); } if(smode) smode->initclient(ci, p, true); return 1; } bool restorescore(clientinfo *ci) { //if(ci->local) return false; savedscore *sc = findscore(ci, false); if(sc) { sc->restore(ci->state); return true; } return false; } void sendresume(clientinfo *ci) { gamestate &gs = ci->state; sendf(-1, 1, "ri3i9vi", N_RESUME, ci->clientnum, gs.state, gs.frags, gs.flags, 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 loaditems() { resetitems(); notgotitems = true; if(m_edit || !loadents(smapname, ments, &mcrc)) return; loopv(ments) if(canspawnitem(ments[i].type)) { server_entity se = { NOTUSED, 0, false }; while(sents.length()<=i) sents.add(se); sents[i].type = ments[i].type; if(m_mp(gamemode) && delayspawn(sents[i].type)) sents[i].spawntime = spawntime(sents[i].type); else sents[i].spawned = true; } notgotitems = false; } void changemap(const char *s, int mode) { stopdemo(); pausegame(false); if(smode) smode->cleanup(); aiman::clearai(); mapreload = false; gamemode = mode; gamemillis = 0; gamelimit = (m_overtime ? 15 : 10)*60000; interm = 0; nextexceeded = 0; copystring(smapname, s); loaditems(); scores.shrink(0); 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 if(m_collect) smode = &collectmode; else smode = NULL; if(m_timed && smapname[0]) sendf(-1, 1, "ri2", N_TIMEUP, gamemillis < gamelimit && !interm ? max((gamelimit - gamemillis)/1000, 1) : 0); loopv(clients) { clientinfo *ci = clients[i]; ci->mapchange(); ci->state.lasttimeplayed = lastmillis; if(m_mp(gamemode) && ci->state.state!=CS_SPECTATOR) sendspawn(ci); } aiman::changemap(); if(m_demo) { if(clients.length()) setupdemoplayback(); } else if(demonextmatch) { demonextmatch = false; setupdemorecord(); } if(smode) smode->setup(); } 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.aitype!=AI_NONE) 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", N_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", N_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", N_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", N_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(gamemillis >= gamelimit && !interm) { sendf(-1, 1, "ri2", N_TIMEUP, 0); if(smode) smode->intermission(); 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); if(target!=actor && !isteam(target->team, actor->team)) actor->state.damage += damage; sendf(-1, 1, "ri6", N_DAMAGE, target->clientnum, actor->clientnum, damage, ts.armour, ts.health); if(target==actor) target->setpushed(); else if(!hitpush.iszero()) { ivec v = vec(hitpush).rescale(DNF); sendf(ts.health<=0 ? -1 : target->ownernum, 1, "ri7", N_HITPUSH, target->clientnum, gun, damage, v.x, v.y, v.z); target->setpushed(); } 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); 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; } actor->state.effectiveness += fragvalue*friends/float(max(enemies, 1)); } sendf(-1, 1, "ri4", N_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 suicide(clientinfo *ci) { gamestate &gs = ci->state; if(gs.state!=CS_ALIVE) return; ci->state.frags += smode ? smode->fragvalue(ci, ci) : -1; ci->state.deaths++; sendf(-1, 1, "ri4", N_DIED, ci->clientnum, ci->clientnum, gs.frags); ci->position.setsize(0); if(smode) smode->died(ci, NULL); gs.state = CS_DEAD; gs.respawn(); } void suicideevent::process(clientinfo *ci) { suicide(ci); } 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; } sendf(-1, 1, "ri4x", N_EXPLODEFX, ci->clientnum, gun, id, ci->ownernum); 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 || (guns[gun].range && from.dist(to) > guns[gun].range + 1)) return; if(gun!=GUN_FIST) gs.ammo[gun]--; gs.lastshot = millis; gs.gunwait = guns[gun].attackdelay; sendf(-1, 1, "rii9x", N_SHOTFX, ci->clientnum, gun, id, 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 || h.dist > guns[gun].range + 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 && (!m_timed || gamemillis < gamelimit)) { 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", N_ITEMSPAWN, i); } else if(sents[i].spawntime<=10000 && oldtime>10000 && (sents[i].type==I_QUAD || sents[i].type==I_BOOST)) { sendf(-1, 1, "ri2", N_ANNOUNCE, sents[i].type); } } } aiman::checkai(); 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(nextexceeded && gamemillis > nextexceeded && (!m_timed || gamemillis < gamelimit)) { nextexceeded = 0; loopvrev(clients) { clientinfo &c = *clients[i]; if(c.state.aitype != AI_NONE) continue; if(c.checkexceeded()) disconnect_client(c.clientnum, DISC_TAGT); else c.scheduleexceeded(); } } if(!gamepaused && m_timed && smapname[0] && gamemillis-curtime>0) checkintermission(); if(interm > 0 && gamemillis>interm) { if(demorecord) enddemorecord(); interm = -1; checkvotes(true); } } struct crcinfo { int crc, matches; crcinfo() {} crcinfo(int crc, int matches) : crc(crc), matches(matches) {} static bool compare(const crcinfo &x, const crcinfo &y) { return x.matches > y.matches; } }; void checkmaps(int req = -1) { if(m_edit || !smapname[0]) return; vector crcs; int total = 0, unsent = 0, invalid = 0; if(mcrc) crcs.add(crcinfo(mcrc, clients.length() + 1)); loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_SPECTATOR || ci->state.aitype != AI_NONE) 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(!mcrc && 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.aitype != AI_NONE || 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", N_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.aitype != AI_NONE || !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", N_SERVMSG, msg); if(req < 0) ci->warned = true; } } } void sendservinfo(clientinfo *ci) { sendf(ci->clientnum, 1, "ri5s", N_SERVINFO, ci->clientnum, PROTOCOL_VERSION, ci->sessionid, serverpass[0] ? 1 : 0, serverdesc); } void noclients() { bannedips.shrink(0); aiman::clearai(); } 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", N_CDIS, n); clients.removeobj(ci); aiman::removeai(ci); if(!numclients(-1, false, true)) noclients(); // bans clear when server empties } else connects.removeobj(ci); } int reserveclients() { return 3; } struct gbaninfo { enet_uint32 ip, mask; }; vector gbans; void cleargbans() { gbans.shrink(0); } bool checkgban(uint ip) { loopv(gbans) if((ip & gbans[i].mask) == gbans[i].ip) return true; return false; } void addgban(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++ != '.'); } gbaninfo &ban = gbans.add(); ban.ip = ip.i; ban.mask = mask.i; loopvrev(clients) { clientinfo *ci = clients[i]; if(ci->local || ci->privilege >= PRIV_ADMIN) continue; if(checkgban(getclientip(ci->clientnum))) disconnect_client(ci->clientnum, DISC_IPBAN); } } 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(checkgban(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", N_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", N_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", N_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); else if(!strncmp(cmd, "cleargbans", cmdlen)) cleargbans(); else if(sscanf(cmd, "addgban %s", val) == 1) addgban(val); } void receivefile(int sender, uchar *data, int len) { if(!m_edit || len > 4*1024*1024) return; clientinfo *ci = getinfo(sender); if(ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) return; ucharbuf p(data, len); int type = getint(p); data += p.len; len -= p.len; switch(type) { case N_UPLOADCFG: DELETEP(cfgdata); if(!len) return; cfgdata = opentempfile("cfgdata", "w+b"); if(!cfgdata) { sendf(sender, 1, "ris", N_SERVMSG, "failed to open temporary file for cfg"); return; } cfgdata->write(data, len); sendf(sender, 1, "ris", N_SERVMSG, "received cfg file"); break; case N_UPLOADMAP: DELETEP(mapdata); if(!len) return; mapdata = opentempfile("mapdata", "w+b"); if(!mapdata) { sendf(sender, 1, "ris", N_SERVMSG, "failed to open temporary file for map"); return; } mapdata->write(data, len); defformatstring(msg)("[%s uploaded map to server, \"/getmap\" to receive it]", colorname(ci)); sendservmsg(msg); break; } } void sendclipboard(clientinfo *ci) { if(!ci->lastclipboard || !ci->clipboard) return; bool flushed = false; loopv(clients) { clientinfo &e = *clients[i]; if(e.clientnum != ci->clientnum && e.needclipboard - ci->lastclipboard >= 0) { if(!flushed) { flushserver(true); flushed = true; } sendpacket(e.clientnum, 1, ci->clipboard); } } } void parsepacket(int sender, int chan, packetbuf &p) // has to parse exactly each byte of the packet { if(sender<0 || p.packet->flags&ENET_PACKET_FLAG_UNSEQUENCED) 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)!=N_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; ci->needclipboard = totalmillis ? totalmillis : 1; if(mastermode>=MM_LOCKED) ci->state.state = CS_SPECTATOR; ci->state.lasttimeplayed = lastmillis; const char *worst = m_teammode ? chooseworstteam(NULL, ci) : NULL; copystring(ci->team, worst ? worst : "good", MAXTEAMLEN+1); sendwelcome(ci); if(restorescore(ci)) sendresume(ci); sendinitclient(ci); aiman::addclient(ci); if(m_demo) setupdemoplayback(); if(servermotd[0]) sendf(sender, 1, "ris", N_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(body) { \ if(cm && (!cm->local || demorecord || hasnonlocalclients())) \ { \ curmsg = p.length(); \ { body; } \ } \ } #define QUEUE_INT(n) QUEUE_BUF(putint(cm->messages, n)) #define QUEUE_UINT(n) QUEUE_BUF(putuint(cm->messages, n)) #define QUEUE_STR(text) QUEUE_BUF(sendstring(text, cm->messages)) int curmsg; while((curmsg = p.length()) < p.maxlen) switch(type = checktype(getint(p), ci)) { case N_POS: { int pcn = getuint(p); p.get(); uint flags = getuint(p); clientinfo *cp = getinfo(pcn); if(cp && pcn != sender && cp->ownernum != sender) cp = NULL; vec pos; loopk(3) { int n = p.get(); n |= p.get()<<8; if(flags&(1<local || demorecord || hasnonlocalclients()) && (cp->state.state==CS_ALIVE || cp->state.state==CS_EDITING)) { //if(!ci->local && !m_edit && max(vel.magnitude2(), (float)fabs(vel.z)) >= 180) // PAS - don't enforce speeds, we allow per map configuration and this conflicts //cp->setexceeded(); cp->position.setsize(0); while(curmsgposition.add(p.buf[curmsg++]); } if(smode && cp->state.state==CS_ALIVE) smode->moved(cp, cp->state.o, cp->gameclip, pos, (flags&0x80)!=0); cp->state.o = pos; cp->gameclip = (flags&0x80)!=0; } break; } case N_TELEPORT: { int pcn = getint(p), teleport = getint(p), teledest = getint(p); clientinfo *cp = getinfo(pcn); if(cp && pcn != sender && cp->ownernum != sender) cp = NULL; if(cp && (!ci->local || demorecord || hasnonlocalclients()) && (cp->state.state==CS_ALIVE || cp->state.state==CS_EDITING)) { flushclientposition(*cp); sendf(-1, 0, "ri4x", N_TELEPORT, pcn, teleport, teledest, cp->ownernum); } break; } case N_JUMPPAD: { int pcn = getint(p), jumppad = getint(p); clientinfo *cp = getinfo(pcn); if(cp && pcn != sender && cp->ownernum != sender) cp = NULL; if(cp && (!ci->local || demorecord || hasnonlocalclients()) && (cp->state.state==CS_ALIVE || cp->state.state==CS_EDITING)) { cp->setpushed(); flushclientposition(*cp); sendf(-1, 0, "ri3x", N_JUMPPAD, pcn, jumppad, cp->ownernum); } break; } case N_FROMAI: { int qcn = getint(p); if(qcn < 0) cq = ci; else { cq = getinfo(qcn); if(cq && qcn != sender && cq->ownernum != sender) cq = NULL; } break; } case N_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); ci->state.rockets.reset(); ci->state.grenades.reset(); } else ci->state.state = ci->state.editstate; QUEUE_MSG; break; } case N_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 N_CHECKMAPS: checkmaps(sender); break; case N_TRYSPAWN: if(!ci || !cq || cq->state.state!=CS_DEAD || cq->state.lastspawn>=0 || (smode && !smode->canspawn(cq))) break; if(!ci->clientmap[0] && !ci->mapcrc) { ci->mapcrc = -1; checkmaps(); } if(cq->state.lastdeath) { flushevents(cq, cq->state.lastdeath + DEATHMILLIS); cq->state.respawn(); } cleartimedevents(cq); sendspawn(cq); break; case N_GUNSELECT: { int gunselect = getint(p); if(!cq || cq->state.state!=CS_ALIVE) break; cq->state.gunselect = gunselect >= GUN_FIST && gunselect <= GUN_PISTOL ? gunselect : GUN_FIST; QUEUE_AI; QUEUE_MSG; break; } case N_SPAWN: { int ls = getint(p), gunselect = getint(p); if(!cq || (cq->state.state!=CS_ALIVE && cq->state.state!=CS_DEAD) || ls!=cq->state.lifesequence || cq->state.lastspawn<0) break; cq->state.lastspawn = -1; cq->state.state = CS_ALIVE; cq->state.gunselect = gunselect >= GUN_FIST && gunselect <= GUN_PISTOL ? gunselect : GUN_FIST; cq->exceeded = 0; if(smode) smode->spawned(cq); QUEUE_AI; QUEUE_BUF({ putint(cm->messages, N_SPAWN); sendstate(cq->state, cm->messages); }); break; } case N_SUICIDE: { if(cq) cq->addevent(new suicideevent); break; } case N_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.dist = getint(p)/DMF; hit.rays = getint(p); loopk(3) hit.dir[k] = getint(p)/DNF; } if(cq) { cq->addevent(shot); cq->setpushed(); } else delete shot; break; } case N_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; hit.rays = getint(p); loopk(3) hit.dir[k] = getint(p)/DNF; } if(cq) cq->addevent(exp); else delete exp; break; } case N_ITEMPICKUP: { int n = getint(p); if(!cq) break; pickupevent *pickup = new pickupevent; pickup->ent = n; cq->addevent(pickup); break; } case N_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) || !m_teammode || !cq->team[0]) break; loopv(clients) { clientinfo *t = clients[i]; if(t==cq || t->state.state==CS_SPECTATOR || t->state.aitype != AI_NONE || strcmp(cq->team, t->team)) continue; sendf(t->clientnum, 1, "riiis", N_TEXT, cq->clientnum, mtype, text); } if(mtype&CHAT_EMOTE) { print("(%s) *%s(%i) %s", ci->team, colorname(ci), ci->clientnum, text); } else print("(%s) <%s(%i)> %s", ci->team, colorname(ci), ci->clientnum, text); } else //it would probably be TEXT... otherwise { loopv(clients) { clientinfo *t = clients[i]; if(t==ci || t->state.aitype != AI_NONE) continue; sendf(t->clientnum, 1, "riiis", N_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 N_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 N_SWITCHMODEL: { ci->playermodel = getint(p); QUEUE_MSG; break; } case N_SWITCHTEAM: { getstring(text, p); filtertext(text, text, false, MAXTEAMLEN); if(strcmp(ci->team, text) && m_teammode && (!smode || smode->canchangeteam(ci, ci->team, text))) { if(ci->state.state==CS_ALIVE) suicide(ci); copystring(ci->team, text); aiman::changeteam(ci); sendf(-1, 1, "riisi", N_SETTEAM, sender, ci->team, ci->state.state==CS_SPECTATOR ? -1 : 0); print("%s(%i) changed teams to %s", ci->name, ci->clientnum, ci->team); } break; } case N_MAPVOTE: case N_MAPCHANGE: { getstring(text, p); filtertext(text, text, false); int reqmode = getint(p); print("%s(%i) voted for \"%s\" on \"%s\"", ci->name, ci->clientnum, modename(reqmode, "unknown"), text); if(type!=N_MAPVOTE && !mapreload) break; vote(text, reqmode, sender); break; } case N_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) 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 N_PING: sendf(sender, 1, "i2", N_PONG, getint(p)); break; case N_CLIENTPING: { int ping = getint(p); if(ci) { ci->ping = ping; loopv(ci->bots) ci->bots[i]->ping = ping; } QUEUE_MSG; break; } case N_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); sendf(-1, 1, "rii", N_MASTERMODE, mastermode); //sendservmsg(s); } else { defformatstring(s)("mastermode %d is disabled on this server", mm); sendf(sender, 1, "ris", N_SERVMSG, s); } } break; } case N_CLEARBANS: { if(ci->privilege || ci->local) { bannedips.shrink(0); sendservmsg("cleared all bans"); print("%s(%i) cleared bans", ci->name, ci->clientnum); } break; } case N_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 N_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) aiman::removeai(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; aiman::addclient(spinfo); if(spinfo->clientmap[0] || spinfo->mapcrc) checkmaps(); sendf(-1, 1, "ri", N_MAPRELOAD); 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", N_SPECTATOR, spectator, val); if(!val && mapreload && !spinfo->privilege && !spinfo->local) sendf(spectator, 1, "ri", N_MAPRELOAD); break; } case N_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(wi->state.state==CS_ALIVE) suicide(wi); 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); } } aiman::changeteam(wi); sendf(-1, 1, "riisi", N_SETTEAM, who, wi->team, 1); break; } case N_FORCEINTERMISSION: if(ci->local && !hasnonlocalclients()) startintermission(); break; case N_RECORDDEMO: { int val = getint(p); if(ci->privilege < (restrictdemos ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break; if(!maxdemos || !maxdemosize) { sendf(ci->clientnum, 1, "ris", N_SERVMSG, "the server has disabled demo recording"); break; } demonextmatch = val!=0; defformatstring(msg)("demo recording is %s for next match", demonextmatch ? "enabled" : "disabled"); sendservmsg(msg); break; } case N_STOPDEMO: { if(ci->privilege < (restrictdemos ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break; stopdemo(); break; } case N_CLEARDEMOS: { int demo = getint(p); if(ci->privilege < (restrictdemos ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break; cleardemos(demo); break; } case N_LISTDEMOS: if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break; listdemos(sender); break; case N_GETDEMO: { int n = getint(p); if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break; senddemo(ci, n); break; } case N_GETMAP: if(!mapdata || !cfgdata) sendf(sender, 1, "ris", N_SERVMSG, "no map to send"); else if(ci->getmap || ci->getcfg) sendf(sender, 1, "ris", N_SERVMSG, "already sending map"); else { sendf(sender, 1, "ris", N_SERVMSG, "server sending map..."); if((ci->getcfg = sendfile(sender, 2, cfgdata, "ri", N_SENDCFG))) ci->getcfg->freeCallback = freegetcfg; if((ci->getmap = sendfile(sender, 2, mapdata, "ri", N_SENDMAP))) ci->getmap->freeCallback = freegetmap; ci->needclipboard = totalmillis ? totalmillis : 1; } break; case N_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->newmap(); } QUEUE_MSG; break; } case N_SETMASTER: { int val = getint(p); getstring(text, p); setmaster(ci, val!=0, text); // don't broadcast the master password break; } case N_ADDBOT: { aiman::reqadd(ci, getint(p)); break; } case N_DELBOT: { aiman::reqdel(ci); break; } case N_BOTLIMIT: { int limit = getint(p); if(ci) aiman::setbotlimit(ci, limit); break; } case N_BOTBALANCE: { int balance = getint(p); if(ci) aiman::setbotbalance(ci, balance!=0); break; } case N_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 N_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 N_PAUSEGAME: { int val = getint(p); if(ci->privilegelocal) break; pausegame(val > 0); break; } case N_TEXTUREREQUEST: { getstring(text, p); getint(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", N_SERVMSG, texmsg); sendfile(sender, 2, file, "risi", N_SENDTEXTURE, text, slot); } else { defformatstring(err)("server - texture: %s not found", text); sendf(sender, 1, "ris", N_SERVMSG, err); } */ break; } //__offtools__ attachments: attach stuff case N_ATTACH: { QUEUE_MSG; int part = getint(p); getstring(text, p); int animrule = getint(p); QUEUE_INT(part); QUEUE_STR(text); QUEUE_INT(animrule); break; } //__offtools__ attachments: detach stuff case N_DETACH: { QUEUE_MSG; int part = getint(p); QUEUE_INT(part); break; } case N_COPY: ci->cleanclipboard(); ci->lastclipboard = totalmillis ? totalmillis : 1; goto genericmsg; case N_PASTE: if(ci->state.state!=CS_SPECTATOR) sendclipboard(ci); goto genericmsg; case N_CLIPBOARD: { int unpacklen = getint(p), packlen = getint(p); ci->cleanclipboard(false); if(ci->state.state==CS_SPECTATOR) { if(packlen > 0) p.subbuf(packlen); break; } if(packlen <= 0 || packlen > (1<<16) || unpacklen <= 0) { if(packlen > 0) p.subbuf(packlen); packlen = unpacklen = 0; } packetbuf q(32 + packlen, ENET_PACKET_FLAG_RELIABLE); putint(q, N_CLIPBOARD); putint(q, ci->clientnum); putint(q, unpacklen); putint(q, packlen); if(packlen > 0) p.get(q.subbuf(packlen).buf, packlen); ci->clipboard = q.finalize(); ci->clipboard->referenceCount++; break; } case N_SERVCMD: getstring(text, p); break; #define PARSEMESSAGES 1 #include "capture.h" #include "ctf.h" #include "collect.h" #undef PARSEMESSAGES case -1: disconnect_client(sender, DISC_TAGT); return; case -2: disconnect_client(sender, DISC_OVERFLOW); return; default: genericmsg: { int size = server::msgsizelookup(type); if(size<=0) {disconnect_client(sender, DISC_TAGT); return; } loopi(size-1) getint(p); if(ci && cq && (ci != cq || ci->state.state!=CS_SPECTATOR)) { QUEUE_AI; QUEUE_MSG; } break; } } } int laninfoport() { return SANDBOX_LANINFO_PORT; } int serverinfoport(int servport) { return servport < 0 ? SANDBOX_SERVINFO_PORT : servport+1; } int serverport(int infoport) { return infoport < 0 ? SANDBOX_SERVER_PORT : infoport-1; } const char *defaultmaster() { return "master.sandboxgamemaker.com"; } int masterport() { return SANDBOX_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); // generic attributes, passed back below putint(p, gamemode); putint(p, max((gamelimit - gamemillis)/1000, 0)); 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 "aiman.h" } sandboxgamemaker-2.8.2+dfsg/src/engine/0000755000175000017500000000000012076771136016756 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/src/engine/lightning.h0000644000175000017500000000744012045412564021110 0ustar bofh80bofh80#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.8.2+dfsg/src/engine/octarender.cpp0000644000175000017500000016234112045412564021610 0ustar bofh80bofh80// 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.8.2+dfsg/src/engine/rendermodel.cpp0000644000175000017500000007504012053622410021751 0ustar bofh80bofh80#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] : 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) { conoutf(CON_WARN, "unable to load model: packages/models/%s", name); 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(15) { const vec2 &sc = sincos360[i*(360/15)]; vec p(xradius*sc.x, yradius*sc.y, 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 || iscubespace(*s)) break; do s++; while(*s && !iscubespace(*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(game::numanims()) if(matchanim(game::animname(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 VARF(animoverride, -1, 0, 0x7F, if(animoverride > 0) animoverride %= game::numanims()); 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(physent *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.8.2+dfsg/src/engine/md2.h0000644000175000017500000003667012045412564017616 0ustar bofh80bofh80struct 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.8.2+dfsg/src/engine/texture.cpp0000644000175000017500000031612212045412564021160 0ustar bofh80bofh80// 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; } } static bool alphaformat(GLenum format) { switch(format) { case GL_ALPHA: case GL_LUMINANCE_ALPHA: case GL_RGBA: return true; default: return false; } } 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; } GLenum format; if(s.compressed) { format = uncompressedformat(s.compressed); t->bpp = formatsize(format); t->type |= Texture::COMPRESSED; } else { format = texformat(s.bpp); t->bpp = s.bpp; } if(alphaformat(format)) t->type |= Texture::ALPHA; 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 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, int margin) { 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; src += margin*(stride + bpp); for(int y = margin; y < h-margin; y++) { for(int x = margin; x < w-margin; x++) { int dr = 0, dg = 0, db = 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) { dr += p[0] * a; dg += p[1] * a; db += p[2] * a; a = 0; } p += bpp; } a += m[-1]; if(x >= 1) { dr += p[0] * a; dg += p[1] * a; db += p[2] * a; a = 0; } p += bpp; int cr = p[0], cg = p[1], cb = p[2]; a += m[0]; dr += cr * a; dg += cg * a; db += cb * a; p += bpp; if(x+1 < w) { cr = p[0]; cg = p[1]; cb = p[2]; } dr += cr * m[1]; dg += cg * m[1]; db += cb * m[1]; p += bpp; if(n > 1) { if(x+2 < w) { cr = p[0]; cg = p[1]; cb = p[2]; } dr += cr * m[2]; dg += cg * m[2]; db += cb * 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) { dr += p[0] * a; dg += p[1] * a; db += p[2] * a; a = 0; } p += bpp; } a += m[-1]; if(x >= 1) { dr += p[0] * a; dg += p[1] * a; db += p[2] * a; a = 0; } p += bpp; int cr = p[0], cg = p[1], cb = p[2]; a += m[0]; dr += cr * a; dg += cg * a; db += cb * a; p += bpp; if(x+1 < w) { cr = p[0]; cg = p[1]; cb = p[2]; } dr += cr * m[1]; dg += cg * m[1]; db += cb * m[1]; p += bpp; if(n > 1) { if(x+2 < w) { cr = p[0]; cg = p[1]; cb = p[2]; } dr += cr * m[2]; dg += cg * m[2]; db += cb * m[2]; p += bpp; } } if(normals) { vec v(dr-0x7F80, dg-0x7F80, db-0x7F80); float mag = 127.5f/v.magnitude(); dst[0] = uchar(v.x*mag + 127.5f); dst[1] = uchar(v.y*mag + 127.5f); dst[2] = uchar(v.z*mag + 127.5f); } else { dst[0] = dr>>8; dst[1] = dg>>8; dst[2] = db>>8; } if(bpp > 3) dst[3] = src[3]; dst += bpp; src += bpp; } src += 2*margin*bpp; } } void blurtexture(int n, int bpp, int w, int h, uchar *dst, const uchar *src, int margin) { switch((clamp(n, 1, 2)<<4) | bpp) { case 0x13: blurtexture<1, 3, false>(w, h, dst, src, margin); break; case 0x23: blurtexture<2, 3, false>(w, h, dst, src, margin); break; case 0x14: blurtexture<1, 4, false>(w, h, dst, src, margin); break; case 0x24: blurtexture<2, 4, false>(w, h, dst, src, margin); break; } } void blurnormals(int n, int w, int h, bvec *dst, const bvec *src, int margin) { switch(clamp(n, 1, 2)) { case 1: blurtexture<1, 3, true>(w, h, dst->v, src->v, margin); break; case 2: blurtexture<2, 3, true>(w, h, dst->v, src->v, margin); 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->type&(Texture::ALPHA|Texture::COMPRESSED)) != Texture::ALPHA) return; ImageData s; if(!texturedata(s, t->name, NULL, false) || !s.data || 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); 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(s.compressed ? s.compressed!=surface[0].compressed || s.w!=surface[0].w || s.h!=surface[0].h || s.levels!=surface[0].levels : surface[0].compressed || s.bpp!=surface[0].bpp) { 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->type = Texture::CUBEMAP; if(transient) t->type |= Texture::TRANSIENT; GLenum format; if(surface[0].compressed) { format = uncompressedformat(surface[0].compressed); t->bpp = formatsize(format); t->type |= Texture::COMPRESSED; } else { format = texformat(surface[0].bpp); t->bpp = surface[0].bpp; } if(alphaformat(format)) t->type |= Texture::ALPHA; t->mipmap = mipit; t->clamp = 3; 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 = format; if(!surface[0].compressed) { 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< texsize) { scaletexture(src, rendersize, rendersize, 3, 3*rendersize, dst, texsize, texsize); swap(src, dst); } if(blur > 0) { blurtexture(blur, 3, texsize, texsize, src, dst); swap(src, dst); } createtexture(tex, texsize, texsize, src, 3, 2, GL_RGB5, side.target); } glFrontFace(GL_CW); delete[] pixels; 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 ? min(em.size, envmapsize) : 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.8.2+dfsg/src/engine/world.h0000644000175000017500000000311412045412564020246 0ustar bofh80bofh80 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.8.2+dfsg/src/engine/octa.cpp0000644000175000017500000015265712045412564020421 0ustar bofh80bofh80// 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.material = MAT_AIR; 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) loopi(numtexs) if(texs[i] == tex) return tex; texs[numtexs++] = tex; } loopirev(numtexs) if(!i || texs[i] > DEFAULT_SKY) return texs[i]; 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); } static int midedge(const ivec &a, const ivec &b, int xd, int yd, bool &perfect) { int ax = a[xd], ay = a[yd], bx = b[xd], 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); } static inline bool crosscenter(const ivec &a, const ivec &b, int xd, int yd) { int ax = a[xd], ay = a[yd], bx = b[xd], by = b[yd]; return (((ax <= 8 && bx <= 8) || (ax >= 8 && bx >= 8)) && ((ay <= 8 && by <= 8) || (ay >= 8 && by >= 8))) || (ax + bx == 16 && ay + by == 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 || crosscenter(v00, v11, C[d], R[d])); } else { e[1][1] = c2; perfect = p2 && (c1 == c2 || crosscenter(v01, v10, C[d], R[d])); } 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, bool solid = false) { 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[dim] = solid ? coord*8 : edgeval(c, p1, dim, coord); v2[dim] = solid ? coord*8 : edgeval(c, p2, dim, coord); v3[dim] = solid ? coord*8 : edgeval(c, p3, dim, coord); pl.toplane(v1.tovec(), v2.tovec(), v3.tovec()); } static 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; } static 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); 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(c, p, p1, p2, plane1, true); if(plane1==plane3) genvertp(c, p, p1, p2, plane1, true); if(plane2==plane3) genvertp(c, p, p2, p3, plane2, true); 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) { if(isentirelysolid(c) || isempty(c)) return; cube o = c; loop(x, 2) loop(y, 2) loop(z, 2) { ivec p(8*x, 8*y, 8*z); vec v; genedgespanvert(p, o, v); edgeset(cubeedge(c, 0, y, z), x, int(v.x+0.49f)); edgeset(cubeedge(c, 1, z, x), y, int(v.y+0.49f)); edgeset(cubeedge(c, 2, x, y), z, int(v.z+0.49f)); } } const ivec cubecoords[8] = // verts of bounding cube { #define GENCUBEVERT(n, x, y, z) ivec(x, y, z), GENCUBEVERTS(0, 8, 0, 8, 0, 8) #undef GENCUBEVERT }; template static inline void gencubevert(cube &c, int i, T &v) { switch(i) { #define GENCUBEVERT(n, x, y, z) \ case n: \ v = T(edgeget(cubeedge(c, 0, y, z), x), \ edgeget(cubeedge(c, 1, z, x), y), \ edgeget(cubeedge(c, 2, x, y), z)); \ break; GENCUBEVERTS(0, 1, 0, 1, 0, 1) #undef GENCUBEVERT } } void genfaceverts(cube &c, int orient, ivec v[4]) { switch(orient) { #define GENFACEORIENT(o, v0, v1, v2, v3) \ case o: v0 v1 v2 v3 break; #define GENFACEVERT(o, n, x,y,z, xv,yv,zv) \ v[n] = ivec(edgeget(cubeedge(c, 0, y, z), x), \ edgeget(cubeedge(c, 1, z, x), y), \ edgeget(cubeedge(c, 2, x, y), z)); GENFACEVERTS(0, 1, 0, 1, 0, 1, , , , , , ) #undef GENFACEORIENT #undef GENFACEVERT } } const ivec facecoords[6][4] = { #define GENFACEORIENT(o, v0, v1, v2, v3) \ { v0, v1, v2, v3 }, #define GENFACEVERT(o, n, x,y,z, xv,yv,zv) \ ivec(x,y,z) GENFACEVERTS(0, 8, 0, 8, 0, 8, , , , , , ) #undef GENFACEORIENT #undef GENFACEVERT }; 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 i = 0; if(solid) { switch(orient) { #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: \ { \ if(dimcoord(orient)) { v0 v1 v2 v3 } else { v3 v2 v1 v0 } \ break; \ } #define GENFACEVERT(orient, vert, xv,yv,zv, x,y,z) \ { facevec &f = fvecs[i]; x ((xv)<<3); y ((yv)<<3); z ((zv)<<3); i++; } GENFACEVERTS(pos.x, pos.x+size, pos.y, pos.y+size, pos.z, pos.z+size, f.x = , f.x = , f.y = , f.y = , (void), (void)) #undef GENFACEVERT } return 4; } ivec buf[4]; if(!v) { genfaceverts(cu, orient, buf); v = buf; } facevec prev(INT_MAX, INT_MAX); switch(orient) { #define GENFACEVERT(orient, vert, sx,sy,sz, dx,dy,dz) \ { \ const ivec &e = v[vert]; \ ivec ef; \ ef.dx = e.sx; ef.dy = e.sy; ef.dz = e.sz; \ if(ef.z == dimcoord(orient)*8) \ { \ facevec &f = fvecs[i]; \ ivec pf; \ pf.dx = pos.sx; pf.dy = pos.sy; pf.dz = pos.sz; \ f = facevec(ef.x*size + (pf.x<<3), ef.y*size + (pf.y<<3)); \ if(f != prev) { prev = f; i++; } \ } \ } GENFACEVERTS(x, x, y, y, z, z, x, x, y, y, z, z) #undef GENFACEORIENT #undef GENFACEVERT } if(fvecs[0] == prev) i--; return i; } 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(o) || 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 gencubevert(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) { ivec v0 = verts[0].getxyz(); const vertinfo *oldverts = cu.ext->verts() + oldsurf.verts; loopj(numverts) if(v0 == oldverts[j].getxyz()) { for(int k = 1; k < numverts; k++) { if(++j >= numverts) j = 0; if(verts[k].getxyz() != oldverts[j].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.8.2+dfsg/src/engine/normal.cpp0000644000175000017500000002717012045412564020752 0ustar bofh80bofh80#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(float u, float v, 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(v, start); setlerpstep(v, 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 u, 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(u-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.8.2+dfsg/src/engine/md5.h0000644000175000017500000003747612045412564017626 0ustar bofh80bofh80struct 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.8.2+dfsg/src/engine/vertmodel.h0000644000175000017500000005713712045412564021136 0ustar bofh80bofh80struct 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 = lastvbuf; } } 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("%s: could not find animation %s", MDL::dir, anim); else loopv(anims) { MDL::loading->parts.last()->setanim(0, anims[i], *frame, *range, *speed, *priority); } } vertcommands() { if(MDL::multiparted()) this->modelcommand(loadpart, "load", "sf"); this->modelcommand(setpitch, "pitch", "ffff"); if(MDL::animated()) this->modelcommand(setanim, "anim", "siiff"); } }; sandboxgamemaker-2.8.2+dfsg/src/engine/master.cpp0000644000175000017500000004711712045412564020760 0ustar bofh80bofh80#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] || c.input[4] == '\n' || c.input[4] == '\r')) { 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.8.2+dfsg/src/engine/smd.h0000644000175000017500000004334412045412564017713 0ustar bofh80bofh80struct 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.8.2+dfsg/src/engine/explosion.h0000644000175000017500000004122212045412564021141 0ustar bofh80bofh80//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) hemiverts[heminumverts++] = vec(sincos360[(360*i)/hres], 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.8.2+dfsg/src/engine/bih.h0000644000175000017500000000227212045412564017665 0ustar bofh80bofh80struct 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.8.2+dfsg/src/engine/textedit.h0000644000175000017500000006763212045412564020770 0ustar bofh80bofh80#define PASTEBUFFER "#pastebuffer" 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); } 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 len > 0; } 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, "r"); 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, "w"); 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; len -= 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); } bool del() // removes the current selection (if any), returns true if selection was removed { int sx, sy, ex, ey; if(!region(sx, sy, ex, ey)) { mark(false); return false; } if(sy == ey) { if(sx == 0 && ex == lines[ey].len) removelines(sy, 1); else lines[sy].del(sx, ex - sx); } else { if(ey > sy+1) { removelines(sy+1, ey-(sy+1)); 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; editline ¤t = currentline(); if(cx >= current.len && cy < lines.length() - 1) { current.append(lines[cy+1].text); removelines(cy + 1, 1); } return true; } 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) { editline newline(&lines[cy].text[cx]); lines[cy].chop(cx); lines[cy].insert(b->lines[i].text,cx); lines.insert(++cy, newline); } else if(i >= b->lines.length() - 1) { 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 movementmark() { scrollonscreen(); if(SDL_GetModState() & KMOD_SHIFT) { if(!region()) mark(true); } else mark(false); } void scrollonscreen() { region(); scrolly = clamp(scrolly, 0, cy); int h = 0; for(int i = cy; i >= scrolly; i--) { int width, height; text_bounds(lines[i].text, width, height, linewrap ? pixelwidth : -1); if(h + height > pixelheight) { scrolly = i + 1; break; } h += height; } } void key(int code, int cooked) { #ifdef __APPLE__ #define MOD_KEYS (KMOD_LMETA|KMOD_RMETA) #else #define MOD_KEYS (KMOD_LCTRL|KMOD_RCTRL) #endif switch(code) { case SDLK_UP: movementmark(); 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); scrollonscreen(); break; } } cy--; scrollonscreen(); break; case SDLK_DOWN: movementmark(); 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); scrollonscreen(); break; } } cy++; scrollonscreen(); break; case -4: scrolly -= 3; break; case -5: scrolly += 3; break; case SDLK_PAGEUP: movementmark(); if(SDL_GetModState() & MOD_KEYS) cy = 0; else cy-=pixelheight/FONTH; scrollonscreen(); break; case SDLK_PAGEDOWN: movementmark(); if(SDL_GetModState() & MOD_KEYS) cy = INT_MAX; else cy+=pixelheight/FONTH; scrollonscreen(); break; case SDLK_HOME: movementmark(); cx = 0; if(SDL_GetModState() & MOD_KEYS) cy = 0; scrollonscreen(); break; case SDLK_END: movementmark(); cx = INT_MAX; if(SDL_GetModState() & MOD_KEYS) cy = INT_MAX; scrollonscreen(); break; case SDLK_LEFT: movementmark(); if(cx > 0) cx--; else if(cy > 0) { cx = INT_MAX; cy--; } scrollonscreen(); break; case SDLK_RIGHT: movementmark(); if(cx < lines[cy].len) cx++; else if(cy < lines.length() - 1) { cx = 0; cy++; } scrollonscreen(); break; case SDLK_DELETE: { if(!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); } } scrollonscreen(); break; } case SDLK_BACKSPACE: { if(!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); } } scrollonscreen(); break; } case SDLK_LSHIFT: case SDLK_RSHIFT: case SDLK_LCTRL: case SDLK_RCTRL: case SDLK_LMETA: case SDLK_RMETA: break; case SDLK_RETURN: { //maintain indentation const char *str = currentline().text; insert('\n'); while((*str == ' ' || *str == '\t') && *(str++)) { insert(*(str - 1)); } scrollonscreen(); break; } case SDLK_TAB: { int sx, sy, ex, ey; if(region(sx, sy, ex, ey)) { for(int i = sy; i <= ey; i++) { if(SDL_GetModState() & KMOD_SHIFT) { int rem = 0; loopj(min(4, lines[i].len)) { if(lines[i].text[j] == ' ') rem++; else { if(lines[i].text[j] == '\t' && !j) rem++; break; } } lines[i].del(0, rem); if(i == my) mx -= rem > mx ? mx : rem; if(i == cy) cx -= rem; } else { lines[i].prepend("\t"); if(i == my) mx++; if(i == cy) cx++; } } } else if(cooked) insert(cooked); scrollonscreen(); break; } case SDLK_a: case SDLK_x: case SDLK_c: case SDLK_v: if(SDL_GetModState() & MOD_KEYS) break; if(!cooked) break; default: insert(cooked); scrollonscreen(); break; } if(SDL_GetModState() & MOD_KEYS) { extern editor *useeditor(const char *name, int mode, bool focus, const char *initval = NULL); switch(code) { case SDLK_a: selectall(); break; case SDLK_x: { editor *b = useeditor(PASTEBUFFER, EDITORFOREVER, false); if(this == b) break; copyselectionto(b); del(); break; } case SDLK_c: { editor *b = useeditor(PASTEBUFFER, EDITORFOREVER, false); if(this == b) break; copyselectionto(b); break; } case SDLK_v: { editor *b = useeditor(PASTEBUFFER, EDITORFOREVER, false); if(this == b) break; insertallfrom(b); break; } } scrollonscreen(); } #undef MOD_KEYS } 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 scrolly = clamp(scrolly, 0, lines.length() - 1); 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); } } 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; } #define TEXTCOMMAND(f, s, d, body) ICOMMAND(f, s, d,\ editor *top = currentfocus();\ if(!top || identflags&IDF_OVERRIDDEN) return;\ body\ ) ICOMMAND(textlist, "", (), // @DEBUG return list of all the editors vector s; loopv(editors) { if(i > 0) s.put(", ", 2); s.put(editors[i]->name, strlen(editors[i]->name)); } s.add('\0'); result(s.getbuf()); ); 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 intret(top->mode); ); 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(); } }); 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 intret(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.8.2+dfsg/src/engine/rendertext.cpp0000644000175000017500000003131212045412564021637 0ustar bofh80bofh80#include "engine.h" static inline bool htcmp(const char *key, const font &f) { return !strcmp(key, f.name); } static hashset 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[name]; if(!f->name) f->name = newstring(name); f->texs.shrink(0); f->texs.add(textureload(tex)); f->chars.shrink(0); f->charoffset = '!'; f->defaultw = *defaultw; f->defaulth = *defaulth; f->scale = f->defaulth; fontdef = f; fontdeftex = 0; } void fontoffset(char *c) { if(!fontdef) return; fontdef->charoffset = c[0]; } void fontscale(int *scale) { if(!fontdef) return; fontdef->scale = *scale > 0 ? *scale : fontdef->defaulth; } 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(fontscale, "i"); COMMAND(fonttex, "s"); COMMAND(fontchar, "iiiiiii"); COMMAND(fontskip, "i"); void fontalias(const char *dst, const char *src) { font *s = fonts.access(src); if(!s) return; font *d = &fonts[dst]; if(!d->name) d->name = newstring(dst); d->texs = s->texs; d->chars = s->chars; d->charoffset = s->charoffset; d->defaultw = s->defaultw; d->defaulth = s->defaulth; d->scale = s->scale; fontdef = d; fontdeftex = d->texs.length()-1; } COMMAND(fontalias, "ss"); 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; } } } float text_widthf(const char *str) { float width, height; text_boundsf(str, width, height); return width; } ICOMMAND(text_width, "s", (char *s), floatret(text_width(s))) #define FONTTAB (4*FONTW) #define TEXTTAB(x) ((int((x)/FONTTAB)+1.0f)*FONTTAB) void tabify(const char *str, int *numtabs) { int tw = max(*numtabs, 0)*FONTTAB-1, tabs = 0; for(float w = text_widthf(str); w <= tw; w = TEXTTAB(w)) ++tabs; int len = strlen(str); char *tstr = newstring(len + tabs); memcpy(tstr, str, len); memset(&tstr[len], '\t', tabs); tstr[len+tabs] = '\0'; stringret(tstr); } COMMAND(tabify, "si"); void draw_textf(const char *fstr, int left, int top, ...) { defvformatstring(str, top, fstr); draw_text(str, left, top); } static float draw_char(Texture *&tex, int c, float x, float y, float scale) { 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 x1 = x + scale*info.offsetx, y1 = y + scale*info.offsety, x2 = x + scale*(info.offsetx + info.w), y2 = y + scale*(info.offsety + info.h), tx1 = info.x / float(tex->xs), ty1 = info.y / float(tex->ys), tx2 = (info.x + info.w) / float(tex->xs), ty2 = (info.y + info.h) / float(tex->ys); varray::attrib(x1, y1); varray::attrib(tx1, ty1); varray::attrib(x2, y1); varray::attrib(tx2, ty1); varray::attrib(x2, y2); varray::attrib(tx2, ty2); varray::attrib(x1, y2); varray::attrib(tx1, ty2); return scale*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 \ float y = 0, x = 0, scale = curfont->scale/float(curfont->defaulth);\ int i;\ for(i = 0; str[i]; i++)\ {\ TEXTINDEX(i)\ int c = uchar(str[i]);\ if(c=='\t') { x = TEXTTAB(x); TEXTWHITE(i) }\ else if(c==' ') { x += scale*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))\ {\ float cw = scale*curfont->chars[c-curfont->charoffset].advance;\ if(cw <= 0) continue;\ if(maxwidth != -1)\ {\ int j = i;\ float 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;\ float cw = scale*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 { float cw = scale*curfont->chars[c-curfont->charoffset].advance; TEXTCHAR(j) }\ } #define TEXTEND(cursor) if(cursor >= i) { do { TEXTINDEX(cursor); } while(0); } int text_visible(const char *str, float hitx, float 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_posf(const char *str, int cursor, float &cx, float &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 = cy = 0; TEXTSKELETON TEXTEND(cursor) #undef TEXTINDEX #undef TEXTWHITE #undef TEXTLINE #undef TEXTCOLOR #undef TEXTCHAR #undef TEXTWORD } void text_boundsf(const char *str, float &width, float &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 } VARP(verttextcursor, 0, 0, 1); 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, scale); x += cw; #define TEXTWORD TEXTWORDSKELETON char colorstack[10]; colorstack[0] = 'c'; //indicate user color bvec color(r, g, b); int colorpos = 0; float cx = -FONTW, 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 TEXTEND(cursor) xtraverts += varray::end(); if(cursor >= 0 && (totalmillis/250)&1) { glColor4ub(r, g, b, a); if(maxwidth != -1 && cx >= maxwidth) { cx = 0; cy += FONTH; } if(verttextcursor) { if(curfont->chars.inrange('|' - curfont->charoffset)) { cx -= curfont->chars['|' - curfont->charoffset].w * curfont->scale / float(curfont->defaulth); } draw_char(tex, '|', left+cx, top+cy, scale); } else draw_char(tex, '_', left+cx, top+cy, scale); 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.8.2+dfsg/src/engine/engine.h0000644000175000017500000005356212045412564020400 0ustar bofh80bofh80#ifndef __ENGINE_H__ #define __ENGINE_H__ #include "cube.h" #include "world.h" #ifndef STANDALONE #include "octa.h" #include "lightmap.h" #include "bih.h" #include "texture.h" #include "model.h" #ifdef __LINUX__ #ifdef V4L2 #include "ccvt.h" #include "v4l2dev.h" #endif #endif #define CONFVERSION 10 // GL_ARB_multitexture extern PFNGLACTIVETEXTUREARBPROC glActiveTexture_; extern PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTexture_; extern PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2f_; extern PFNGLMULTITEXCOORD3FARBPROC glMultiTexCoord3f_; extern PFNGLMULTITEXCOORD4FARBPROC glMultiTexCoord4f_; // GL_ARB_vertex_buffer_object extern PFNGLGENBUFFERSARBPROC glGenBuffers_; extern PFNGLBINDBUFFERARBPROC glBindBuffer_; extern PFNGLMAPBUFFERARBPROC glMapBuffer_; extern PFNGLUNMAPBUFFERARBPROC glUnmapBuffer_; extern PFNGLBUFFERDATAARBPROC glBufferData_; extern PFNGLBUFFERSUBDATAARBPROC glBufferSubData_; extern PFNGLDELETEBUFFERSARBPROC glDeleteBuffers_; extern PFNGLGETBUFFERSUBDATAARBPROC glGetBufferSubData_; // GL_ARB_occlusion_query extern PFNGLGENQUERIESARBPROC glGenQueries_; extern PFNGLDELETEQUERIESARBPROC glDeleteQueries_; extern PFNGLBEGINQUERYARBPROC glBeginQuery_; extern PFNGLENDQUERYARBPROC glEndQuery_; extern PFNGLGETQUERYIVARBPROC glGetQueryiv_; extern PFNGLGETQUERYOBJECTIVARBPROC glGetQueryObjectiv_; extern PFNGLGETQUERYOBJECTUIVARBPROC glGetQueryObjectuiv_; // GL_EXT_framebuffer_object extern PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbuffer_; extern PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffers_; extern PFNGLGENFRAMEBUFFERSEXTPROC glGenRenderbuffers_; extern PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorage_; extern PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatus_; extern PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebuffer_; extern PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffers_; extern PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffers_; extern PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2D_; extern PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbuffer_; extern PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmap_; // GL_EXT_framebuffer_blit #ifndef GL_EXT_framebuffer_blit #define GL_READ_FRAMEBUFFER_EXT 0x8CA8 #define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 #define GL_DRAW_FRAMEBUFFER_BINDING_EXT 0x8CA6 #define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA typedef void (APIENTRYP PFNGLBLITFRAMEBUFFEREXTPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); #endif extern PFNGLBLITFRAMEBUFFEREXTPROC glBlitFramebuffer_; // GL_EXT_draw_range_elements extern PFNGLDRAWRANGEELEMENTSEXTPROC glDrawRangeElements_; // GL_EXT_blend_minmax extern PFNGLBLENDEQUATIONEXTPROC glBlendEquation_; // GL_EXT_blend_color extern PFNGLBLENDCOLOREXTPROC glBlendColor_; // GL_EXT_multi_draw_arrays extern PFNGLMULTIDRAWARRAYSEXTPROC glMultiDrawArrays_; extern PFNGLMULTIDRAWELEMENTSEXTPROC glMultiDrawElements_; // GL_EXT_packed_depth_stencil #ifndef GL_DEPTH_STENCIL_EXT #define GL_DEPTH_STENCIL_EXT 0x84F9 #endif #ifndef GL_DEPTH24_STENCIL8_EXT #define GL_DEPTH24_STENCIL8_EXT 0x88F0 #endif // GL_ARB_texture_compression extern PFNGLCOMPRESSEDTEXIMAGE3DARBPROC glCompressedTexImage3D_; extern PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glCompressedTexImage2D_; extern PFNGLCOMPRESSEDTEXIMAGE1DARBPROC glCompressedTexImage1D_; extern PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC glCompressedTexSubImage3D_; extern PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC glCompressedTexSubImage2D_; extern PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC glCompressedTexSubImage1D_; extern PFNGLGETCOMPRESSEDTEXIMAGEARBPROC glGetCompressedTexImage_; // GL_EXT_fog_coord extern PFNGLFOGCOORDPOINTEREXTPROC glFogCoordPointer_; #include "varray.h" extern dynent *player; extern physent *camera1; // special ent that acts as camera, same object as player1 in FPS mode extern int worldscale, worldsize; extern int mapversion; extern char *maptitle; extern vector 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, scale; font() : name(NULL) {} ~font() { DELETEA(name); } }; #define FONTH (curfont->scale) #define FONTW (FONTH/2) #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, int margin = 0); extern void blurnormals(int n, int w, int h, bvec *dst, const bvec *src, int margin = 0); 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 edgespan2vectorcube(cube &c); 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 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 else 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 else if(v.y >= o.y+s.y) p &= 0x33; // etc.. if(v.x <= o.x) p &= 0xAA; else 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 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, int limit = -1); 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 *cmdprefix); 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 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(); //new UI by eihrul, courtesy of 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; } // 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.8.2+dfsg/src/engine/octa.h0000644000175000017500000002435112045412564020053 0ustar bofh80bofh80// 6-directional octree heightfield map format struct elementset { ushort texture, lmid, envmap; uchar dim, layer; ushort length[2], minvert[2], maxvert[2]; }; enum { EMID_NONE = 0, EMID_CUSTOM, EMID_SKY, EMID_RESERVED }; struct materialsurface { enum { F_EDIT = 1<<0 }; ivec o; ushort csize, rsize; union { short index; short depth; }; uchar material, orient, flags, skip; union { entity *light; ushort envmap; uchar ends; }; }; struct vertinfo { ushort x, y, z, u, v, norm; void setxyz(ushort a, ushort b, ushort c) { x = a; y = b; z = c; } void setxyz(const ivec &v) { setxyz(v.x, v.y, v.z); } void set(ushort a, ushort b, ushort c, ushort s = 0, ushort t = 0, ushort n = 0) { setxyz(a, b, c); u = s; v = t; norm = n; } void set(const ivec &v, ushort s = 0, ushort t = 0, ushort n = 0) { set(v.x, v.y, v.z, s, t, n); } ivec getxyz() const { return ivec(x, y, z); } }; enum { LAYER_TOP = (1<<5), LAYER_BOTTOM = (1<<6), LAYER_DUP = (1<<7), LAYER_BLEND = LAYER_TOP|LAYER_BOTTOM, MAXFACEVERTS = 15 }; enum { LMID_AMBIENT = 0, LMID_AMBIENT1, LMID_BRIGHT, LMID_BRIGHT1, LMID_DARK, LMID_DARK1, LMID_RESERVED }; struct surfaceinfo { uchar lmid[2]; uchar verts, numverts; int totalverts() const { return numverts&LAYER_DUP ? (numverts&MAXFACEVERTS)*2 : numverts&MAXFACEVERTS; } bool used() const { return lmid[0] != LMID_AMBIENT || lmid[1] != LMID_AMBIENT || numverts&~LAYER_TOP; } void clear() { lmid[0] = LMID_AMBIENT; lmid[1] = LMID_AMBIENT; numverts = (numverts&MAXFACEVERTS) | LAYER_TOP; } void brighten() { lmid[0] = LMID_BRIGHT; lmid[1] = LMID_AMBIENT; numverts = (numverts&MAXFACEVERTS) | LAYER_TOP; } }; static const surfaceinfo ambientsurface = {{LMID_AMBIENT, LMID_AMBIENT}, 0, LAYER_TOP}; static const surfaceinfo brightsurface = {{LMID_BRIGHT, LMID_AMBIENT}, 0, LAYER_TOP}; static const surfaceinfo brightbottomsurface = {{LMID_AMBIENT, LMID_BRIGHT}, 0, LAYER_BOTTOM}; struct grasstri { vec v[4]; int numv; vec4 tcu, tcv; plane surface; vec center; float radius; float minz, maxz; ushort texture, lmid; }; struct occludequery { void *owner; GLuint id; int fragments; }; struct vtxarray; struct octaentities { vector 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 }; #define GENCUBEVERTS(x0,x1, y0,y1, z0,z1) \ GENCUBEVERT(0, x1, y1, z0) \ GENCUBEVERT(1, x0, y1, z0) \ GENCUBEVERT(2, x0, y1, z1) \ GENCUBEVERT(3, x1, y1, z1) \ GENCUBEVERT(4, x1, y0, z1) \ GENCUBEVERT(5, x0, y0, z1) \ GENCUBEVERT(6, x0, y0, z0) \ GENCUBEVERT(7, x1, y0, z0) #define GENFACEVERTX(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv) #define GENFACEVERTSX(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEORIENT(0, GENFACEVERTX(0,0, x0,y1,z1, d0,r1,c1), GENFACEVERTX(0,1, x0,y1,z0, d0,r1,c0), GENFACEVERTX(0,2, x0,y0,z0, d0,r0,c0), GENFACEVERTX(0,3, x0,y0,z1, d0,r0,c1)) \ GENFACEORIENT(1, GENFACEVERTX(1,0, x1,y1,z1, d1,r1,c1), GENFACEVERTX(1,1, x1,y0,z1, d1,r0,c1), GENFACEVERTX(1,2, x1,y0,z0, d1,r0,c0), GENFACEVERTX(1,3, x1,y1,z0, d1,r1,c0)) #define GENFACEVERTY(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv) #define GENFACEVERTSY(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEORIENT(2, GENFACEVERTY(2,0, x1,y0,z1, c1,d0,r1), GENFACEVERTY(2,1, x0,y0,z1, c0,d0,r1), GENFACEVERTY(2,2, x0,y0,z0, c0,d0,r0), GENFACEVERTY(2,3, x1,y0,z0, c1,d0,r0)) \ GENFACEORIENT(3, GENFACEVERTY(3,0, x0,y1,z0, c0,d1,r0), GENFACEVERTY(3,1, x0,y1,z1, c0,d1,r1), GENFACEVERTY(3,2, x1,y1,z1, c1,d1,r1), GENFACEVERTY(3,3, x1,y1,z0, c1,d1,r0)) #define GENFACEVERTZ(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv) #define GENFACEVERTSZ(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEORIENT(4, GENFACEVERTZ(4,0, x0,y0,z0, r0,c0,d0), GENFACEVERTZ(4,1, x0,y1,z0, r0,c1,d0), GENFACEVERTZ(4,2, x1,y1,z0, r1,c1,d0), GENFACEVERTZ(4,3, x1,y0,z0, r1,c0,d0)) \ GENFACEORIENT(5, GENFACEVERTZ(5,0, x0,y0,z1, r0,c0,d1), GENFACEVERTZ(5,1, x1,y0,z1, r1,c0,d1), GENFACEVERTZ(5,2, x1,y1,z1, r1,c1,d1), GENFACEVERTZ(5,3, x0,y1,z1, r0,c1,d1)) #define GENFACEVERTSXY(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEVERTSX(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEVERTSY(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) #define GENFACEVERTS(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEVERTSXY(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEVERTSZ(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) sandboxgamemaker-2.8.2+dfsg/src/engine/shader.cpp0000644000175000017500000024007012045412564020724 0ustar bofh80bofh80// 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.xy, -fragment.texcoord[%d].z, smvals.y, smvals.xzzz;\n" "CMP smvals.w, -smdiff.x, smvals.w, 0;\n" "MAD_SAT smvals.w, -8, smdiff.y, smvals.w;\n" : "TEMP smvals, smtest, smambient;\n" "TEX smvals, fragment.texcoord[%d], texture[7], 2D;\n" "MUL smtest.y, fragment.texcoord[%d].z, smvals.y;\n" "SLT smtest.xy, smtest.y, smvals.xzzz;\n" "MAD_SAT smvals.w, smvals.w, smtest.x, -smtest.y;\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 && !iscubespace(*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(iscubealpha(*pspragma)) pspragma++; while(*pspragma && !iscubespace(*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.8.2+dfsg/src/engine/water.cpp0000644000175000017500000013006512045412564020602 0ustar bofh80bofh80#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); } static void drawmaterialquery(const materialsurface &m, float offset, float border = 0) { if(varray::data.empty()) { varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); varray::begin(GL_QUADS); } float x = m.o.x, y = m.o.y, z = m.o.z, csize = m.csize + border, rsize = m.rsize + border; switch(m.orient) { #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: v0 v1 v2 v3 break; #define GENFACEVERT(orient, vert, mx,my,mz, sx,sy,sz) \ varray::attrib(mx sx, my sy, mz sz); GENFACEVERTS(x, x, y, y, z, z, - border, + csize, - border, + rsize, + offset, - offset) #undef GENFACEORIENT #undef GENFACEVERT } } 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; } drawmaterialquery(m, 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); } varray::enable(); loopv(ref.matsurfs) { materialsurface &m = *ref.matsurfs[i]; drawmaterialquery(m, -offset, maskreflect); } 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.8.2+dfsg/src/engine/scale.h0000644000175000017500000001042612045412564020212 0ustar bofh80bofh80static 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.8.2+dfsg/src/engine/grass.cpp0000644000175000017500000002607712045412564020606 0ustar bofh80bofh80#include "engine.h" VARP(grass, 0, 0, 1); VAR(dbggrass, 0, 0, 1); VARP(grassdist, 0, 256, 10000); FVARR(grasstaper, 0, 0.2, 1); FVARP(grassstep, 0.5, 2, 8); VARR(grassheight, 1, 4, 64); #define NUMGRASSWEDGES 8 static struct grasswedge { vec dir, across, edge1, edge2; plane bound1, bound2; grasswedge(int i) : dir(2*M_PI*(i+0.5f)/float(NUMGRASSWEDGES), 0), across(2*M_PI*((i+0.5f)/float(NUMGRASSWEDGES) + 0.25f), 0), edge1(vec(2*M_PI*i/float(NUMGRASSWEDGES), 0).div(cos(M_PI/NUMGRASSWEDGES))), edge2(vec(2*M_PI*(i+1)/float(NUMGRASSWEDGES), 0).div(cos(M_PI/NUMGRASSWEDGES))), bound1(vec(2*M_PI*(i/float(NUMGRASSWEDGES) - 0.25f), 0), 0), bound2(vec(2*M_PI*((i+1)/float(NUMGRASSWEDGES) + 0.25f), 0), 0) { across.div(-across.dot(bound1)); } } grasswedges[NUMGRASSWEDGES] = { 0, 1, 2, 3, 4, 5, 6, 7 }; struct grassvert { vec pos; uchar color[4]; float u, v, lmu, lmv; }; static vector 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; extern bool brightengeom; extern int fullbright; int lmid = brightengeom && (g.lmid < LMID_RESERVED || (fullbright && editmode)) ? LMID_BRIGHT : g.lmid; group->lmtex = lightmaptexs.inrange(lmid) ? lightmaptexs[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.8.2+dfsg/src/engine/pch.cpp0000644000175000017500000000002512045412564020222 0ustar bofh80bofh80#include "engine.h" sandboxgamemaker-2.8.2+dfsg/src/engine/shadowmap.cpp0000644000175000017500000003770312045412564021450 0ustar bofh80bofh80#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< 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(float u, float v, const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end); extern void lerpnormal(float u, 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.8.2+dfsg/src/engine/worldio.cpp0000644000175000017500000020140512045412564021134 0ustar bofh80bofh80 // 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<>4) | ((hassurfs&0x03)<<4); } } if(mapversion >= 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 %s %s", index >= 0 ? textypename(s.sts[j].type) : "1", escapestring(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), "w"); 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 bool 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", escapeid(id.name), *id.storage.i); break; case ID_FVAR: f->printf("//%s %s\n", escapeid(id.name), floatstr(*id.storage.f)); break; case ID_SVAR: f->printf("//%s %s\n", escapeid(id.name), escapestring(*id.storage.s)); 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 %s // %d\n", escapestring(mapmodels[i].name), 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; } void clearmapcrc() { mapcrc = 0; } 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(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"); 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); UI::clearmainmenu(); 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.8.2+dfsg/src/engine/bih.cpp0000644000175000017500000002434512045412564020225 0ustar bofh80bofh80#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 = max(tmin, farsplit); 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.8.2+dfsg/src/engine/lightmap.cpp0000644000175000017500000027114412045412564021271 0ustar bofh80bofh80#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 = sincos360[clamp(int(light.attached->attr[0]), 1, 89)].x, spotatten = (ray.dot(spot) - maxatten) / (1 - 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, 64); 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, vec origin1, const vec &xstep1, const vec &ystep1, 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 + 4)*(LM_MAXH + 4)*sizeof(vec)); origin1.sub(vec(ystep1).add(xstep1).mul(blurlms)); origin2.sub(vec(ystep2).add(xstep2).mul(blurlms)); int aasample = min(1 << lmaa, 4); int stride = aasample*(w->w+1); vec *sample = w->colordata; uchar *skylight = w->ambient; lerpbounds start, end; initlerpbounds(-blurlms, -blurlms, lv, numv, start, end); float sidex = side0 + blurlms*sidestep; for(int y = 0; y < w->h; ++y, sidex += sidestep) { vec normal, nstep; lerpnormal(-blurlms, y - blurlms, lv, numv, start, end, normal, nstep); for(int x = 0; x < w->w; ++x, normal.add(nstep), skylight += w->bpp) { #define EDGE_TOLERANCE(x, y) \ (x < blurlms \ || x+1 > w->w - blurlms \ || y < blurlms \ || y+1 > w->h - blurlms \ ? edgetolerance : 1) float t = EDGE_TOLERANCE(x, y) * tolerance; 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, t, 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, t, u, skylight[3]); sample += aasample; } sample += aasample; } if(adaptivesample > 1 && min(w->w, w->h) >= 2) lightmask = ~lightused; sample = w->colordata; initlerpbounds(-blurlms, -blurlms, lv, numv, start, end); sidex = side0 + blurlms*sidestep; for(int y = 0; y < w->h; ++y, sidex += sidestep) { vec normal, nstep; lerpnormal(-blurlms, y - blurlms, 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 AA_EDGE_TOLERANCE(x, y, i) EDGE_TOLERANCE(x + aacoords[i][0], y + aacoords[i][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, AA_EDGE_TOLERANCE(x, y, 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, AA_EDGE_TOLERANCE(x, y, 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, edgetolerance * 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(-blurlms, w->h - blurlms, 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 = blurlms && (w->w > 1 || w->h > 1) ? w->blur : w->colorbuf; uchar mincolor[4] = { 255, 255, 255, 255 }, maxcolor[4] = { 0, 0, 0, 0 }; bvec *dstray = blurlms && (w->w > 1 || w->h > 1) ? (bvec *)w->raydata : 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->colorbuf, w->blur, blurlms); if((w->type&LM_TYPE) == LM_BUMPMAP0) blurnormals(blurlms, w->w, w->h, w->raybuf, (const bvec *)w->raydata, blurlms); w->lastlightmap->w = (w->w -= 2*blurlms); w->lastlightmap->h = (w->h -= 2*blurlms); } 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(!preview) { w->w += 2*blurlms; w->h += 2*blurlms; } 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 + 4)*(LM_MAXH + 4)]; blur = new uchar[4*(LM_MAXW + 4)*(LM_MAXH + 4)]; colordata = new vec[4*(LM_MAXW+1 + 4)*(LM_MAXH+1 + 4)]; raydata = new vec[(LM_MAXW + 4)*(LM_MAXH + 4)]; 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] = { uchar(fullbrightlevel), uchar(fullbrightlevel), uchar(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] = { uchar(fullbrightlevel), uchar(fullbrightlevel), uchar(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(mag < 1e-4f) ray = vec(0, 0, -1); else { 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 = sincos360[clamp(int(e.attached->attr[0]), 1, 89)].x, spotatten = (ray.dot(spot) - maxatten) / (1 - maxatten); if(spotatten <= 0) continue; intensity *= spotatten; } //if(target==player->o) //{ // conoutf(CON_DEBUG, "%d - %f %f", i, intensity, mag); //} vec lightcol = vec(e.attr[1], e.attr[2], e.attr[3]).mul(1.0f/255); color.add(vec(lightcol).mul(intensity)); dir.add(vec(ray).mul(-intensity*lightcol.x*lightcol.y*lightcol.z)); } if(sunlight && shadowray(target, sunlightdir, 1e16f, RAY_SHADOW | RAY_POLY | (skytexturelight ? RAY_SKIPSKY : 0), t) > 1e15f) { vec lightcol = vec(sunlightcolor.x, sunlightcolor.y, sunlightcolor.z).mul(sunlightscale/255); color.add(lightcol); dir.add(vec(sunlightdir).mul(lightcol.x*lightcol.y*lightcol.z)); } 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 = sincos360[clamp(int(e.attached->attr[0]), 1, 89)].x, spotatten = (ray.dot(spot) - maxatten) / (1 - 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.8.2+dfsg/src/engine/iqm.h0000644000175000017500000003466312045412564017722 0ustar bofh80bofh80struct 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]); 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.8.2+dfsg/src/engine/varray.h0000644000175000017500000001565112045412564020434 0ustar bofh80bofh80namespace 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 = attribmask = 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.8.2+dfsg/src/engine/animmodel.h0000644000175000017500000016130612045412564021074 0ustar bofh80bofh80VARFP(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->type&Texture::ALPHA && !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->type&Texture::ALPHA) { 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]].sub(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->type&Texture::ALPHA ? 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][game::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][game::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[game::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 = {'\0'}; // crashes clang if "" is used here 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.8.2+dfsg/src/engine/glare.cpp0000644000175000017500000000236412045412564020552 0ustar bofh80bofh80#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< { 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.8.2+dfsg/src/engine/renderva.cpp0000644000175000017500000026332112045412564021270 0ustar bofh80bofh80// 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); #define GENFACEORIENT(orient, v0, v1, v2, v3) do { \ int dim = dimension(orient); \ if(dimcoord(orient)) \ { \ if(camera[dim] < bo[dim] + br[dim]) continue; \ } \ else if(camera[dim] > bo[dim]) continue; \ v0 v1 v2 v3 \ xtraverts += 4; \ } while(0); #define GENFACEVERT(orient, vert, ox,oy,oz, rx,ry,rz) \ glVertex3f(ox rx, oy ry, oz rz); GENFACEVERTS(bo.x, bo.x + br.x, bo.y, bo.y + br.y, bo.z, bo.z + br.z, , , , , , ) #undef GENFACEORIENT #undef GENFACEVERTS 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 || oe->distance >= 0) { 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.8.2+dfsg/src/engine/rendergl.cpp0000644000175000017500000026235012045412564021265 0ustar bofh80bofh80// 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); VAR(glslversion, 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(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); if(len) 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 bool mesa = false, intel = false, ati = false, nvidia = false; if(strstr(renderer, "Mesa") || strstr(version, "Mesa")) mesa = true; else if(strstr(vendor, "NVIDIA")) nvidia = true; else if(strstr(vendor, "ATI") || strstr(vendor, "Advanced Micro Devices")) ati = true; else if(strstr(vendor, "Intel")) intel = true; //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; GLint val; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &val); hwtexsize = val; 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)"); #ifdef __APPLE__ // Intel HD3000 broke occlusion queries - either causing software fallback, or returning wrong results if(!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(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; } 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(ati) ati_dph_bug = ati_line_bug = 1; else if(mesa) 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"); const char *str = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION_ARB); uint majorversion, minorversion; if(!str || sscanf(str, " %u.%u", &majorversion, &minorversion) != 2) glslversion = 100; else glslversion = majorversion*100 + minorversion; } } extern int reservedynlighttc, reserveshadowmaptc, batchlightmaps, ffdynlights, fpdepthfx; if(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(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(intel) { #ifdef __APPLE__ apple_vp_bug = 1; #endif } if(!hasGLSL || glslversion < 130) { avoidshaders = 1; if(hwtexsize < 4096) { maxtexsize = hwtexsize >= 2048 ? 512 : 256; batchlightmaps = 0; } if(!hasTF) ffdynlights = 0; } reservevpparams = 20; if(!hasOQ) waterrefract = 0; } bool hasshaders = (hasVP && hasFP) || hasGLSL; if(hasshaders) { extern int matskel, forceglsl; if(!avoidshaders) { matskel = 0; if(hasGLSL && glslversion >= 130) forceglsl = 1; } } 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(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(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(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(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(nvidia || (ati && 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; } } } } 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 = camera1->yaw, pitch = camera1->pitch; vecfromyawpitch(yaw, pitch, 1, 0, camdir); vecfromyawpitch(yaw, 0, 0, -1, camright); vecfromyawpitch(yaw, pitch+90, 1, 0, camup); vec lookdir = camdir; 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)); lookdir = dir1.sub(dir2).normalize(); if(raycubepos(camera1->o, lookdir, worldpos, 0, RAY_CLIPMAT|RAY_SKIPFIRST) == -1) worldpos = vec(camdir).mul(2*worldsize).add(camera1->o); } 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(0, 0, size, size); 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); 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); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); GLfloat border[4] = { minimapcolor.x/255.0f, minimapcolor.y/255.0f, minimapcolor.z/255.0f, 1.0f }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border); 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(); if(wireframe && editmode) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); renderparticles(true); 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(); extern int hidehud; if(!hidehud && !UI::mainmenu) { glDisable(GL_TEXTURE_2D); notextureshader->set(); 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); glEnable(GL_TEXTURE_2D); defaultshader->set(); } else { defaultshader->set(); } UI::render(); 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); UI::render(); 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("data/fps/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, 20, 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, "newui/cursor"); 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", escapestring(crosshairs[i]->name), i); f->printf("\n"); } void drawcrosshair(int w, int h) { bool windowhit = UI::hascursor(); if(!windowhit && hidehud) return; //(hidehud || player->state==CS_SPECTATOR || player->state==CS_DEAD)) return; if(!windowhit && UI::mainmenu) return; float r = 1, g = 1, b = 1, cx = 0.5f, cy = 0.5f, chsize; Texture *crosshair; UI::getcursorpos(cx, cy); if(windowhit) { defformatstring(tname)("data/%s", guicursortex); static Texture *cursor = NULL; cursor = textureload(tname, 3, true); crosshair = cursor; chsize = cursorsize*w/900.0f; } 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->type&Texture::ALPHA) 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) { 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); if(!UI::mainmenu) { drawdamagescreen(w, h); drawdamagecompass(w, h); } glEnable(GL_TEXTURE_2D); defaultshader->set(); int conw = int(w/conscale), conh = int(h/conscale), abovehud = conh - FONTH; // int limitgui = abovehud; if(!hidehud && !UI::mainmenu) { if(hidestats || (!editmode && !showeditstats)) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); game::gameplayhud(w, h); abovehud = min(abovehud, int(conh*game::abovegameplayhud(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 = executestr("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 = executestr("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); } 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; if((renderedframe && !UI::mainmenu && lastupdate != lastmillis) || lastw != w || lasth != h) { 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.8.2+dfsg/src/engine/lensflare.h0000644000175000017500000001454012045412564021077 0ustar bofh80bofh80static 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 flaredir = vec(o).sub(camera1->o); vec center = vec(camdir).mul(flaredir.dot(camdir)).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(); 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(camdir).mul(flaredir.dot(camdir)).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.8.2+dfsg/src/engine/blob.cpp0000644000175000017500000004656112045412564020405 0ustar bofh80bofh80#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) { switch(orient) { #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: v0 v1 v2 v3 break; #define GENFACEVERT(orient, vert, x,y,z, xv,yv,zv) \ pos[numverts++] = vec(x xv, y yv, z zv); GENFACEVERTS(o.x, o.x, o.y, o.y, o.z, o.z, , + mat->csize, , + mat->rsize, + 0.1f, - 0.1f); #undef GENFACEORIENT #undef GENFACEVERT } 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.8.2+dfsg/src/engine/client.cpp0000644000175000017500000001601312045412564020732 0ustar bofh80bofh80// 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; } SVARP(connectname, ""); VARP(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*1024, rate*1024); 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); UI::mainmenu = 1; } 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.8.2+dfsg/src/engine/main.cpp0000644000175000017500000007274012053074143020405 0ustar bofh80bofh80// main.cpp: initialisation & main loop #include "engine.h" SVARO(version, "2.8.2"); 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; 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() { stream *f = openutf8file("init.cfg", "w"); 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, ""); vector events; void pushevent(const SDL_Event &e) { events.add(e); } static bool filterevent(const SDL_Event &event) { switch(event.type) { case SDL_MOUSEMOTION: #ifndef WIN32 if(grabinput && !(screen->flags&SDL_FULLSCREEN)) { if(event.motion.x == screen->w / 2 && event.motion.y == screen->h / 2) return false; // ignore any motion events generated by SDL_WarpMouse #ifdef __APPLE__ if(event.motion.y == 0) return false; // let mac users drag windows via the title bar #endif } #endif break; } return true; } static inline bool pollevent(SDL_Event &event) { while(SDL_PollEvent(&event)) { if(filterevent(event)) return true; } return false; } bool interceptkey(int sym) { static int lastintercept = SDLK_UNKNOWN; int len = lastintercept == sym ? events.length() : 0; SDL_Event event; while(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 ignoremousemotion() { SDL_Event e; SDL_PumpEvents(); while(SDL_PeepEvents(&e, 1, SDL_GETEVENT, SDL_EVENTMASK(SDL_MOUSEMOTION))); } static void resetmousemotion() { #ifndef WIN32 if(grabinput && !(screen->flags&SDL_FULLSCREEN)) { SDL_WarpMouse(screen->w / 2, screen->h / 2); } #endif } static void checkmousemotion(int &dx, int &dy) { loopv(events) { SDL_Event &event = events[i]; if(event.type != SDL_MOUSEMOTION) { if(i > 0) events.remove(0, i); return; } dx += event.motion.xrel; dy += event.motion.yrel; } events.setsize(0); SDL_Event event; while(pollevent(event)) { if(event.type != SDL_MOUSEMOTION) { events.add(event); return; } dx += event.motion.xrel; dy += event.motion.yrel; } } void checkinput() { SDL_Event event; int lasttype = 0, lastbut = 0; bool mousemoved = false; while(events.length() || pollevent(event)) { if(events.length()) event = events.remove(0); switch(event.type) { case SDL_QUIT: quit(); return; #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(grabinput) { int dx = event.motion.xrel, dy = event.motion.yrel; checkmousemotion(dx, dy); if(!UI::movecursor(dx, dy) && !UI::hascursor()) mousemove(dx, dy); mousemoved = true; } 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; } } if(mousemoved) resetmousemotion(); } 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(menufps, 0, 60, 1000); VARP(maxfps, 0, 200, 1000); void limitfps(int &millis, int curmillis) { int limit = UI::mainmenu && menufps ? (maxfps ? min(maxfps, menufps) : menufps) : maxfps; 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"); UI::setup(); 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); execfile("data/ui.cfg"); formatstring(confname)("data/%s/ui.cfg", game::gameident()); execfile(confname, false); 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); ignoremousemotion(); 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(); UI::update(); 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; if(UI::mainmenu) 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.8.2+dfsg/src/engine/mpr.h0000644000175000017500000004711212045412564017723 0ustar bofh80bofh80// 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.8.2+dfsg/src/engine/renderparticles.cpp0000644000175000017500000016660612055557300022657 0ustar bofh80bofh80// 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; } 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); 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) { if(collide >= 0) { 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 - floorz; 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; } } else 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 killpart(listparticle *p) { } void reset() { if(!list) return; listparticle *p = list; for(;;) { killpart(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; killpart(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(); float scale = p->size/80.0f; GLfloat billboardmatrix[16] = { scale*camright.x, scale*camright.y, scale*camright.z, 0, -scale*camup.x, -scale*camup.y, -scale*camup.z, 0, -scale*camdir.x, -scale*camdir.y, -scale*camdir.z, 0, o.x, o.y, o.z, 1 }; glMultMatrixf(billboardmatrix); 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) { const vec2 &sc = sincos360[k*(180/(10-1))]; float c = (0.5f + 0.1f)*sc.y, s = 0.5f - (0.5f + 0.1f)*sc.x; 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) { const vec2 &sc = sincos360[k*(180/(10-1))]; float c = 0.5f*sc.y, s = 0.5f - 0.5f*sc.x; 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) { const vec2 &sc = sincos360[k*(180/(10-1))]; float c = (0.5f + 0.1f)*sc.y, s = 0.5f - (0.5f + 0.1f)*sc.x; glVertex2f(left + c*FONTH, s*FONTH); } glEnd(); } glColor3ubv(color); glBegin(GL_TRIANGLE_STRIP); loopk(10) { const vec2 &sc = sincos360[k*(180/(10-1))]; float c = 0.5f*sc.y, s = 0.5f - 0.5f*sc.x; 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 killpart(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(); float scale = p->size/80.0f; GLfloat billboardmatrix[16] = { scale*camright.x, scale*camright.y, scale*camright.z, 0, -scale*camup.x, -scale*camup.y, -scale*camup.z, 0, -scale*camdir.x, -scale*camdir.y, -scale*camdir.z, 0, o.x, o.y, o.z, 1 }; glMultMatrixf(billboardmatrix); 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] = { uchar(r), uchar(g), uchar(b), uchar(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("packages/particles/blood", PT_PART|PT_FLIP|PT_MOD|PT_RND4, DECAL_BLOOD), // 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 new quadrenderer("packages/particles/waterleak", PT_PART|PT_FLIP|PT_MOD|PT_RND4, DECAL_WATERLEAK), &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) + (parts[type]->collide >= 0 ? COLLIDEERROR : 0) : -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 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 * 24..26 flat plane * +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) { const vec2 &sc = sincos360[rnd(360)]; to[dir%3] = sc.y*radius; to[(dir+1)%3] = sc.x*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 if(dir < 24) //sphere { to = vec(PI2*float(rnd(1000))/1000.0, PI*float(rnd(1000)-500)/1000.0).mul(radius); to.add(p); from = p; } else if(dir < 27) // flat plane { to[dir%3] = float(rndscale(2*radius)-radius); to[(dir+1)%3] = float(rndscale(2*radius)-radius); to[(dir+2)%3] = 0.0; to.add(p); from = to; } else from = to = p; if(inv) swap(from, to); if(taper) { float dist = clamp(from.dist2(camera1->o)/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(from, to, rnd(fade*3)+1, type, color, size, gravity); else { vec d = vec(to).sub(from).rescale(vel); //velocity particle *n = newparticle(from, d, rnd(fade*3)+1, type, color, size, gravity); if(fade < 0 && parts[type]->collide) n->val = from.z - raycube(from, vec(0, 0, -1), parts[type]->collide >= 0 ? COLLIDERADIUS : max(from.z, 0.0f), RAY_CLIPMAT) + (parts[type]->collide >= 0 ? COLLIDEERROR : 0); } } } 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]); if(identexists(aliasname)) particle_textcopy(e.o, getalias(aliasname), PART_TEXT, 1, 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_textcopy(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; tmp[0] = ds[0] = '\0'; //prevents weird visual artefacts extern void printent(extentity &e, char *buf); int colour = 0xFFB600; pos.z += 1.5; if(!showenttext) { printent(e, ds); particle_textcopy(pos, ds, PART_TEXT, 1, colour, 2.0f); return; } /* 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); } 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] == 8) { defformatstring(aliasname)("part_text_%d", e.attr[1]); defformatstring(party_text)("particles:%s", getalias(aliasname)); particle_textcopy(e.o, party_text, PART_TEXT, 1, 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] == 8) { defformatstring(aliasname)("part_text_%d", e.attr[1]); defformatstring(party_text)("particles:%s", getalias(aliasname)); particle_textcopy(e.o, party_text, PART_TEXT, 1, 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.8.2+dfsg/src/engine/decal.cpp0000644000175000017500000005067312045412564020536 0ustar bofh80bofh80#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) { planes[0] = vec(0, 0, 0); switch(orient) { #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: \ planes[0][dimension(orient)] = dimcoord(orient) ? 1 : -1; \ v0 v1 v2 v3 \ break; #define GENFACEVERT(orient, vert, x,y,z, xv,yv,zv) \ pos[numverts++] = vec(x xv, y yv, z zv); GENFACEVERTS(o.x, o.x, o.y, o.y, o.z, o.z, , + mat->csize, , + mat->rsize, + 0.1f, - 0.1f); #undef GENFACEORIENT #undef GENFACEVERT } } 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.8.2+dfsg/src/engine/pvs.cpp0000644000175000017500000012201412045412564020263 0ustar bofh80bofh80#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.8.2+dfsg/src/engine/octaedit.cpp0000644000175000017500000026332012045412564021255 0ustar bofh80bofh80#include "engine.h" extern int outline; void boxs(int orient, vec o, const vec &s) { int d = dimension(orient), dc= dimcoord(orient); float f = !outline ? 0 : (dc>0 ? 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); bool hidecursor = UI::hascursor() || blendpaintmode, hovering = false; hmapsel = false; vec dir = vec(worldpos).sub(camera1->o).normalize(); if(moving) { ivec e; static vec v, handle; editmoveplane(sel.o.tovec(), dir, 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(dir); } else { ivec w; float sdist = 0, wdist = 0, t; int entorient = 0, ent = -1; wdist = rayent(camera1->o, dir, 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), camera1->o, dir, 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(dir).mul(wdist+0.05f).add(camera1->o); if(!insideworld(w)) { loopi(3) wdist = min(wdist, ((dir[i] > 0 ? worldsize : 0) - camera1->o[i]) / dir[i]); w = vec(dir).mul(wdist-0.05f).add(camera1->o); if(!insideworld(w)) { wdist = 0; loopi(3) w[i] = clamp(camera1->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), camera1->o, dir, 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) == (dir[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(camera1->o, dir, 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; if(UI::mainmenu) return; 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) { int bsize = sizeof(block3)+sizeof(cube)*s.size(); if(bsize <= 0 || bsize > (100<<20)) return 0; block3 *b = (block3 *)new uchar[bsize]; 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); if(blocksize <= 0 || blocksize > (undomegs<<20)) return NULL; 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); if(u) 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); } if(r) { 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() <= 0 || e->copy->size() > (1<<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() > (1<<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; if(_u) { 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 || s->material != MAT_AIR) 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); if(uselasttex) { int tex = DEFAULT_GEOM; extern int curtexindex; if(texmru.inrange(curtexindex)) tex = texmru[curtexindex]; loopi(6) c.texture[i] = tex; } else 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; } ivec getcubevector2(cube &c, int dir, int x,int y) { int d = dimension(dir); int dc = dimcoord(dir); ivec u(d,x,y,dc); ivec nv; for(int i=0;i<3;i++) { if(u[D[i]]) nv[i]=8-edgeget(cubeedge(c,i,u[R[i]],u[C[i]]),u[D[i]]); else nv[i]=edgeget(cubeedge(c,i,u[R[i]],u[C[i]]),u[D[i]]); } return nv; } // like setcubevector, but make the offset (dx,dy,dz) always zero-based relative to the vertex of the cube void setcubevector2(cube &c, int dir, int x,int y, int dx, int dy, int dz) { int d = dimension(dir); int dc = dimcoord(dir); ivec u(d,x,y,dc); ivec nv(d,dx,dy,dz); for(int i=0;i<3;i++) { if(u[D[i]]) { edgeset(cubeedge(c,i,u[R[i]],u[C[i]]),u[D[i]],8-nv[i]); } else { edgeset(cubeedge(c,i,u[R[i]],u[C[i]]),u[D[i]],nv[i]); } } } int CalcHeight(int x,int y,int tz,int ix,int iy,int dir) { int z=tz-1; int height=0; int d = dimension(dir); // int dc = dimcoord(dir); int currCubeHeight=0; while(z>=0) { cube &c = blockcube(x,y,z,sel,sel.grid); if(isempty(c)) break; ivec v = getcubevector2(c,dir,ix,iy); if(v[R[d]]!=0 || v[C[d]]!=0) { // If there is an offset in this point, then we use the opposite vertex to calculate the height // as it has been probably moved to simulate another polygon. v = getcubevector2(c,dir^1,ix,iy); if(v[d]>0) height=currCubeHeight+v[d]; } else if(8-v[d]>0) { height=currCubeHeight+(8-v[d]); } currCubeHeight+=8; z--; } return height; } void SetHeight(int x,int y,int tz,int dir,int h00,int h01,int h10,int h11) { //char temp[256]; //sprintf(temp,"Set Height %d %d %d %d %d {%d %d %d %d} %d\n",x,y,tz,ix,iy,h00,h01,h10,h11,d);OutputDebugString(temp); int d = dimension(dir); int dc = dimcoord(dir); // int or_x=R[d]; // int or_y=C[d]; int or_z=D[d]; int z=tz-1; int currHeight=0; int h[2][2]={{h00,h01},{h10,h11}}; while(z>=0) { cube &c = blockcube(x,y,z,sel,sel.grid); if(h00>currHeight || h11>currHeight || h10>currHeight || h01>currHeight) { solidfaces(c); if(uselasttex) { int tex = DEFAULT_GEOM; extern int curtexindex; if(texmru.inrange(curtexindex)) tex = texmru[curtexindex]; loopi(6) c.texture[i] = tex; } if(h00 move the vertex inside to match the slope if(rh<0) { int joinCount=0; int highX,highY; bool bJoinToOppositeX=(h[useX^1][iy]/8)>(h[useX][iy]/8); bool bJoinToOppositeY=(h[useX][iy^1]/8)>(h[useX][iy]/8); bool bJoinToOpposite=(h[useX^1][iy^1]/8)>(h[useX][iy]/8); if(bJoinToOppositeX || bJoinToOppositeY) { if(bJoinToOppositeX && bJoinToOppositeY) { joinCount=2; } else { joinCount=1; if(bJoinToOppositeX) { highX=useX^1;highY=iy; } else { highX=useX;highY=iy^1; } } } else if(bJoinToOpposite) { highX=useX^1;highY=iy^1;joinCount=1; } if(joinCount==1) { if(h[highX][highY]>=currHeight) { int offsetX=-1; int offsetY=-1; int thisOffsetX = (int)(float(8*(-rh))/(h[highX][highY]-h[useX][iy])); if(highX != useX) offsetX = thisOffsetX; else offsetX = 0; if(highY != iy) offsetY = thisOffsetX; else offsetY = 0; setcubevector2(c,dir,ix,iy,offsetX,offsetY,0); setcubevector2(c,dir^1,ix,iy,offsetX,offsetY,0); if(dc == 0) highX = 1-highX; if(iCountPointsBelow!=3 && (bJoinToOppositeX || bJoinToOppositeY)) { cube &c2 = blockcube(x,y,z+1,sel,sel.grid); int hOffsetX = highX==ix?offsetX:8-offsetX; int hOffsetY = highY==iy?offsetY:8-offsetY; // we use the top of the cube to make the slope, the part of the cube // under the top block is not visible so the gap won't be noticed setcubevector2(c2,dir,highX,highY,hOffsetX,hOffsetY,0); } else { // We use the lateral of the cube to make the slope. cube &c2 = blockcube(x,y,z+1,sel,sel.grid); ivec currV = getcubevector2(c2,dir,ix,iy); // Move the top to the first visible point setcubevector2(c2,dir,ix,iy,offsetX,offsetY,0); // move the bottom to the end of the slope setcubevector2(c2,dir^1,ix,iy,currV[R[d]],currV[C[d]],8-currV[D[d]]); } } else { setcubevector2(c,dir,ix,iy,8,8,0); setcubevector2(c,dir^1,ix,iy,8,8,0); } } else if(joinCount==2 && (h[useX^1][iy]>currHeight || h[useX][iy^1]>currHeight)) { int thisOffsetX1 = (int)(float(8*(-rh))/(h[useX^1][iy]-h[useX][iy])); int thisOffsetX2 = (int)(float(8*(-rh))/(h[useX][iy^1]-h[useX][iy])); setcubevector2(c,dir,ix,iy,thisOffsetX1,0,0); setcubevector2(c,dir^1,ix,iy,thisOffsetX1,0,0); // calculate the common face for the vertex at ix,iy^1 int newdir=(dir+4)%6; int fy=ix; int fx=0; if((iy&1)==1) newdir^=1; if(dc) setcubevector2(c,newdir,fx,fy,0,0,8-thisOffsetX2); else setcubevector2(c,newdir,fx,fy,0,0,thisOffsetX2); cube &c2 = blockcube(x,y,z+1,sel,sel.grid); int currZ = getcubevector2(c2,dir,ix,iy)[d]; setcubevector2(c2,dir,ix,iy,thisOffsetX1,0,0); setcubevector2(c2,dir,ix,iy^1,0,8-thisOffsetX2,0); setcubevector2(c2,dir^1,ix,iy,0,0,8-currZ); } } ivec v2(d, ix, iy, dc); edgeset(cubeedge(c, or_z, v2[R[or_z]], v2[C[or_z]]), v2[D[or_z]], newHeight); } } } } else emptyfaces(c); currHeight+=8; z--; } } int *getselectionheight(selinfo &sel,int *buffer) { int d = dimension(sel.orient); int dc = dimcoord(sel.orient); int *heightSelection=buffer==NULL?new int[((sel.cxs+2)*(sel.cys+2))/4]:buffer; int ix0=!dc; int iy0=0; int ix1=dc; int iy1=1; int or_x=R[d]; int or_y=C[d]; int or_z=D[d]; int tx=sel.s[or_x]; int ty=sel.s[or_y]; int tz=sel.s[or_z]; for(int y=0;ysel.s[d]*8 || h2>sel.s[d]*8) { sel.s[d]++; if(!dc) sel.o[d] -= sel.grid; changed = true; } // expand selection if the blocks schrank out of it if(h1<0 || h2<0) { sel.s[d]++; if(dc) sel.o[d] += sel.grid*seldir; changed = true; } return changed; } void modifyGeometry(int dir, int mode, selinfo &sel) { int d = dimension(sel.orient); int dc = dimcoord(sel.orient); int seldir = dc ? -dir : dir; // float highest=8; int cornerX = (sel.corner&1 ? 1 : 0); int cornerY = (sel.corner&2 ? 1 : 0); int or_x=R[d]; int or_y=C[d]; int or_z=D[d]; int tx=sel.s[or_x]; int ty=sel.s[or_y]; int tz=sel.s[or_z]; ivec curprec(cur); curprec.sub(sel.o); int curprec_x=2*(curprec[or_x]/sel.grid)+cornerX; int curprec_y=2*(curprec[or_y]/sel.grid)+cornerY; if(sel.cxs>2 || sel.cys>2) // At least two cubes are selected { int clickedEdge=0; int selectedCorner=-1; if(sel.cxs>2 || (curprec_y!=0 && curprec_y!=sel.cys-1)) { if(curprec_x==0) clickedEdge=4; else if(curprec_x==sel.cxs-1) clickedEdge=5; } if(sel.cys>2 || clickedEdge==0) { if(curprec_y==0) clickedEdge=2; else if(curprec_y==sel.cys-1) clickedEdge=3; } if(curprec_y==0 || curprec_y==sel.cys-1) { if(curprec_x==0) selectedCorner=0; else if(curprec_x==sel.cxs-1) selectedCorner=1; if(curprec_y==sel.cys-1 && selectedCorner!=-1) selectedCorner+=2; } if(!dc && (clickedEdge&4)) clickedEdge^=1; if(!dc && (selectedCorner!=-1)) selectedCorner^=1; // Orientation holds the value of the selected edge: // // 3 // 2-------3 // ^ | | | // | | | | // | +---+---+ // | 4 | | | 5 // | | | | // | 0-------1 // y 2 // x ---------> // pullPushGeometry: // 0 : Slope // 1 : Tube // 2 : Ellipsoid // 3 : Stairs // 4 : Pyramid corner // 5 : Peak if(selectedCorner!=-1 || clickedEdge!=0) { int *heightSelection=NULL; switch(pullPushGeometry) { case 0: // Slope { int heightA=0,heightB=0; bool bSelectionChanged=false; int count=0; do { heightSelection=getselectionheight(sel,heightSelection); if(clickedEdge&2) { heightA=heightSelection[0]; heightB=heightSelection[(tx+1)*ty]; } else { heightA=heightSelection[0]; heightB=heightSelection[tx]; } if(clickedEdge&1) heightB-=dir; else heightA-=dir; bSelectionChanged=CheckSelection(heightA,heightB,d,dc,seldir); tz=sel.s[or_z]; count++; } while(bSelectionChanged && count<5); float h_part=((float)(heightB-heightA))/((clickedEdge&2)?ty:tx); for(int y=0;yo[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, ""); #if 0 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, ""); #endif 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"); 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.8.2+dfsg/src/engine/rendersky.cpp0000644000175000017500000004560012045412564021466 0ustar bofh80bofh80#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) domeverts[domenumverts++] = domevert(vec(sincos360[(360*i)/hres], 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.8.2+dfsg/src/engine/skelmodel.h0000644000175000017500000023445712045412564021116 0ustar bofh80bofh80VARP(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 = lastvbuf; } } 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 modelcommands commands; 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("%s: could not find animation %s", MDL::dir, 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()) this->modelcommand(loadpart, "load", "ssf"); this->modelcommand(settag, "tag", "ssffffff"); this->modelcommand(setpitch, "pitch", "sffff"); this->modelcommand(setpitchtarget, "pitchtarget", "ssiff"); this->modelcommand(setpitchcorrect, "pitchcorrect", "ssfff"); if(MDL::animated()) { this->modelcommand(setanim, "anim", "ssfiii"); this->modelcommand(setanimpart, "animpart", "s"); this->modelcommand(setadjust, "adjust", "sffffff"); } } }; sandboxgamemaker-2.8.2+dfsg/src/engine/sound.cpp0000644000175000017500000005103112045412564020603 0ustar bofh80bofh80// 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; }; struct soundconfig { int slots, numslots; int maxuses; bool hasslot(const soundslot *p, const vector &v) const { return p >= v.getbuf() + slots && p < v.getbuf() + slots+numslots && slots+numslots < v.length(); } int chooseslot() const { return numslots > 1 ? slots + rnd(numslots) : slots; } }; 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", ".mid", ".flac", ".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"); static hashtable samples; static vector gameslots, mapslots; static vector gamesounds, mapsounds; static int findsound(const char *name, int vol, vector &sounds, vector &slots) { loopv(sounds) { soundconfig &s = sounds[i]; loopj(s.numslots) { soundslot &c = slots[s.slots+j]; if(!strcmp(c.sample->name, name) && (!vol || c.volume==vol)) return i; } } return -1; } static int addslot(const char *name, int vol, vector &slots) { soundsample *s = samples.access(name); if(!s) { char *n = newstring(name); s = &samples[n]; s->name = n; s->chunk = NULL; } soundslot *oldslots = slots.getbuf(); int oldlen = slots.length(); soundslot &slot = slots.add(); // soundslots.add() may relocate slot pointers if(slots.getbuf() != oldslots) loopv(channels) { soundchannel &chan = channels[i]; if(chan.inuse && chan.slot >= oldslots && chan.slot < &oldslots[oldlen]) chan.slot = &slots[chan.slot - oldslots]; } slot.sample = s; slot.volume = vol ? vol : 100; return oldlen; } static int addsound(const char *name, int vol, int maxuses, vector &sounds, vector &slots) { soundconfig &s = sounds.add(); s.slots = addslot(name, vol, slots); s.numslots = 1; s.maxuses = maxuses; return sounds.length()-1; } void registersound(char *name, int *vol) { intret(addsound(name, *vol, 0, gamesounds, gameslots)); } COMMAND(registersound, "si"); void mapsound(char *name, int *vol, int *maxuses) { intret(addsound(name, *vol, *maxuses < 0 ? 0 : max(1, *maxuses), mapsounds, mapslots)); } COMMAND(mapsound, "sii"); void altsound(char *name, int *vol) { if(gamesounds.empty()) return; addslot(name, *vol, gameslots); gamesounds.last().numslots++; } COMMAND(altsound, "si"); void altmapsound(char *name, int *vol) { if(mapsounds.empty()) return; addslot(name, *vol, mapslots); mapsounds.last().numslots++; } COMMAND(altmapsound, "si"); 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(); gameslots.setsize(0); gamesounds.setsize(0); mapslots.setsize(0); mapsounds.setsize(0); samples.clear(); } void clearmapsounds() { loopv(channels) if(channels[i].inuse && channels[i].ent) { Mix_HaltChannel(i); freechannel(i); } mapslots.setsize(0); 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 &slots = ent ? mapslots : gameslots; vector &sounds = ent ? mapsounds : gamesounds; if(!sounds.inrange(n)) { conoutf(CON_WARN, "unregistered sound: %d", n); return -1; } soundconfig &config = 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 && config.hasslot(channels[chanid].slot, slots)) { Mix_HaltChannel(chanid); freechannel(chanid); } return -1; } } if(chanid < 0) { if(config.maxuses) { int uses = 0; loopv(channels) if(channels[i].inuse && config.hasslot(channels[i].slot, slots) && ++uses >= config.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(channels.inrange(chanid)) { soundchannel &chan = channels[chanid]; if(chan.inuse && config.hasslot(chan.slot, slots)) { if(loc) chan.loc = *loc; else if(chan.hasloc()) chan.clearloc(); return chanid; } } if(fade < 0) return -1; soundslot &slot = slots[config.chooseslot()]; if(!slot.sample->chunk) { if(!slot.sample->name[0]) return -1; const char *exts[] = { "", ".ogg", ".flac", ".wav" }; 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(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) || !gamesounds[n].hasslot(channels[chanid].slot, gameslots)) 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, gameslots); if(id < 0) id = addsound(s, vol, 0, gamesounds, gameslots); 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", mapslots[mapsounds[*id].slots].sample->name); result(s);} ); void writemapsounds(stream *f) { loopv(mapsounds) { soundconfig &c = mapsounds[i]; loopj(c.numslots) { soundslot &s = mapslots[c.slots + j]; if(!j) f->printf("mapsound %s %d %d // %d\n", escapestring(s.sample->name), s.volume, c.maxuses, i); else f->printf("altmapsound %s %d\n", escapestring(s.sample->name), s.volume); } } } 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.8.2+dfsg/src/engine/serverbrowser.cpp0000644000175000017500000004635512045412564022402 0ustar bofh80bofh80// 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, 0, 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 sortservers() { servers.sort(serverinfo::compare); } COMMAND(sortservers, ""); VARP(autosortservers, 0, 1, 1); VARP(autoupdateservers, 0, 1, 1); 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(); if(autosortservers) sortservers(); } serverinfo *selectedserver = NULL; ICOMMAND(numservers, "", (), intret(servers.length())) ICOMMAND(selectserver, "i", (int *i), if(selectedserver) return; if(servers.inrange(*i)) selectedserver = servers[*i]; ) ICOMMAND(serverinfo, "ii", (int *i, int *n), refreshservers(); if(!servers.inrange(*i)) { result(""); return; } serverinfo &si = *servers[*i]; switch(*n) { case 0: result(si.name); return; case 1: intret(si.port); return; case 2: if(si.address.host == ENET_HOST_ANY) result("[unknown host]"); else if(si.ping == serverinfo::WAITING) result("[waiting for response]"); else result(si.sdesc); return; case 3: result(si.map); return; case 4: intret(si.ping); return; case 5: intret(si.numplayers); return; default: result(""); return; } ) ICOMMAND(serverauxinfo, "ii", (int *i, int *n), refreshservers(); if(servers.inrange(*i) && servers[*i]->attr.inrange(*n)) intret(servers[*i]->attr[*n]); else intret(0); ) void connectselected() { if(!selectedserver) return; connectserv(selectedserver->name, selectedserver->port, selectedserver->password); selectedserver = NULL; } COMMAND(connectselected, ""); void clearservers(bool full = false) { resolverclear(); if(full) servers.deletecontents(); else loopvrev(servers) if(!servers[i]->keep) delete servers.remove(i); selectedserver = NULL; } #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); } bool updatedservers = false; void updatefrommaster() { vector data; retrieveservers(data); if(data.empty()) conoutf("master server not replying"); else { clearservers(); execute(data.getbuf()); } refreshservers(); updatedservers = true; } void initservers() { selectedserver = NULL; if(autoupdateservers && !updatedservers) updatefrommaster(); } 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, ""); COMMAND(initservers, ""); void writeservercfg() { if(!game::savedservers()) return; stream *f = openutf8file(path(game::savedservers(), true), "w"); 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", escapeid(s->name), s->port, escapestring(s->password)); else f->printf("keepserver %s %d\n", escapeid(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", escapeid(s->name), s->port, escapestring(s->password)); else f->printf("addserver %s %d\n", escapeid(s->name), s->port); } } delete f; } sandboxgamemaker-2.8.2+dfsg/src/engine/ragdoll.h0000644000175000017500000003513512045412564020553 0ustar bofh80bofh80struct 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.8.2+dfsg/src/engine/depthfx.h0000644000175000017500000001473512045412564020574 0ustar bofh80bofh80// 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< 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, ALPHA = 1<<11, FLAGS = 0xFF00 }; 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.8.2+dfsg/src/engine/movie.cpp0000644000175000017500000012615312045412564020602 0ustar bofh80bofh80// 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.8.2+dfsg/src/engine/md3.h0000644000175000017500000001601212045412564017603 0ustar bofh80bofh80struct 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.8.2+dfsg/src/engine/blend.cpp0000644000175000017500000005560412045412564020551 0ustar bofh80bofh80#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*h]; uchar *dst = buf, *src = data; loopi(h) { loopj(w) { *dst++ = 255 - *src; *dst++ = 255 - *src++; } } createtexture(tex, w, h, buf, 3, 1, GL_LUMINANCE_ALPHA); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); GLfloat border[4] = { 0, 0, 0, 0 }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border); 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, ""); ICOMMAND(numblendbrush, "", (), intret(brushes.length())); 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) << BM_SCALE, y1 = (int)floor(clamp(worldpos.y, 0.0f, float(worldsize))/(1<h) << BM_SCALE, x2 = x1 + (brush->w << BM_SCALE), y2 = y1 + (brush->h << 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.8.2+dfsg/src/engine/material.cpp0000644000175000017500000010407312045412564021256 0ustar bofh80bofh80#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); } }; static float wfwave, wfscroll, wfxscale, wfyscale; static void renderwaterfall(const materialsurface &m, 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, 2, GL_FLOAT); varray::begin(GL_QUADS); } float x = m.o.x, y = m.o.y, zmin = m.o.z, zmax = zmin; if(m.ends&1) zmin += -WATER_OFFSET-WATER_AMPLITUDE; if(m.ends&2) zmax += wfwave; int csize = m.csize, rsize = m.rsize; #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: v0 v1 v2 v3 break; #undef GENFACEVERTX #define GENFACEVERTX(orient, vert, mx,my,mz, sx,sy,sz) \ { \ vec v(mx sx, my sy, mz sz); \ varray::attrib(v.x, v.y, v.z); \ GENFACENORMAL \ varray::attrib(wfxscale*v.y, wfyscale*(v.z+wfscroll)); \ } #undef GENFACEVERTY #define GENFACEVERTY(orient, vert, mx,my,mz, sx,sy,sz) \ { \ vec v(mx sx, my sy, mz sz); \ varray::attrib(v.x, v.y, v.z); \ GENFACENORMAL \ varray::attrib(wfxscale*v.x, wfyscale*(v.z+wfscroll)); \ } #define GENFACENORMAL varray::attrib(n.x, n.y, n.z); if(normal) { vec n = *normal; switch(m.orient) { GENFACEVERTSXY(x, x, y, y, zmin, zmax, /**/, + csize, /**/, + rsize, + offset, - offset) } } #undef GENFACENORMAL #define GENFACENORMAL else switch(m.orient) { GENFACEVERTSXY(x, x, y, y, zmin, zmax, /**/, + csize, /**/, + rsize, + offset, - offset) } #undef GENFACENORMAL #undef GENFACEORIENT #undef GENFACEVERTX #define GENFACEVERTX(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv) #undef GENFACEVERTY #define GENFACEVERTY(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv) } static void drawmaterial(const materialsurface &m, float offset) { if(varray::data.empty()) { varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); varray::begin(GL_QUADS); } float x = m.o.x, y = m.o.y, z = m.o.z, csize = m.csize, rsize = m.rsize; switch(m.orient) { #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: v0 v1 v2 v3 break; #define GENFACEVERT(orient, vert, mx,my,mz, sx,sy,sz) \ varray::attrib(mx sx, my sy, mz sz); GENFACEVERTS(x, x, y, y, z, z, /**/, + csize, /**/, + rsize, + offset, - offset) #undef GENFACEORIENT #undef GENFACEVERT } } 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}, {"pain", MAT_PAIN}, {"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_PAIN, 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_PAIN: glColor3ub(70, 30, 10); break; // brown case MAT_ALPHA: glColor3ub(85, 0, 85); break; // pink } } drawmaterial(m, -0.1f); } xtraverts += varray::end(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); disablepolygonoffset(GL_POLYGON_OFFSET_LINE); } VARP(glassenv, 0, 1, 1); static void drawglass(const materialsurface &m, 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); } #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: v0 v1 v2 v3 break; #define GENFACEVERT(orient, vert, mx,my,mz, sx,sy,sz) \ { \ vec v(mx sx, my sy, mz sz); \ vec reflect = vec(v).sub(camera1->o); \ reflect[dimension(orient)] = -reflect[dimension(orient)]; \ varray::attrib(v.x, v.y, v.z); \ GENFACENORMAL \ varray::attrib(reflect.x, reflect.y, reflect.z); \ } #define GENFACENORMAL varray::attrib(n.x, n.y, n.z); float x = m.o.x, y = m.o.y, z = m.o.z, csize = m.csize, rsize = m.rsize; if(normal) { vec n = *normal; switch(m.orient) { GENFACEVERTS(x, x, y, y, z, z, /**/, + csize, /**/, + rsize, + offset, - offset) } } #undef GENFACENORMAL #define GENFACENORMAL else switch(m.orient) { GENFACEVERTS(x, x, y, y, z, z, /**/, + csize, /**/, + rsize, + offset, - offset) } #undef GENFACENORMAL #undef GENFACEORIENT #undef GENFACEVERT } 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_PAIN: glColor3ub( 96, 160, 255); break; // brown case MAT_ALPHA: glColor3ub( 0, 255, 0); break; // pink default: continue; } lastmat = m.material; } drawmaterial(m, -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); float angle = fmod(float(lastmillis/(renderpath!=R_FIXEDFUNCTION ? 600.0f : 300.0f)/(2*M_PI)), 1.0f), s = angle - int(angle) - 0.5f; s *= 8 - fabs(s)*16; wfwave = vertwater ? WATER_AMPLITUDE*s-WATER_OFFSET : -WATER_OFFSET; wfscroll = 16.0f*lastmillis/1000.0f; wfxscale = TEX_SCALE/(wslot.sts[1].t->xs*wslot.scale); wfyscale = TEX_SCALE/(wslot.sts[1].t->ys*wslot.scale); } 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(m.orient!=O_TOP) { float angle = fmod(float(lastmillis/2000.0f/(2*M_PI)), 1.0f), s = angle - int(angle) - 0.5f; s *= 8 - fabs(s)*16; wfwave = vertwater ? WATER_AMPLITUDE*s-WATER_OFFSET : -WATER_OFFSET; wfscroll = 16.0f*lastmillis/3000.0f; wfxscale = TEX_SCALE/(lslot.sts[1].t->xs*lslot.scale); wfyscale = TEX_SCALE/(lslot.sts[1].t->ys*lslot.scale); } 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, 0.1f, 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, 0.1f); break; case MAT_GLASS: if(m.envmap!=EMID_NONE && glassenv) drawglass(m, 0.1f, renderpath!=R_FIXEDFUNCTION ? &normals[m.orient] : NULL); else drawmaterial(m, 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.8.2+dfsg/src/engine/console.cpp0000644000175000017500000006053712045412564021130 0ustar bofh80bofh80// 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; enum { CF_COMPLETE = 1<<0, CF_EXECUTE = 1<<1 }; int commandflags = 0, 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(iscubespace(*action)) action++; int len = strlen(action); while(len>0 && iscubespace(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, char *flags = 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); commandflags = 0; if(flags) while(*flags) switch(*flags++) { case 'c': commandflags |= CF_COMPLETE; break; case 'x': commandflags |= CF_EXECUTE; break; case 's': commandflags |= CF_COMPLETE|CF_EXECUTE; break; } else if(init) commandflags |= CF_COMPLETE|CF_EXECUTE; } ICOMMAND(saycommand, "C", (char *init), inputcommand(init)); COMMAND(inputcommand, "ssss"); #if !defined(WIN32) && !defined(__APPLE__) #include #include #endif void pasteconsole() { #ifdef WIN32 UINT fmt = CF_UNICODETEXT; if(!IsClipboardFormatAvailable(fmt)) { fmt = CF_TEXT; if(!IsClipboardFormatAvailable(fmt)) return; } if(!OpenClipboard(NULL)) return; HANDLE h = GetClipboardData(fmt); size_t commandlen = strlen(commandbuf); int cblen = int(GlobalSize(h)), decoded = 0; ushort *cb = (ushort *)GlobalLock(h); switch(fmt) { case CF_UNICODETEXT: decoded = min(int(sizeof(commandbuf)-1-commandlen), cblen/2); loopi(decoded) commandbuf[commandlen++] = uni2cube(cb[i]); break; case CF_TEXT: decoded = min(int(sizeof(commandbuf)-1-commandlen), cblen); memcpy(&commandbuf[commandlen], cb, decoded); break; } commandbuf[commandlen + decoded] = '\0'; GlobalUnlock(cb); CloseClipboard(); #elif defined(__APPLE__) extern char *mac_pasteconsole(int *cblen); int cblen = 0; uchar *cb = (uchar *)mac_pasteconsole(&cblen); if(!cb) return; size_t commandlen = strlen(commandbuf); int decoded = decodeutf8((uchar *)&commandbuf[commandlen], int(sizeof(commandbuf)-1-commandlen), cb, cblen); commandbuf[commandlen + decoded] = '\0'; free(cb); #else SDL_SysWMinfo wminfo; SDL_VERSION(&wminfo.version); wminfo.subsystem = SDL_SYSWM_X11; if(!SDL_GetWMInfo(&wminfo)) return; int cbsize; uchar *cb = (uchar *)XFetchBytes(wminfo.info.x11.display, &cbsize); if(!cb || !cbsize) return; size_t commandlen = strlen(commandbuf); for(uchar *cbline = cb, *cbend; commandlen + 1 < sizeof(commandbuf) && cbline < &cb[cbsize]; cbline = cbend + 1) { cbend = (uchar *)memchr(cbline, '\0', &cb[cbsize] - cbline); if(!cbend) cbend = &cb[cbsize]; int cblen = int(cbend-cbline), commandmax = int(sizeof(commandbuf)-1-commandlen); loopi(cblen) if((cbline[i]&0xC0) == 0x80) { commandlen += decodeutf8((uchar *)&commandbuf[commandlen], commandmax, cbline, cblen); goto nextline; } cblen = min(cblen, commandmax); loopi(cblen) commandbuf[commandlen++] = uni2cube(*cbline++); nextline: commandbuf[commandlen] = '\n'; if(commandlen + 1 < sizeof(commandbuf) && cbend < &cb[cbsize]) ++commandlen; commandbuf[commandlen] = '\0'; } XFree(cb); #endif } struct hline { char *buf, *action, *prompt; int flags; hline() : buf(NULL), action(NULL), prompt(NULL), flags(0) {} ~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); commandflags = flags; } bool shouldsave() { return strcmp(commandbuf, buf) || (commandaction ? !action || strcmp(commandaction, action) : action!=NULL) || (commandprompt ? !prompt || strcmp(commandprompt, prompt) : prompt!=NULL) || commandflags != flags; } void save() { buf = newstring(commandbuf); if(commandaction) action = newstring(commandaction); if(commandprompt) prompt = newstring(commandprompt); flags = commandflags; } void run() { if(flags&CF_EXECUTE && buf[0]=='/') execute(buf+1); else if(action) { alias("commandbuf", buf); execute(action); } 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; if(!UI::mainmenu) { 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(commandflags&CF_COMPLETE) { complete(commandbuf, commandflags&CF_EXECUTE ? "/" : NULL); 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); } } } 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 else if(!UI::keypress(code, isdown, cooked)) // UI mouse button intercept { 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]) { if(validateblock(km.actions[j])) f->printf("%s %s [%s]\n", cmds[j], escapestring(km.name), km.actions[j]); else f->printf("%s %s %s\n", cmds[j], escapestring(km.name), escapestring(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, const char *cmdprefix) { int cmdlen = 0; if(cmdprefix) { cmdlen = strlen(cmdprefix); if(strncmp(s, cmdprefix, cmdlen)) { defformatstring(cmd)("%s%s", cmdprefix, s); copystring(s, cmd); } } if(!s[cmdlen]) return; if(!completesize) { completesize = (int)strlen(&s[cmdlen]); lastcomplete[0] = '\0'; } filesval *f = NULL; if(completesize) { char *end = strchr(&s[cmdlen], ' '); if(end) { string command; copystring(command, &s[cmdlen], min(size_t(end-&s[cmdlen]+1), sizeof(command))); filesval **hasfiles = completions.access(command); if(hasfiles) f = *hasfiles; } } const char *nextcomplete = NULL; string prefix; if(f) // complete using filenames { int commandsize = strchr(&s[cmdlen], ' ')+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+cmdlen-commandsize)==0 && strcmp(f->files[i], lastcomplete) > 0 && (!nextcomplete || strcmp(f->files[i], nextcomplete) < 0)) nextcomplete = f->files[i]; } } else // complete using command names { if(cmdprefix) copystring(prefix, cmdprefix); else prefix[0] = '\0'; enumerate(idents, ident, id, if(strncmp(id.name, &s[cmdlen], completesize)==0 && strcmp(id.name, lastcomplete) > 0 && (!nextcomplete || strcmp(id.name, nextcomplete) < 0)) nextcomplete = id.name; ); } if(nextcomplete) { formatstring(s)("%s%s", prefix, 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) { if(validateblock(v->dir)) f->printf("listcomplete %s [%s]\n", escapeid(k), v->dir); else f->printf("listcomplete %s %s\n", escapeid(k), escapestring(v->dir)); } else f->printf("complete %s %s %s\n", escapeid(k), escapestring(v->dir), escapestring(v->ext ? v->ext : "*")); } } ICOMMAND(getgame, "", (), result(game::gameident());); sandboxgamemaker-2.8.2+dfsg/src/engine/dynlight.cpp0000644000175000017500000001571012045412564021301 0ustar bofh80bofh80#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.8.2+dfsg/src/engine/world.cpp0000644000175000017500000011266212045412564020612 0ustar bofh80bofh80// 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); ICOMMAND(getcurmap, "", (), result(game::getclientmap())) 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(15) { vec p(e.o); const vec2 &sc = sincos360[i*(360/15)]; p[axis>=2 ? 1 : 0] += radius*sc.x; p[axis>=1 ? 2 : 1] += radius*sc.y; 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 = clamp(int(e.attr[0]), 1, 89); 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, ""); static int keepents = 0; extentity *newentity(bool local, const vec &o, int type, int *attrs, int &idx) { vector &ents = entities::getents(); if(local) { idx = -1; for(int i = keepents; i < ents.length(); i++) if(ents[i]->type == ET_EMPTY) { idx = i; break; } if(idx < 0 && ents.length() >= MAXENTS) { conoutf("too many entities"); return NULL; } } else while(ents.length() < idx) ents.add(entities::newentity())->type = ET_EMPTY; 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); } if(ents.inrange(idx)) { entities::deleteentity(ents[idx]); ents[idx] = &e; } else { idx = ents.length(); ents.add(&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) { int idx; extentity *t = newentity(true, player->o, type, attrs, idx); if(!t) return; dropentity(*t); t->type = ET_EMPTY; enttoggle(idx); makeundoent(); entedit(idx, 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(); float m = float(sel.grid)/float(entcopygrid); loopv(entcopybuf) { entity &c = entcopybuf[i]; vec o(c.o); o.mul(m).add(sel.o.tovec()); int idx; extentity *e = newentity(true, o, ET_EMPTY, c.attr.getbuf(), idx); if(!e) continue; entadd(idx); keepents = max(keepents, idx + 1); } keepents = 0; 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) { 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; if(type != ET_EMPTY) 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 && executebool(body))); 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, ""); void enttype(char *type, int *numargs) { if(*numargs >= 1) { int typeidx = findtype(type); if(typeidx != ET_EMPTY) groupedit( e.type = typeidx; int numattrs = getattrnum(typeidx); while(e.attr.length() < numattrs) e.attr.add(0); while(e.attr.length() > numattrs) e.attr.pop(); ); } else entfocus(efocus, { result(entities::entname(e.type)); }) } void entattr(int *attr, int *val, int *numargs) { if(*numargs >= 2) { groupedit( if(e.attr.inrange(*attr)) e.attr[*attr] = *val; ); } else entfocus(efocus, { if(e.attr.inrange(*attr)) intret(e.attr[*attr]); }); } COMMAND(enttype, "sN"); COMMAND(entattr, "iiN"); 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(); clearmapcrc(); 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); UI::clearmainmenu(); 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; vector &ents = entities::getents(); if(ents.length()<=i) { extentity *e = newentity(local, o, type, attrs, i); if(!e) return; addentity(i); attachentity(*e); } else { extentity &e = *ents[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.8.2+dfsg/src/engine/ui.cpp0000644000175000017500000024652712051200222020067 0ustar bofh80bofh80#include "engine.h" #include "textedit.h" namespace UI { struct delayedupdate { enum { INT, FLOAT, STRING, ACTION } type; ident *id; union { int i; float f; char *s; uint *c; } val; delayedupdate() : type(ACTION), id(NULL) { val.s = NULL; } ~delayedupdate() { if(type == STRING) delete[] val.s; if(type == ACTION) freecode(val.c); } void schedule(uint *code) { type = ACTION; val.c = code; keepcode(code); } 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.c) execute(val.c); } 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 vector updatelater; template static void updateval(char *var, T val, uint *onchange) { ident *id = writeident(var); updatelater.add().schedule(id, val); updatelater.add().schedule(onchange); } ICOMMAND(updateval, "sse", (char *var, char *value, uint *onchange), { updateval(var, value, onchange); }); static int getval(char *var) { ident *id = readident(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 = readident(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 = readident(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 ""; } } struct Object; Object *selected = NULL, *hovering = NULL, *focused = NULL, *tooltip = NULL; float hoverx = 0, hovery = 0, selectx = 0, selecty = 0; float cursorx = 0.5f, cursory = 0.5f; 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 inline 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); } static inline void quadtri(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, ty + th); glVertex2f(x, y + h); glTexCoord2f(tx + tw, ty + th); glVertex2f(x + w, 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_BUTTON, TYPE_SCROLLER, TYPE_SCROLLBAR, TYPE_SCROLLBUTTON, TYPE_SLIDER, TYPE_SLIDERBUTTON, TYPE_IMAGE, TYPE_TAG, TYPE_WINDOW, TYPE_TEXTEDITOR, }; enum { ORIENT_HORIZ = 0, ORIENT_VERT, }; 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 bool hoverkey(int code, bool isdown, int cooked) { if(parent) return parent->hoverkey(code, isdown, cooked); 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; } virtual bool takesinput() const { return true; } 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 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(); } bool takesinput() const { loopchildrenrev(o, if(o->takesinput()) return true; ); return false; } }; World *world; 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; loopchildren(o, { o->x = offsetx; o->y = offsety; o->adjustlayout(offsetx, offsety, widths[column], heights[row]); offsetx += widths[column] + cspace; column = (column + 1) % columns; if(!column) { offsetx = 0; offsety += heights[row] + rspace; row++; } }); } }; 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) {} Object *target(float cx, float cy) { Object *o = Object::target(cx, cy); return o ? o : this; } 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 { uint *cond; Conditional(uint *cond) : cond(cond) { keepcode(cond); } ~Conditional() { freecode(cond); } int forks() const { return 2; } int choosefork() const { return execute(cond) ? 0 : 1; } }; struct Button : Object { uint *onselect; Object *tooltip; Button(uint *onselect) : onselect(onselect), tooltip(NULL) { keepcode(onselect); } ~Button() { freecode(onselect); delete tooltip; } int forks() const { return 3; } int choosefork() const { return isselected(this) ? 2 : (ishovering(this) ? 1 : 0); } Object *hover(float cx, float cy) { if(target(cx, cy)) { UI::tooltip = this->tooltip; return this; } return NULL; } Object *select(float cx, float cy) { return target(cx, cy) ? this : NULL; } void selected(float cx, float cy) { updatelater.add().schedule(onselect); } const int gettype() const { return TYPE_BUTTON; } }; struct ConditionalButton : Button { uint *cond; ConditionalButton(uint *cond, uint *onselect) : Button(onselect), cond(cond) { keepcode(cond); } ~ConditionalButton() { freecode(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 { uint *cond; float split; Toggle(uint *cond, uint *onselect, float split = 0) : Button(onselect), cond(cond), split(split) { keepcode(cond); } ~Toggle() { freecode(cond); } int forks() const { return 4; } int choosefork() const { return (execute(cond) ? 2 : 0) + (ishovering(this) ? 1 : 0); } 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; bool canscroll; 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) { canscroll = false; return NULL; } canscroll = true; Object *o = Object::hover(cx + offsetx, cy + offsety); return o ? o : this; } Object *select(float cx, float cy) { if(cx + offsetx >= virtw || cy + offsety >= virth) return NULL; return Object::select(cx + offsetx, cy + offsety); } bool hoverkey(int code, bool isdown, int cooked); 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; } virtual int getorient() const =0; Object *hover(float cx, float cy) { Object *o = Object::hover(cx, cy); if(o) return o; return this; } 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) {} bool hoverkey(int code, bool isdown, int cooked) { if(code != -4 && code != -5) return Object::hoverkey(code, isdown, cooked); if(!isdown) return false; Scroller *scroller = (Scroller *) findsibling(TYPE_SCROLLER, NULL); if(!scroller || !scroller->canscroll) return false; float adjust = (code == -4 ? -.2 : .2) * arrowspeed; if(getorient() == ORIENT_VERT) scroller->addvscroll(adjust); else scroller->addhscroll(adjust); return true; } 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; }; bool Scroller::hoverkey(int code, bool isdown, int cooked) { if(code != -4 && code != -5) return Object::hoverkey(code, isdown, cooked); if(!canscroll || !isdown) return false; ScrollBar *slider = (ScrollBar *) findsibling(TYPE_SCROLLBAR, NULL); if(!slider) return false;; float adjust = (code == -4 ? -.2 : .2) * slider->arrowspeed; if(slider->getorient() == ORIENT_VERT) addvscroll(adjust); else addhscroll(adjust); return true; } 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; } int getorient() const { return ORIENT_HORIZ; } 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; } int getorient() const { return ORIENT_VERT; } 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); } }; struct Slider : Object { char *var; float vmin, vmax; uint *onchange; float arrowsize; float stepsize; int steptime; int laststep; int arrowdir; Slider(char *varname, float min = 0, float max = 0, uint *onchange = NULL, float arrowsize = 0, float stepsize = 1, int steptime = 1000) : var(newstring(varname)), vmin(min), vmax(max), onchange(onchange), arrowsize(arrowsize), stepsize(stepsize), steptime(steptime), laststep(0), arrowdir(0) { keepcode(onchange); ident *id = readident(varname); if(id && vmin == 0 && vmax == 0) { if(id->type == ID_VAR) { vmin = id->minval; vmax = id->maxval; } else if(id->type == ID_FVAR) { vmin = id->minvalf; vmax = id->maxvalf; } } } ~Slider() { freecode(onchange); delete[] var; } void dostep(int n) { int maxstep = fabs(vmax - vmin) / stepsize; int curstep = (getfval(var) - min(vmin, vmax)) / stepsize; int newstep = clamp(curstep + n, 0, maxstep); updateval(var, min(vmax, vmin) + newstep * stepsize, onchange); } void setstep(int n) { int steps = fabs(vmax - vmin) / stepsize; int newstep = clamp(n, 0, steps); updateval(var, min(vmax, vmin) + newstep * stepsize, onchange); } bool hoverkey(int code, bool isdown, int cooked) { switch(code) { case SDLK_UP: case SDLK_LEFT: if(isdown) dostep(-1); return true; case -4: if(isdown) dostep(-3); return true; case SDLK_DOWN: case SDLK_RIGHT: if(isdown) dostep(1); return true; case -5: if(isdown) dostep(3); return true; } return Object::hoverkey(code, isdown, cooked); } 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 this; } 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() { if(laststep + steptime > totalmillis) return; laststep = totalmillis; dostep(arrowdir); } 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; } void layout() { float lastw = w, lasth = h; Object::layout(); if(isselected(this)) { w = lastw; h = lasth; } } const int gettype() const { return TYPE_SLIDERBUTTON; } }; struct HorizontalSlider : Slider { HorizontalSlider(char *varname, float vmin = 0, float vmax = 0, uint *onchange = NULL, float arrowsize = 0, float stepsize = 1, int steptime = 1000) : Slider(varname, vmin, vmax, onchange, arrowsize, stepsize, steptime) {} 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((cx - arrowsize - button->w / 2) / (w - 2 * arrowsize - button->w), 0.f, 1.f); int steps = fabs(vmax - vmin) / stepsize; int step = lroundf(steps * pos); setstep(step); } void adjustchildren() { SliderButton *button = (SliderButton *) findname(TYPE_SLIDERBUTTON, NULL, false); if(!button) return; int steps = fabs(vmax - vmin) / stepsize; int curstep = (getfval(var) - min(vmax, vmin)) / stepsize; float width = max(w - 2 *arrowsize, 0.0f); button->w = max(button->w, width / steps); button->x = arrowsize + (width - button->w) * curstep / steps; button->adjust &= ~ALIGN_HMASK; Slider::adjustchildren(); } void movebutton(Object *o, float fromx, float fromy, float tox, float toy) { scrollto(o->x + o->w / 2 + tox - fromx, o->y + toy); } }; struct VerticalSlider : Slider { VerticalSlider(char *varname, float vmin = 0, float vmax = 0, uint *onchange = NULL, float arrowsize = 0, float stepsize = 1, int steptime = 1000) : Slider(varname, vmin, vmax, onchange, arrowsize, stepsize, steptime) {} 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((cy - arrowsize - button->h / 2) / (h - 2 * arrowsize - button->h), 0.f, 1.f); int steps = (max(vmax, vmin) - min(vmax, vmin)) / stepsize; int step = lroundf(steps * pos); setstep(step); } void adjustchildren() { SliderButton *button = (SliderButton *) findname(TYPE_SLIDERBUTTON, NULL, false); if(!button) return; int steps = (max(vmax, vmin) - min(vmax, vmin)) / stepsize + 1; int curstep = (getfval(var) - min(vmax, vmin)) / stepsize; float height = max(h - 2 *arrowsize, 0.0f); button->h = max(button->h, height / steps); button->y = arrowsize + (height - button->h) * curstep / steps; button->adjust &= ~ALIGN_VMASK; Slider::adjustchildren(); } void movebutton(Object *o, float fromx, float fromy, float tox, float toy) { scrollto(o->x + o->h / 2 + 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) {} 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_TRIANGLE_STRIP); glVertex2f(sx, sy); glVertex2f(sx + w, sy); glVertex2f(sx, sy + h); glVertex2f(sx + w, 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_TRIANGLE_STRIP); quadtri(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_TRIANGLE_STRIP); quadtri(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); } }; struct TiledImage : Image { float tilew, tileh; TiledImage(Texture *tex, float tileh = 0, float tilew = 0,float minw = 0, float minh = 0) : Image(tex, minw, minh), tilew(tilew), tileh(tileh) {} Object *target(float cx, float cy) { Object *o = Object::target(cx, cy); if(o) return o; if(tex->bpp < 32) return this; float dx = fmod(cx, tilew), dy = fmod(cy, tileh); return checkalphamask(tex, dx/tilew, dy/tileh) ? this : NULL; } void draw(float sx, float sy) { glBindTexture(GL_TEXTURE_2D, tex->id); //we cannot use the built in OpenGL texture repeat with clamped textures. if(tex->clamp) { float dx = 0, dy = 0; glBegin(GL_QUADS); while(dx < w) { while(dy < h) { float dw = min(tilew, w - dx), dh = min(tileh, h - dy); quad(sx + dx, sy + dy, dw, dh, 0, 0, dw / tilew, dh / tileh); dy += tileh; } dy = 0; dx += tilew; } glEnd(); } else { glBegin(GL_TRIANGLE_STRIP); quadtri(sx, sy, w, h, 0, 0, w/tilew, h/tileh); 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; float wrap; vec color; Text(const char *str, float scale = 1, float wrap = -1, float r = 1, float g = 1, float b = 1) : str(newstring(str)), scale(scale), wrap(wrap), 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, -1, wrap <= 0 ? -1 : wrap/k); glColor3f(1, 1, 1); glPopMatrix(); Object::draw(sx, sy); } void layout() { Object::layout(); int tw, th; float k = drawscale(); text_bounds(str, tw, th, wrap <= 0 ? -1 : wrap/k); if(wrap <= 0) w = max(w, tw*k); else w = max(w, min(wrap, tw*k)); h = max(h, th*k); } }; struct EvalText : Object { uint *cmd; float scale; float wrap; vec color; EvalText(uint *cmd, float scale = 1, float wrap = -1, float r = 1, float g = 1, float b = 1) : cmd(cmd), scale(scale), wrap(wrap), color(r, g, b) { keepcode(cmd); } ~EvalText() { freecode(cmd); } 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) { tagval result; executeret(cmd, result); float k = drawscale(); glPushMatrix(); glScalef(k, k, 1); draw_text(result.getstr(), int(sx/k), int(sy/k), color.x * 255, color.y * 255, color.z * 255, 255, -1, wrap <= 0 ? -1 : wrap/k); glColor3f(1, 1, 1); glPopMatrix(); Object::draw(sx, sy); } void layout() { tagval result; executeret(cmd, result); Object::layout(); int tw, th; float k = drawscale(); text_bounds(result.getstr(), tw, th, wrap <= 0 ? -1 : wrap/k); if(wrap <= 0) w = max(w, tw*k); else w = max(w, min(wrap, tw*k)); h = max(h, th*k); } }; struct TextEditor; TextEditor *textediting; int refreshrepeat = 0; struct TextEditor : Object { float scale, offsetx, offsety; editor *edit; char *keyfilter; const char *name, *initval; int length, height, mode; 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), edit(NULL), keyfilter(keyfilter ? newstring(keyfilter) : NULL), name(newstring(name)), initval(initval ? newstring(initval) : NULL), length(length), height(height), mode(mode) {} ~TextEditor() { DELETEA(keyfilter); DELETEA(name); DELETEA(initval); if(this == textediting) textediting = NULL; refreshrepeat++; } 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; } virtual void commit() { } 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) { setfocus(this); edit->mark(false); offsetx = cx; offsety = cy; } bool hoverkey(int code, bool isdown, int cooked) { switch(code) { case SDLK_LEFT: case SDLK_RIGHT: case SDLK_UP: case SDLK_DOWN: case -4: case -5: if(isdown) edit->key(code, cooked); return true; } return Object::hoverkey(code, isdown, cooked); } 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_KP_ENTER: if(!cooked) return true; case SDLK_TAB: if(edit->maxy != 1) break; case SDLK_ESCAPE: setfocus(NULL); return true; case SDLK_HOME: case SDLK_END: case SDLK_PAGEUP: case SDLK_PAGEDOWN: case SDLK_DELETE: case SDLK_BACKSPACE: case SDLK_LSHIFT: case SDLK_RSHIFT: case SDLK_LCTRL: case SDLK_RCTRL: case SDLK_LMETA: case SDLK_RMETA: break; case SDLK_a: case SDLK_x: case SDLK_c: case SDLK_v: if(SDL_GetModState()) break; default: if(!cooked || code<32) return false; if(keyfilter && !strchr(keyfilter, cooked)) return true; break; } if(isdown) edit->key(code, cooked); return true; } virtual void resetvalue() { if(initval && strcmp(edit->lines[0].text, initval)) edit->clear(initval); } void layout() { Object::layout(); editor *lastedit = edit; edit = useeditor(name, mode, false, initval); if(lastedit != edit) { edit->linewrap = length<0; edit->maxx = edit->linewrap ? -1 : length; edit->maxy = height <= 0 ? 1 : -1; edit->pixelwidth = abs(length)*FONTW; if(!edit->linewrap || edit->maxy != 1) edit->pixelheight = FONTH*max(height, 1); } if(!isfocused(this) && edit->mode == EDITORFOCUSED) resetvalue(); 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, 0xFFFFFF, isfocused(this)); glColor3f(1, 1, 1); glPopMatrix(); Object::draw(sx, sy); } const int gettype() const { return TYPE_TEXTEDITOR; } }; struct Field : TextEditor { char *var; uint *onchange; Field(const char *var, int length, uint *onchange, float scale = 1, const char *keyfilter = NULL) : TextEditor(var, length, 0, scale, NULL, EDITORFOCUSED, keyfilter), var(newstring(var)), onchange(onchange) { keepcode(onchange); } ~Field() { delete[] var; freecode(onchange); } void commit() { updateval(var, edit->lines[0].text, onchange); } bool hoverkey(int code, bool isdown, int cooked) { return key(code, isdown, cooked); } void resetvalue() { const char *str = getsval(var); if(strcmp(edit->lines[0].text, str)) edit->clear(str); } 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_ESCAPE: setfocus(NULL); return true; case SDLK_KP_ENTER: case SDLK_RETURN: case SDLK_TAB: if(!cooked) return false; commit(); setfocus(NULL); return true; case SDLK_HOME: case SDLK_END: case SDLK_DELETE: case SDLK_BACKSPACE: case SDLK_LEFT: case SDLK_RIGHT: break; default: if(!cooked || code<32) return false; if(keyfilter && !strchr(keyfilter, cooked)) return true; break; } if(isdown) edit->key(code, cooked); return true; } }; 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 Window : NamedObject { uint *onhide; Window(const char *name, uint *onhide = NULL) : NamedObject(name), onhide(onhide) { keepcode(onhide); } ~Window() { freecode(onhide); } void hidden() { if(onhide) execute(onhide); } const int gettype() const { return TYPE_WINDOW; } }; struct Overlay : Window { Overlay(const char *name, uint *onhide = NULL) : Window(name, onhide) {} ~Overlay() {} bool takesinput() const { return false; } Object *target(float, float) {return NULL;} Object *hover(float, float) {return NULL;} Object *select(float, float) {return NULL;} }; vector build; Window *buildwindow(const char *name, uint *contents, uint *onhide = NULL, int noinput = 0) { Window *window = noinput ? new Overlay(name, onhide) : new Window(name, onhide); build.add(window); execute(contents); build.pop(); return window; } ICOMMAND(showui, "seei", (const char *name, uint *contents, uint *onhide, int *noinput), { 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, *noinput); 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", (const char *name), intret(hideui(name) ? 1 : 0)); ICOMMAND(replaceui, "sse", (const char *wname, const char *tname, uint *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); }); int numui() { int n = 0; loopv(world->children) { if(world->children[i]->gettype() == TYPE_WINDOW) n++; } return n; } void clearuis() { loopv(world->children) { if(world->children[i]->gettype() != TYPE_WINDOW) continue; Window *window = (Window *) world->children[i]; window->hidden(); world->remove(window); } } bool activeui(const char *name) { return world->findname(TYPE_WINDOW, name, false); } void addui(Object *o, uint *children) { if(build.length()) { o->parent = build.last(); o->adjust = o->parent->adjust & ALIGN_MASK; build.last()->children.add(o); } if(children[0]) { build.add(o); execute(children); build.pop(); } if(!build.length()) world->layout(); } 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, "se", (char *name, uint *children), addui(new Tag(name), children)); ICOMMAND(uihlist, "fe", (float *space, uint *children), addui(new HorizontalList(*space), children)); ICOMMAND(uivlist, "fe", (float *space, uint *children), addui(new VerticalList(*space), children)); ICOMMAND(uitable, "ife", (int *columns, float *space, uint *children), addui(new Table(*columns, *space), children)); ICOMMAND(uispace, "ffe", (float *spacew, float *spaceh, uint *children), addui(new Spacer(*spacew, *spaceh), children)); ICOMMAND(uifill, "ffe", (float *minw, float *minh, uint *children), addui(new Filler(*minw, *minh), children)); ICOMMAND(uiclip, "ffe", (float *clipw, float *cliph, uint *children), addui(new Clipper(*clipw, *cliph), children)); ICOMMAND(uiscroll, "ffe", (float *clipw, float *cliph, uint *children), addui(new Scroller(*clipw, *cliph), children)); ICOMMAND(uihscrollbar, "ffe", (float *arrowsize, float *arrowspeed, uint *children), addui(new HorizontalScrollBar(*arrowsize, *arrowspeed), children)); ICOMMAND(uivscrollbar, "ffe", (float *arrowsize, float *arrowspeed, uint *children), addui(new VerticalScrollBar(*arrowsize, *arrowspeed), children)); ICOMMAND(uiscrollbutton, "e", (uint *children), addui(new ScrollButton, children)); ICOMMAND(uihslider, "sffeffie", (char *var, float *vmin, float *vmax, uint *onchange, float *arrowsize, float *stepsize, int *steptime, uint *children), addui(new HorizontalSlider(var, *vmin, *vmax, onchange, *arrowsize, *stepsize ? *stepsize : 1, *steptime), children)); ICOMMAND(uivslider, "sffeffie", (char *var, float *vmin, float *vmax, uint *onchange, float *arrowsize, float *stepsize, int *steptime, uint *children), addui(new VerticalSlider(var, *vmin, *vmax, onchange, *arrowsize, *stepsize ? *stepsize : 1, *steptime), children)); ICOMMAND(uisliderbutton, "e", (uint *children), addui(new SliderButton, children)); ICOMMAND(uioffset, "ffe", (float *offsetx, float *offsety, uint *children), addui(new Offsetter(*offsetx, *offsety), children)); ICOMMAND(uibutton, "ee", (uint *onselect, uint *children), addui(new Button(onselect), children)); ICOMMAND(uicond, "ee", (uint *cond, uint *children), addui(new Conditional(cond), children)); ICOMMAND(uicondbutton, "eee", (uint *cond, uint *onselect, uint *children), addui(new ConditionalButton(cond, onselect), children)); ICOMMAND(uitoggle, "eefe", (uint *cond, uint *onselect, float *split, uint *children), addui(new Toggle(cond, onselect, *split), children)); ICOMMAND(uitooltip, "e", (uint *children), if(build.empty() || build.last()->gettype() != TYPE_BUTTON) return; Button *button = (Button *) build.last(); if(!button->tooltip) button->tooltip = new Object(); build.add(button->tooltip); execute(children); build.pop(); ) ICOMMAND(uiimage, "sffe", (char *texname, float *minw, float *minh, uint *children), addui(new Image(textureload(texname, 3, true, false), *minw, *minh), children)); ICOMMAND(uislotview, "iffe", (int *slotnum, float *minw, float *minh, uint *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, "ffffffe", (float *r, float *g, float *b, float *a, float *minw, float *minh, uint *children), addui(new Rectangle(Rectangle::SOLID, *r, *g, *b, *a, *minw, *minh), children)); ICOMMAND(uimodcolor, "fffffe", (float *r, float *g, float *b, float *minw, float *minh, uint *children), addui(new Rectangle(Rectangle::MODULATE, *r, *g, *b, 1, *minw, *minh), children)); ICOMMAND(uistretchedimage, "sffe", (char *texname, float *minw, float *minh, uint *children), addui(new StretchedImage(textureload(texname, 3, true, false), *minw, *minh), children)); ICOMMAND(uicroppedimage, "sffsssse", (char *texname, float *minw, float *minh, char *cropx, char *cropy, char *cropw, char *croph, uint *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, "ssfe", (char *texname, char *texborder, float *screenborder, uint *children), Texture *tex = textureload(texname, 3, true, false); addui(new BorderedImage(tex, strchr(texborder, 'p') ? atof(texborder) / tex->xs : atof(texborder), *screenborder), children)); ICOMMAND(uitiledimage, "sffffe", (char *texname, float *tilew, float *tileh, float *minw, float *minh, uint *children), Texture *tex = textureload(texname, 3, true, false); addui(new TiledImage(tex, *tilew <= 0 ? 1 : *tilew, *tileh <= 0 ? 1 : *tileh, *minw, *minh), children)); ICOMMAND(uicolortext, "sfffffe", (char *text, float *scale, float *wrap, float *r, float *g, float *b, uint *children), addui(new Text(text, *scale <= 0 ? 1 : *scale, *wrap, *r, *g, *b), children)); ICOMMAND(uitext, "sffe", (char *text, float *scale, float *wrap, uint *children), addui(new Text(text, *scale <= 0 ? 1 : *scale, *wrap), children)); ICOMMAND(uicolorevaltext, "efffffe", (uint *cmd, float *scale, float *wrap,float *r, float *g, float *b, uint *children), addui(new EvalText(cmd, *scale <= 0 ? 1 : *scale, *wrap, *r, *g, *b), children)); ICOMMAND(uievaltext, "effe", (uint *cmd, float *scale, float *wrap, uint *children), addui(new EvalText(cmd, *scale <= 0 ? 1 : *scale, *wrap), children)); ICOMMAND(uitexteditor, "siifsise", (char *name, int *length, int *height, float *scale, char *initval, int *keep, char *filter, uint *children), addui(new TextEditor(name, *length, *height, *scale, initval, *keep ? EDITORFOREVER : EDITORUSED, filter[0] ? filter : NULL), children)); ICOMMAND(uifield, "siefse", (char *var, int *length, uint *onchange, float *scale, char *filter, uint *children), addui(new Field(var, *length, onchange, *scale, filter[0] ? filter : NULL), children)); FVAR(cursorsensitivity, 1e-3f, 1, 1000); void resetcursor() { if(editmode || world->children.empty()) cursorx = cursory = 0.5f; } //0 - centre always; 1 - free only when UIs are shown; 2 - always VARP(freecursor, 0, 1, 2); VARP(freeeditcursor, 0, 1, 2); static inline int cursormode() { return editmode ? freeeditcursor : freecursor; } bool movecursor(int &dx, int &dy) { if(cursormode() == 2 || (world->takesinput() && cursormode() >= 1)) { 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(cursormode() == 2) { if(cursorx != 1 && cursorx != 0) dx = 0; if(cursory != 1 && cursory != 0) dy = 0; return false; } return true; } return false; } bool hascursor() { if(mainmenu) return true; if(world->takesinput() && cursormode() >= 1) { if(world->target(cursorx*world->w, cursory*world->h)) return true; } return false; } void getcursorpos(float &x, float &y) { if(cursormode() == 2 || (world->takesinput() && cursormode() >= 1)) { x = cursorx; y = cursory; } else x = y = .5f; } bool keypress(int code, bool isdown, int cooked) { if(!hascursor()) return false; switch(code) { case -5: case -4: case SDLK_LEFT: case SDLK_RIGHT: case SDLK_DOWN: case SDLK_UP: { if((focused && focused->hoverkey(code, isdown, cooked)) || (hovering && hovering->hoverkey(code, isdown, cooked))) return true; return false; } 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())) { clearuis(); mainmenu = 0; } } void setup() { world = new World; } int showchanges = 0; void update() { loopv(updatelater) updatelater[i].run(); updatelater.shrink(0); if(showchanges && !world->findname(TYPE_WINDOW, NULL, false)) { if(identexists("showchanges")) execute("showchanges"); } if(mainmenu && !isconnected(true) && !world->children.length() && identexists("showmain")) { execute("showmain"); } readyeditors(); tooltip = NULL; 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(); if(tooltip) { tooltip->layout(); tooltip->adjustchildren(); } flusheditors(); bool wastextediting = textediting!=NULL; if(textediting && !isfocused(textediting)) textediting->commit(); if(!focused || focused->gettype() != TYPE_TEXTEDITOR) textediting = NULL; else textediting = (TextEditor *) focused; if(refreshrepeat || (textediting!=NULL) != wastextediting) { SDL_EnableUNICODE(textediting!=NULL); keyrepeat(textediting!=NULL || editmode); refreshrepeat = 0; } } 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(); if(tooltip) { float margin = max((float(screen->w)/screen->h - 1)/2, 0.0f); float left = -margin, right = 1 + margin * 2; float x = left + cursorx * right + 0.01, y = cursory + 0.01; if(x + tooltip->w * .95 > right - margin) { x -= tooltip->w + 0.02; if(x <= -margin) x = -margin + 0.02; } if(y + tooltip->h * .95 > 1) { y -= tooltip->h + 0.02; if(y < 0) y = 0; } tooltip->draw(x, y); } 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() { static uint *resetgl = compilecode("resetgl"); static uint *resetsound = compilecode("resetsound"); int changetypes = 0; loopv(needsapply) changetypes |= needsapply[i].type; if(changetypes&CHANGE_GFX) UI::updatelater.add().schedule(resetgl); if(changetypes&CHANGE_SOUND) UI::updatelater.add().schedule(resetsound); } ICOMMAND(pendingchanges, "", (), intret(needsapply.length())); ICOMMAND(clearchanges, "", (), clearchanges(CHANGE_GFX|CHANGE_SOUND)); COMMAND(applychanges, ""); ICOMMAND(loopchanges, "se", (char *var, uint *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(); } sandboxgamemaker-2.8.2+dfsg/src/engine/rendertarget.h0000644000175000017500000004577412045412564021627 0ustar bofh80bofh80extern 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_ARB); 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.8.2+dfsg/src/engine/server.cpp0000644000175000017500000010137412045412564020767 0ustar bofh80bofh80// 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, "Sandbox 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) || (iscubespace(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; int localclients = 0, nonlocalclients = 0; bool hasnonlocalclients() { return nonlocalclients!=0; } bool haslocalclients() { return localclients!=0; } client &addclient(int type) { client *c = NULL; loopv(clients) if(clients[i]->type==ST_EMPTY) { c = clients[i]; break; } if(!c) { c = new client; c->num = clients.length(); clients.add(c); } c->info = server::newclientinfo(); c->type = type; switch(type) { case ST_TCPIP: nonlocalclients++; break; case ST_LOCAL: localclients++; break; } return *c; } void delclient(client *c) { if(!c) return; switch(c->type) { case ST_TCPIP: nonlocalclients--; if(c->peer) c->peer->data = NULL; break; case ST_LOCAL: localclients--; break; case ST_EMPTY: return; } c->type = ST_EMPTY; c->peer = NULL; if(c->info) { server::deleteclientinfo(c->info); c->info = 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); delclient(clients[n]); 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); } #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 && !iscubespace(*args)) args++; int cmdlen = args - input; while(args < end && iscubespace(*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.getbuf() + 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 { 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(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) 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); delclient(c); 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); delclient(clients[i]); disconnected = true; } if(!disconnected) return; game::gamedisconnect(cleanup); UI::mainmenu = 1; } void localconnect() { client &c = addclient(ST_LOCAL); copystring(c.hostname, "local"); 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() { 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, enet_uint16(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) { #ifdef WIN32 setupwindow("Sandbox server"); #endif 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; i= 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 && lshift < elvl) \ { \ float edist = disttoent(lc->ext->ents, oclast, o, ray, radius, mode, t); \ if(edist < 1e15f) \ { \ if(earlyexit) return min(edist, dist); \ elvl = lshift; \ dent = min(dent, edist); \ } \ 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, true); 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, true); 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((pw.y-c.y-fdir.y)*w.y + (pw.z-c.z-fdir.z)*w.z >= 0 && 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((pw.x-c.x-fdir.x)*w.x + (pw.z-c.z-fdir.z)*w.z >= 0 && 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((pw.x-c.x-fdir.x)*w.x + (pw.y-c.y-fdir.y)*w.y >= 0 && 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; } #define PHYSFRAMETIME 5 VARP(maxroll, 0, 0, 20); FVAR(straferoll, 0, 0.033f, 90); FVAR(faderoll, 0, 0.95f, 1); VAR(floatspeed, 1, 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(pl)) { 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)); } 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 && maxroll) pl->roll = clamp(pl->roll - pow(clamp(1.0f + pl->strafe*pl->roll/maxroll, 0.0f, 1.0f), 0.33f)*pl->strafe*curtime*straferoll, -maxroll, maxroll); else pl->roll *= curtime == PHYSFRAMETIME ? faderoll : pow(faderoll, curtime/float(PHYSFRAMETIME)); // 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; } 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.8.2+dfsg/src/engine/command.cpp0000644000175000017500000026236012045412564021102 0ustar bofh80bofh80// 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; ident *dummyident = NULL; 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_START) 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; } void cleancode(ident &id) { if(id.code) { id.code[0] -= 0x100; if(int(id.code[0]) < 0x100) delete[] id.code; id.code = NULL; } } struct nullval : tagval { nullval() { setnull(); } } nullval; tagval noret = nullval, *commandret = &noret; void clear_command() { enumerate(idents, ident, i, { if(i.type==ID_ALIAS) { DELETEA(i.name); i.forcenull(); 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; } cleancode(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; for(int i = 0; i < MAXARGS; i++) { defformatstring(argname)("arg%d", i+1); newident(argname, IDF_ARG); } dummyident = newident("//dummy", IDF_UNKNOWN); 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; int usedargs; identstack *argstack; } noalias = { NULL, NULL, (1<next) total++; for(identlink *l = aliasstack; l != &noalias; 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 == &noalias) 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); } void pusharg(ident &id, const tagval &v, identstack &stack) { stack.val = id.val; stack.valtype = id.valtype; stack.next = id.stack; id.stack = &stack; id.setval(v); cleancode(id); } void poparg(ident &id) { if(!id.stack) return; identstack *stack = id.stack; if(id.valtype == VAL_STR) delete[] id.val.s; id.setval(*stack); cleancode(id); id.stack = stack->next; } ICOMMAND(push, "rte", (ident *id, tagval *v, uint *code), { if(id->type != ID_ALIAS || id->index < MAXARGS) return; identstack stack; pusharg(*id, *v, stack); v->type = VAL_NULL; id->flags &= ~IDF_UNKNOWN; executeret(code, *commandret); poparg(*id); }); static inline void pushalias(ident &id, identstack &stack) { if(id.type == ID_ALIAS && id.index >= MAXARGS) { pusharg(id, nullval, stack); id.flags &= ~IDF_UNKNOWN; } } static inline void popalias(ident &id) { if(id.type == ID_ALIAS && id.index >= MAXARGS) poparg(id); } ICOMMAND(local, "L", (), {}); static inline bool checknumber(const char *s) { if(isdigit(s[0])) return true; else switch(s[0]) { case '+': case '-': return isdigit(s[1]) || (s[1] == '.' && isdigit(s[2])); case '.': return isdigit(s[1]) != 0; default: return false; } } ident *newident(const char *name, int flags) { ident *id = idents.access(name); if(!id) { if(checknumber(name)) { debugcode("number %s is not a valid identifier name", name); return dummyident; } ident init(ID_ALIAS, newstring(name), flags); id = addident(init); } return id; } ident *writeident(const char *name, int flags) { ident *id = newident(name, flags); if(id->index < MAXARGS && !(aliasstack->usedargs&(1<index))) { pusharg(*id, nullval, aliasstack->argstack[id->index]); aliasstack->usedargs |= 1<index; } return id; } ident *readident(const char *name) { ident *id = idents.access(name); if(id && id->index < MAXARGS && !(aliasstack->usedargs&(1<index))) return NULL; 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 setarg(ident &id, tagval &v) { if(aliasstack->usedargs&(1<argstack[id.index]); aliasstack->usedargs |= 1<type == ID_ALIAS) { if(id->index < MAXARGS) setarg(*id, v); else setalias(*id, v); } else { debugcode("cannot redefine builtin %s with an alias", id->name); freearg(v); } } else if(checknumber(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->index >= MAXARGS || aliasstack->usedargs&(1<index)) ? 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 numargs = 0; bool limit = true; for(const char *fmt = args; *fmt; fmt++) switch(*fmt) { case 'i': case 'f': case 't': case 'N': case 'D': if(numargs < MAXARGS) numargs++; break; case 's': case 'e': case 'r': if(numargs < MAXARGS) { argmask |= 1< 8) fatal("builtin %s declared with too many args: %d", name, numargs); ident c(ID_COMMAND, name, args, argmask, (void *)fun); addident(c); return false; } const char *parsestring(const char *p) { for(; *p; p++) switch(*p) { case '\r': case '\n': case '\"': return p; case '^': if(*++p) break; return p; } return p; } int unescapestring(char *dst, const char *src, const char *end) { char *start = dst; while(src < end) { int c = *src++; if(c == '^') { if(src >= 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 = unescapestring(s, p, end); s[len] = '\0'; p = end; if(*p=='\"') p++; return s; } static inline const char *parseword(const char *p) { const int maxbrak = 100; static char brakstack[maxbrak]; int brakdepth = 0; for(;; p++) { p += strcspn(p, "\"/;()[] \t\r\n\0"); switch(p[0]) { case '"': case ';': case ' ': case '\t': case '\r': case '\n': case '\0': return p; case '/': if(p[1] == '/') return p; break; case '[': case '(': if(brakdepth >= maxbrak) return p; brakstack[brakdepth++] = p[0]; break; case ']': if(brakdepth <= 0 || brakstack[--brakdepth] != '[') return p; break; case ')': if(brakdepth <= 0 || brakstack[--brakdepth] != '(') return p; break; } } return p; } static inline char *cutword(const char *&p, int &len) { const char *word = p; p = parseword(p); 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(uchar(word[i]))<<((i+1)*8); code.add(op); return; } code.add((macro ? CODE_MACRO : CODE_VAL|RET_STR)|(len<<8)); code.put((const 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_OFFSET|((start+2)<<8)); code.add(CODE_EXIT); code[start] |= uint(code.length() - (start + 1))<<8; } static inline void compileident(vector &code, const char *word = NULL) { ident *id = newident(word ? word : "//dummy", IDF_UNKNOWN); code.add((id->index < MAXARGS ? CODE_IDENTARG : CODE_IDENT)|(id->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); code.add(CODE_OFFSET|((start+2)<<8)); 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 void 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)) goto invalid; break; case '$': compilelookup(code, p, VAL_STR); break; default: { lookup = cutword(p, lookuplen); if(!lookup) goto invalid; 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((id->index < MAXARGS ? CODE_LOOKUPARG : 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(iscubealnum(*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((id->index < MAXARGS ? CODE_LOOKUPARG : 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 void 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, "@\"/[]\0"); int c = *p++; switch(c) { case '\0': debugcode(debugline(line, "missing \"]\"")); p--; goto done; case '\"': p = parsestring(p); if(*p=='\"') p++; break; case '/': if(*p=='/') p += strcspn(p, "\n\0"); break; case '[': brak++; break; case ']': brak--; break; case '@': { const char *esc = p; while(*p == '@') p++; int level = p - (esc - 1); if(brak > level) continue; else if(brak < level) debugcode(debugline(line, "too many @s")); 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; } } } done: if(p-1 > start) { if(!concs) switch(wordtype) { case VAL_CODE: { p = start; int inst = code.length(); code.add(CODE_BLOCK); code.add(CODE_OFFSET|((inst+2)<<8)); compilestatements(code, p, VAL_ANY, ']'); code.add(CODE_EXIT); code[inst] |= uint(code.length() - (inst + 1))<<8; return; } case VAL_IDENT: { char *name = newstring(start, p-1-start); compileident(code, name); delete[] name; return; } } 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 '$': compilelookup(code, p, wordtype); return true; 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 ? (id->index < MAXARGS ? CODE_ALIASARG : 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(!checknumber(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, fakeargs = 0; 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); fakeargs++; } 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); fakeargs++; } numargs++; break; case 'f': if(more) more = compilearg(code, p, VAL_FLOAT); if(!more) { if(rep) break; compilefloat(code); fakeargs++; } numargs++; break; case 't': if(more) more = compilearg(code, p, VAL_ANY); if(!more) { if(rep) break; compilenull(code); fakeargs++; } numargs++; break; case 'e': if(more) more = compilearg(code, p, VAL_CODE); if(!more) { if(rep) break; compileblock(code); fakeargs++; } numargs++; break; case 'r': if(more) more = compilearg(code, p, VAL_IDENT); if(!more) { if(rep) break; compileident(code); fakeargs++; } numargs++; break; case 'N': compileint(code, numargs-fakeargs); 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; case 'L': if(more) while(numargs < MAXARGS && (more = compilearg(code, p, VAL_IDENT))) numargs++; if(more) while((more = compilearg(code, p, VAL_ANY))) code.add(CODE_POP); code.add(CODE_LOCAL); goto endcmd; } endfmt: code.add(comtype|(rettype < VAL_ANY ? rettype<index<<8)); endcmd: 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); p--; 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_START); 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)); code[0] += 0x100; return code; } void keepcode(uint *code) { if(!code) return; switch(*code&CODE_OP_MASK) { case CODE_START: *code += 0x100; return; } switch(code[-1]&CODE_OP_MASK) { case CODE_START: code[-1] += 0x100; break; case CODE_OFFSET: code -= int(code[-1]>>8); *code += 0x100; break; } } void freecode(uint *code) { if(!code) return; switch(*code&CODE_OP_MASK) { case CODE_START: *code -= 0x100; if(int(*code) < 0x100) delete[] code; return; } switch(code[-1]&CODE_OP_MASK) { case CODE_START: code[-1] -= 0x100; if(int(code[-1]) < 0x100) delete[] &code[-1]; break; case CODE_OFFSET: code -= int(code[-1]>>8); *code -= 0x100; if(int(*code) < 0x100) delete[] code; break; } } static void printvar(ident *id) { switch(id->type) { case ID_VAR: { int i = *id->storage.i; if(i < 0) conoutf("%s = %d", id->name, i); else 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); 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_START: case CODE_OFFSET: 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_LOCAL: { identstack locals[MAXARGS]; freearg(result); loopi(numargs) pushalias(*args[i].id, locals[i]); code = runcode(code, result); loopi(numargs) popalias(*args[i].id); goto exit; } 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((const char *)code, len)); code += len/sizeof(uint) + 1; continue; } case CODE_VALI|RET_STR: { char s[4] = { char((op>>8)&0xFF), char((op>>16)&0xFF), char((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(*(const 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+1); 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_START); compileint(buf, arg.i); buf.add(CODE_RESULT); buf.add(CODE_EXIT); break; case VAL_FLOAT: buf.reserve(8); buf.add(CODE_START); 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_START); 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_IDENTARG: { ident *id = identmap[op>>8]; if(!(aliasstack->usedargs&(1<index))) { pusharg(*id, nullval, aliasstack->argstack[id->index]); aliasstack->usedargs |= 1<index; } args[numargs++].setident(id); 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); if(id->index < MAXARGS && !(aliasstack->usedargs&(1<index))) { pusharg(*id, nullval, aliasstack->argstack[id->index]); aliasstack->usedargs |= 1<index; } 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); \ if(id->index < MAXARGS && !(aliasstack->usedargs&(1<index))) { nval; continue; } \ 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_LOOKUPARG|RET_STR: #define LOOKUPARG(aval, nval) { \ id = identmap[op>>8]; \ if(!(aliasstack->usedargs&(1<index))) { nval; continue; } \ aval; \ continue; \ } LOOKUPARG(args[numargs++].setstr(newstring(id->getstr())), args[numargs++].setstr(newstring(""))); 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_LOOKUPARG|RET_INT: LOOKUPARG(args[numargs++].setint(id->getint()), args[numargs++].setint(0)); 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_LOOKUPARG|RET_FLOAT: LOOKUPARG(args[numargs++].setfloat(id->getfloat()), args[numargs++].setfloat(0.0f)); 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_LOOKUPARG|RET_NULL: LOOKUPARG(id->getval(args[numargs++]), args[numargs++].setnull()); 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; \ } 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_ALIASARG: setarg(*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(*identmap[i], args[i+offset], argstack[i]); \ int oldargs = _numargs, newargs = numargs-offset; \ _numargs = newargs; \ int oldflags = identflags; \ identflags |= id->flags&IDF_OVERRIDDEN; \ identlink aliaslink = { id, aliasstack, (1<code) id->code = compilecode(id->getstr()); \ uint *code = id->code; \ code[0] += 0x100; \ runcode(code+1, result); \ code[0] -= 0x100; \ if(int(code[0]) < 0x100) delete[] code; \ aliasstack = aliaslink.next; \ identflags = oldflags; \ for(int i = 0; i < newargs; i++) \ poparg(*identmap[i]); \ for(int argmask = aliaslink.usedargs&(~0<>8]; if(id->flags&IDF_UNKNOWN) { debugcode("unknown command: %s", id->name); goto forceresult; } CALLALIAS(0); continue; case CODE_CALLARG|RET_NULL: case CODE_CALLARG|RET_STR: case CODE_CALLARG|RET_FLOAT: case CODE_CALLARG|RET_INT: forcenull(result); id = identmap[op>>8]; if(!(aliasstack->usedargs&(1<index))) 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(checknumber(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, fakeargs = 1; for(const char *fmt = id->args; *fmt && i < maxargs; fmt++, i++) switch(*fmt) { case 'i': if(numargs <= i) { args[numargs++].setint(0); fakeargs++; } else forceint(args[i]); break; case 'f': if(numargs <= i) { args[numargs++].setfloat(0.0f); fakeargs++; } else forcefloat(args[i]); break; case 's': if(numargs <= i) { args[numargs++].setstr(newstring("")); fakeargs++; } else forcestr(args[i]); break; case 't': if(numargs <= i) { args[numargs++].setnull(); fakeargs++; } break; case 'e': if(numargs <= i) { uint *buf = new uint[2]; buf[0] = CODE_START; buf[1] = CODE_EXIT; args[numargs++].setcode(buf); fakeargs++; } else { 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)); fakeargs++; } else { ident *id = newident(args[i].type==VAL_STR ? args[i].s : "//dummy", IDF_UNKNOWN); freearg(args[i]); args[i].setident(id); } break; case 'N': args[numargs].setint(numargs-fakeargs); numargs++; fakeargs++; break; #ifndef STANDALONE case 'D': args[numargs].setint(addreleaseaction(conc(args, numargs, true)) ? 1 : 0); numargs++; fakeargs++; 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; case 'L': { identstack locals[MAXARGS]; freearg(args[0]); loopj(numargs-1) { tagval &v = args[j+1]; if(v.type != VAL_IDENT) { ident *id = newident(v.type==VAL_STR ? v.s : "//dummy", IDF_UNKNOWN); freearg(v); v.setident(id); } pushalias(*v.id, locals[j]); } code = runcode(code, result); loopj(numargs-1) popalias(*args[j+1].id); goto exit; } } #define ARG(n) (id->argmask&(1<flags&IDF_HEX && numargs > 2) { val = (val << 16) | (forceint(args[2])<<8); 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->index < MAXARGS && !(aliasstack->usedargs&(1<index))) goto forceresult; 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); if(int(code[0]) >= 0x100) code.disown(); } char *executestr(const uint *code) { tagval result; runcode(code, result); if(result.type == VAL_NULL) return NULL; forcestr(result); return result.s; } char *executestr(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); if(int(code[0]) >= 0x100) code.disown(); int i = result.getint(); freearg(result); return i; } static inline bool getbool(const char *s) { switch(s[0]) { case '+': case '-': switch(s[1]) { case '0': break; case '.': return !isdigit(s[2]) || parsefloat(s) != 0; default: return true; } // fall through case '0': { char *end; int val = strtol((char *)s, &end, 0); if(val) return true; switch(*end) { case 'e': case '.': return parsefloat(s) != 0; default: return false; } } case '.': return !isdigit(s[1]) || parsefloat(s) != 0; case '\0': return false; default: return true; } } static inline bool getbool(const tagval &v) { switch(v.type) { case VAL_FLOAT: return v.f!=0; case VAL_INT: return v.i!=0; case VAL_STR: case VAL_MACRO: return getbool(v.s); default: return false; } } bool executebool(const uint *code) { tagval result; runcode(code, result); bool b = getbool(result); freearg(result); return b; } bool executebool(const char *p) { tagval result; executeret(p, result); bool b = getbool(result); freearg(result); return b; } 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; } const char *escapestring(const char *s) { static vector strbuf[3]; static int stridx = 0; stridx = (stridx + 1)%3; vector &buf = strbuf[stridx]; buf.setsize(0); buf.add('"'); for(; *s; s++) switch(*s) { case '\n': buf.put("^n", 2); break; case '\t': buf.put("^t", 2); break; case '\f': buf.put("^f", 2); break; case '"': buf.put("^\"", 2); break; case '^': buf.put("^^", 2); break; default: buf.add(*s); break; } buf.put("\"\0", 2); return buf.getbuf(); } const char *escapeid(const char *s) { const char *end = s + strcspn(s, "\"/;()[] \f\t\r\n\0"); return *end ? escapestring(s) : s; } bool validateblock(const char *s) { const int maxbrak = 100; static char brakstack[maxbrak]; int brakdepth = 0; for(; *s; s++) switch(*s) { case '[': case '(': if(brakdepth >= maxbrak) return false; brakstack[brakdepth++] = *s; break; case ']': if(brakdepth <= 0 || brakstack[--brakdepth] != '[') return false; break; case ')': if(brakdepth <= 0 || brakstack[--brakdepth] != '(') return false; break; case '"': s = parsestring(s + 1); if(*s != '"') return false; break; case '/': if(s[1] == '/') return false; break; case '\f': return false; } return brakdepth == 0; } #ifndef STANDALONE bool sortidents(ident *x, ident *y) { return strcmp(x->name, y->name) < 0; } void writecfg(const char *name) { defformatstring(confname)("config_%s.cfg", game::gameident()); stream *f = openutf8file(path((name && name[0]) ? name : confname, true), "w"); 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", escapeid(id.name), *id.storage.i); break; case ID_FVAR: f->printf("%s %s\n", escapeid(id.name), floatstr(*id.storage.f)); break; case ID_SVAR: f->printf("%s %s\n", escapeid(id.name), escapestring(*id.storage.s)); 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(!validateblock(id.val.s)) { f->printf("%s = %s\n", escapeid(id), escapestring(id.val.s)); break; } case VAL_FLOAT: case VAL_INT: f->printf("%s = [%s]\n", escapeid(id), 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 ICOMMAND(do, "e", (uint *body), executeret(body, *commandret)); 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))); static inline void setiter(ident &id, int i, identstack &stack) { if(i) { if(id.valtype != VAL_INT) { if(id.valtype == VAL_STR) delete[] id.val.s; cleancode(id); id.valtype = VAL_INT; } id.val.i = i; } else { tagval zero; zero.setint(0); pusharg(id, zero, stack); id.flags &= ~IDF_UNKNOWN; } } ICOMMAND(loop, "rie", (ident *id, int *n, uint *body), { if(*n <= 0 || id->type!=ID_ALIAS) return; identstack stack; loopi(*n) { setiter(*id, i, stack); 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) { setiter(*id, i, stack); if(!executebool(cond)) break; execute(body); } poparg(*id); }); ICOMMAND(while, "ee", (uint *cond, uint *body), while(executebool(cond)) execute(body)); char *loopconc(ident *id, int n, uint *body, bool space) { identstack stack; vector s; loopi(n) { setiter(*id, i, stack); tagval v; executeret(body, v); const char *vstr = v.getstr(); int len = strlen(vstr); if(space && i) s.add(' '); s.put(vstr, len); freearg(v); } poparg(*id); s.add('\0'); return newstring(s.getbuf(), s.length()-1); } ICOMMAND(loopconcat, "rie", (ident *id, int *n, uint *body), { if(*n > 0 && id->type==ID_ALIAS) commandret->setstr(loopconc(id, *n, body, true)); }); ICOMMAND(loopconcatword, "rie", (ident *id, int *n, uint *body), { if(*n > 0 && id->type==ID_ALIAS) commandret->setstr(loopconc(id, *n, body, false)); }); 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 stringret(char *s) { commandret->setstr(s); } 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()); } static const char *liststart = NULL, *listend = NULL, *listquotestart = NULL, *listquoteend = NULL; static inline void skiplist(const char *&p) { for(;;) { p += strspn(p, " \t\r\n"); if(p[0]!='/' || p[1]!='/') break; p += strcspn(p, "\n\0"); } } static bool parselist(const char *&s, const char *&start = liststart, const char *&end = listend, const char *"estart = listquotestart, const char *"eend = listquoteend) { skiplist(s); switch(*s) { case '"': quotestart = s++; start = s; s = parsestring(s); end = s; if(*s == '"') s++; quoteend = s; break; case '(': case '[': quotestart = s; start = s+1; for(int braktype = *s++, brak = 1;;) { s += strcspn(s, "\"/;()[]\0"); int c = *s++; switch(c) { case '\0': s--; quoteend = end = s; return true; case '"': s = parsestring(s); if(*s == '"') s++; break; case '/': if(*s == '/') s += strcspn(s, "\n\0"); break; case '(': case '[': if(c == braktype) brak++; break; case ')': if(braktype == '(' && --brak <= 0) goto endblock; break; case ']': if(braktype == '[' && --brak <= 0) goto endblock; break; } } endblock: end = s-1; quoteend = s; break; case '\0': case ')': case ']': return false; default: quotestart = start = s; s = parseword(s); quoteend = end = s; break; } skiplist(s); if(*s == ';') s++; return true; } void explodelist(const char *s, vector &elems, int limit) { const char *start, *end; while((limit < 0 || elems.length() < limit) && parselist(s, start, end)) elems.add(newstring(start, end-start)); } char *indexlist(const char *s, int pos) { loopi(pos) if(!parselist(s)) return newstring(""); const char *start, *end; return parselist(s, start, end) ? newstring(start, end-start) : newstring(""); } int listlen(const char *s) { int n = 0; while(parselist(s)) n++; return n; } void at(char *s, int *pos) { commandret->setstr(indexlist(s, *pos)); } void substr(char *s, int *start, int *count, int *numargs) { int len = strlen(s), offset = clamp(*start, 0, len); commandret->setstr(newstring(&s[offset], *numargs >= 3 ? clamp(*count, 0, len - offset) : len - offset)); } void sublist(const char *s, int *skip, int *count, int *numargs) { int offset = max(*skip, 0), len = *numargs >= 3 ? max(*count, 0) : -1; loopi(offset) if(!parselist(s)) break; if(len < 0) { if(offset > 0) skiplist(s); commandret->setstr(newstring(s)); return; } const char *list = s, *start, *end, *qstart, *qend = s; if(len > 0 && parselist(s, start, end, list, qend)) while(--len > 0 && parselist(s, start, end, qstart, qend)); commandret->setstr(newstring(list, qend - list)); } 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"); ICOMMAND(escape, "s", (char *s), result(escapestring(s))); ICOMMAND(unescape, "s", (char *s), { int len = strlen(s); char *d = newstring(len); d[unescapestring(d, s, &s[len])] = '\0'; stringret(d); }); COMMAND(substr, "siiN"); COMMAND(sublist, "siiN"); 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, *start, *end; parselist(s, start, end);) { char *val = newstring(start, end-start); if(n++) { if(id->valtype == VAL_STR) delete[] id->val.s; else id->valtype = VAL_STR; cleancode(*id); id->val.s = val; } else { tagval t; t.setstr(val); pusharg(*id, t, stack); id->flags &= ~IDF_UNKNOWN; } if(executebool(body) && search) { intret(n-1); search = false; break; } } if(search) intret(-1); if(n) poparg(*id); } void prettylist(const char *s, const char *conj) { vector p; const char *start, *end; for(int len = listlen(s), n = 0; parselist(s, start, end); n++) { p.put(start, end - start); 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(' '); } } p.add('\0'); result(p.getbuf()); } COMMAND(prettylist, "ss"); int listincludes(const char *list, const char *needle, int needlelen) { int offset = 0; for(const char *s = list, *start, *end; parselist(s, start, end);) { int len = end - start; if(needlelen == len && !strncmp(needle, start, len)) return offset; offset++; } return -1; } char *listdel(const char *s, const char *del) { vector p; for(const char *start, *end, *qstart, *qend; parselist(s, start, end, qstart, qend);) { if(listincludes(del, start, end-start) < 0) { if(!p.empty()) p.add(' '); p.put(qstart, qend-qstart); } } p.add('\0'); return newstring(p.getbuf(), p.length()-1); } void listsplice(const char *s, const char *vals, int *skip, int *count, int *numargs) { int offset = max(*skip, 0), len = *numargs >= 4 ? max(*count, 0) : -1; const char *list = s, *start, *end, *qstart, *qend = s; loopi(offset) if(!parselist(s, start, end, qstart, qend)) break; vector p; if(qend > list) p.put(list, qend-list); if(*vals) { if(!p.empty()) p.add(' '); p.put(vals, strlen(vals)); } while(len-- > 0) if(!parselist(s)) break; skiplist(s); switch(*s) { case '\0': case ')': case ']': break; default: if(!p.empty()) p.add(' '); p.put(s, strlen(s)); break; } p.add('\0'); commandret->setstr(newstring(p.getbuf(), p.length()-1)); } COMMAND(listsplice, "ssiiN"); 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->valtype == 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); loopvrev(files) { char *t = strstr(files[i], "."); if(t) { delete files[i]; files.remove(i); } else { loopj(i) { if(!strcmp(files[i], files[j])) { delete[] files[j]; files.remove(j); break; } } } } loopv(files) { if(i) { if(id->valtype == VAL_STR) delete[] id->val.s; else id->valtype = VAL_STR; id->val.s = files[i]; } else { tagval t; t.setstr(files[i]); pusharg(*id, t, stack); id->flags &= ~IDF_UNKNOWN; } execute(body); } if(files.length()) poparg(*id); }); ICOMMAND(+, "V", (tagval *v, int n), int ret = 0; loopi(n) ret += v[i].getint(); intret(ret)); ICOMMAND(-, "V", (tagval *v, int n), int ret = n >= 1 ? v->getint() : 0; loopi(n - 1) ret -= v[i + 1].getint(); intret(ret)); ICOMMAND(+f, "V", (tagval *v, int n), float ret = 0; loopi(n) ret += v[i].getfloat(); floatret(ret)); ICOMMAND(-f, "V", (tagval *v, int n), float ret = n >= 1 ? v->getfloat() : 0; loopi(n - 1) ret -= v[i + 1].getfloat(); floatret(ret)); ICOMMAND(*, "ii", (int *a, int *b), intret(*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(!, "t", (tagval *a), intret(!getbool(*a))); ICOMMAND(&, "ii", (int *a, int *b), intret(*a & *b)); ICOMMAND(|, "V", (tagval *v, int n), int ret = 0; loopi(n) ret |= v[i].getint(); intret(ret)); 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), { if(!numargs) intret(1); else loopi(numargs) { if(i) freearg(*commandret); executeret(args[i].code, *commandret); if(!getbool(*commandret)) break; } }); ICOMMAND(||, "e1V", (tagval *args, int numargs), { if(!numargs) intret(0); else loopi(numargs) { if(i) freearg(*commandret); executeret(args[i].code, *commandret); if(getbool(*commandret)) break; } }); 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(i+1 < numargs) { if(executebool(args[i].code)) { executeret(args[i+1].code, *commandret); break; } } else { executeret(args[i].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; uint *command; }; vector sleepcmds; void addsleep(int *msec, uint *cmd) { sleepcmd &s = sleepcmds.add(); s.delay = max(*msec, 1); s.millis = lastmillis; s.command = cmd; keepcode(cmd); s.flags = identflags; } COMMANDN(sleep, addsleep, "ie"); void checksleep(int millis) { loopv(sleepcmds) { sleepcmd &s = sleepcmds[i]; if(millis - s.millis >= s.delay) { uint *cmd = s.command; // execute might create more sleep commands s.command = NULL; int oldflags = identflags; identflags = s.flags; execute(cmd); identflags = oldflags; freecode(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 freecode(sleepcmds[i].command); } sleepcmds.shrink(len); } void clearsleep_(int *clearoverrides) { clearsleep(*clearoverrides!=0 || identflags&IDF_OVERRIDDEN); } COMMANDN(clearsleep, clearsleep_, "i"); #endif sandboxgamemaker-2.8.2+dfsg/src/READMELINUX0000644000175000017500000000174012045372717017211 0ustar bofh80bofh80Linux 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.8.2+dfsg/src/moviecube_exp/0000755000175000017500000000000012076771134020341 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/src/moviecube_exp/characterinfo.cpp0000644000175000017500000000446112045412564023655 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/map.h0000644000175000017500000000226412045412564021266 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/clientmode.cpp0000644000175000017500000000144112045412564023163 0ustar bofh80bofh80/* * 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.8.2+dfsg/src/moviecube_exp/modeinfo.h0000644000175000017500000000446012045412564022311 0ustar bofh80bofh80/* * 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.8.2+dfsg/src/moviecube_exp/roadmap0000644000175000017500000000133212045372717021706 0ustar bofh80bofh80ROADMAP: -------- 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.8.2+dfsg/src/moviecube_exp/mapentities.h0000644000175000017500000000210112045412564023021 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/pch.cpp0000644000175000017500000000002312045412564021605 0ustar bofh80bofh80#include "game.h" sandboxgamemaker-2.8.2+dfsg/src/moviecube_exp/trigger.cpp0000644000175000017500000002645312045412564022515 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/playermodelinfo.h0000644000175000017500000001154612045412564023705 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/mapentities.cpp0000644000175000017500000000365712045412564023375 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/map.cpp0000644000175000017500000000373312045412564021623 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/servmode.h0000644000175000017500000000276612045412564022344 0ustar bofh80bofh80/* * 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.8.2+dfsg/src/moviecube_exp/client.cpp0000644000175000017500000015463012045412564022327 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/dynentities.h0000644000175000017500000000361212045412564023046 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/action.h0000644000175000017500000000054512045412564021766 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/botmgr.h0000644000175000017500000001604712045412564022007 0ustar bofh80bofh80// 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.8.2+dfsg/src/moviecube_exp/action.cpp0000644000175000017500000000226012045412564022315 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/render.cpp0000644000175000017500000002264312045412564022326 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/extinfo.h0000644000175000017500000001211312045412564022157 0ustar bofh80bofh80 #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.8.2+dfsg/src/moviecube_exp/characterinfo.h0000644000175000017500000000205112045412564023313 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/control.cpp0000644000175000017500000001655612045412564022535 0ustar bofh80bofh80//////////////////////////////////////////////////////// // 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.8.2+dfsg/src/moviecube_exp/camera.h0000644000175000017500000000166312045412564021743 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/movable.cpp0000644000175000017500000001453012045412564022470 0ustar bofh80bofh80// 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.8.2+dfsg/src/moviecube_exp/changelog0000644000175000017500000000062112045372717022212 0ustar bofh80bofh80changelog: 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.8.2+dfsg/src/moviecube_exp/moviecube.cpp0000644000175000017500000005507412056016245023027 0ustar bofh80bofh80#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); // if (deathscore) showscores(false); // 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!"); // showscores(true); 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; } bool showenthelpers() { if(m_edit || editmode) return true; return false; } bool needminimap() { return 0; } bool allowdoublejump(physent *d) {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.8.2+dfsg/src/moviecube_exp/playermodelinfo.cpp0000644000175000017500000001205412045412564024233 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/control.h0000644000175000017500000000525512045412564022174 0ustar bofh80bofh80/* * 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.8.2+dfsg/src/moviecube_exp/game.h0000644000175000017500000003667012045412564021432 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/dynlight.cpp0000644000175000017500000000224112045412564022661 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/clientmode.h0000644000175000017500000000215312045412564022631 0ustar bofh80bofh80/* * 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.8.2+dfsg/src/moviecube_exp/server.cpp0000644000175000017500000024256512045412564022364 0ustar bofh80bofh80#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.8.2+dfsg/src/moviecube_exp/camera.cpp0000644000175000017500000000361212045412564022272 0ustar bofh80bofh80#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.8.2+dfsg/src/launcher/0000755000175000017500000000000012076771134017310 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/src/launcher/pasl.cpp0000644000175000017500000007511412045412564020756 0ustar bofh80bofh80///////////////////////////////////////////////////////////////////////////// // 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.8.2+dfsg/src/launcher/paslapp.h0000644000175000017500000000252712045412564021122 0ustar bofh80bofh80///////////////////////////////////////////////////////////////////////////// // 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.8.2+dfsg/src/launcher/sandboxlogo.xpm0000644000175000017500000000235412045372717022361 0ustar bofh80bofh80/* XPM */ static char * sandboxlogo_xpm[] = { "32 32 1 1", " c None", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "}; sandboxgamemaker-2.8.2+dfsg/src/launcher/pasl.h0000644000175000017500000001473212045412564020422 0ustar bofh80bofh80///////////////////////////////////////////////////////////////////////////// // 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.8.2+dfsg/src/launcher/paslapp.cpp0000644000175000017500000000357512045412564021461 0ustar bofh80bofh80///////////////////////////////////////////////////////////////////////////// // 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.8.2+dfsg/src/launcher/makefile.gcc0000644000175000017500000000476112045372717021553 0ustar bofh80bofh80### 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.8.2+dfsg/src/launcher/PASL.rc0000644000175000017500000000003112045372717020367 0ustar bofh80bofh80#include "wx/msw/wx.rc" sandboxgamemaker-2.8.2+dfsg/src/launcher/PASL.pjd0000644000175000017500000067475312045372717020574 0ustar bofh80bofh80
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.8.2+dfsg/src/launcher/NoImage.xpm0000644000175000017500000001243212045372717021357 0ustar bofh80bofh80/* 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.8.2+dfsg/src/launcher/Makefile0000644000175000017500000000522612045372717020755 0ustar bofh80bofh80### 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.8.2+dfsg/src/krsgame/0000755000175000017500000000000012076771133017137 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/src/krsgame/krsrender.cpp0000644000175000017500000000617512045412564021647 0ustar bofh80bofh80#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_IDLE|ANIM_LOOP, 0, 0, 0, 0, 1, false); } else renderclient(d, playermodels(d->playerindex), NULL, ANIM_IDLE|ANIM_LOOP, 0, 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); } } } const char *animname(int i) { i &= 0x7F; if(i >= NUMANIMS) return ""; return animnames[i]; } const int numanims() {return NUMANIMS;} } sandboxgamemaker-2.8.2+dfsg/src/krsgame/TODO.txt0000644000175000017500000000132512047476455020455 0ustar bofh80bofh80Vehicle 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.8.2+dfsg/src/krsgame/krsents.cpp0000644000175000017500000001056112045412564021333 0ustar bofh80bofh80#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.8.2+dfsg/src/krsgame/krsai.cpp0000644000175000017500000000513212045412564020751 0ustar bofh80bofh80#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.8.2+dfsg/src/krsgame/krsgame.h0000644000175000017500000001205512045412564020740 0ustar bofh80bofh80#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; }; enum { ANIM_BRAKE = ANIM_GAMESPECIFIC, NUMANIMS }; static const char * const animnames[] = { ANIMNAMES, "brake" }; 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.8.2+dfsg/src/krsgame/krsstubs.cpp0000644000175000017500000000673612056016245021531 0ustar bofh80bofh80#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) {} 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(physent *d) {return false;} bool detachcamera() { return false; } bool needminimap() { return false; } bool allowedittoggle() { return true; } bool allowmove (physent *d) {return true;} bool collidecamera() {return !editmode;} } 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.8.2+dfsg/src/krsgame/waypoint.cpp0000644000175000017500000002341512045412564021516 0ustar bofh80bofh80#include "krsgame.h" /** us V them - the differences between us and the upstream sauerbraten FPS 1) we don't use 0 to denote a dummy waypoint 2) numlinks is not limited - this could allow an exorbitant amount up to 255 */ namespace ai { vector 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.8.2+dfsg/src/krsgame/PSEUDO-CODE0000644000175000017500000001116212045372717020573 0ustar bofh80bofh80/* 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.8.2+dfsg/src/krsgame/krs.cpp0000644000175000017500000002072312045412564020442 0ustar bofh80bofh80#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(ivel.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.8.2+dfsg/src/krsgame/krsscript.cpp0000644000175000017500000000304512045412564021665 0ustar bofh80bofh80#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.8.2+dfsg/src/sandbox_src_license.txt0000644000175000017500000000344612047476455022274 0ustar bofh80bofh80Platinum Arts Sandbox Free 3D Game Maker 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 ======= Platinum Arts Sandbox Free 3D Game Maker game engine source code, any release. Copyright (C) 2006-2010 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. 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 Platinum Arts Sandbox Free 3D Game Maker 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). AUTHORS ====== Michael Tomaino Kevin Meyer Dale Weiler sandboxgamemaker-2.8.2+dfsg/src/moviecube_license.txt0000644000175000017500000000324112047476455021736 0ustar bofh80bofh80Moviecube is a Machinima tool based on the Sauerbraten game engine, both of which are covered under the ZLIB license. You may use the source code so long as you obey this license, for further information see: http://www.opensource.org/licenses/zlib-license.php LICENSE ======= Moviecube, Copyright (C) 2007-2008 Thomas Achtner Sauerbraten, Copyright (C) 2001-2008 Wouter "aardappel" van Oortmerssen, Lee "eihrul" Salzman 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 this directory of the archive, the included enet network library 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). sandboxgamemaker-2.8.2+dfsg/src/qtlaunch/0000755000175000017500000000000012076771131017323 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/src/qtlaunch/launcher.h0000644000175000017500000000322712045412564021277 0ustar bofh80bofh80#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.8.2+dfsg/src/qtlaunch/io.cpp0000644000175000017500000000577212045412564020447 0ustar bofh80bofh80#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.8.2+dfsg/src/qtlaunch/mainwindow.cpp0000644000175000017500000000526012045412564022204 0ustar bofh80bofh80#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.8.2+dfsg/src/qtlaunch/aboutwindow.cpp0000644000175000017500000000014612045412564022370 0ustar bofh80bofh80#include "launcher.h" aboutwindow::aboutwindow() { setWindowTitle("About Platinum Arts Sandbox"); } sandboxgamemaker-2.8.2+dfsg/src/qtlaunch/main.cpp0000644000175000017500000000057512045412564020760 0ustar bofh80bofh80#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.8.2+dfsg/src/qtlaunch/readme0000644000175000017500000000052112045372717020504 0ustar bofh80bofh80To 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.8.2+dfsg/src/sb/0000755000175000017500000000000012076771135016114 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/src/sb/extentity.h0000644000175000017500000000423012045412564020313 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/extentityhandler.h0000644000175000017500000001133712045412564021657 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/ientities.cpp0000644000175000017500000000527312045412564020616 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/qcscript.h0000644000175000017500000000365212045412564020115 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/objectfactory.h0000644000175000017500000001110412045412564021112 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/testscript.cpp0000644000175000017500000000227012045412564021017 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/singleton.h0000644000175000017500000000042612045412564020263 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/objectgenerator.h0000644000175000017500000000071712045412564021441 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/exp_local.cpp0000644000175000017500000000237412045412564020566 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/README0000644000175000017500000000042312045372717016772 0ustar bofh80bofh80classes 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.8.2+dfsg/src/sb/handlerfactory.h0000644000175000017500000000477612045412564021302 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/qcscript.cpp0000644000175000017500000000702212045412564020443 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/entityscript/0000755000175000017500000000000012076771135020655 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/src/sb/entityscript/instance.cpp0000644000175000017500000000434212045412564023162 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/entityscript/signal.h0000644000175000017500000000064312045412564022300 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/entityscript/scriptmanager.cpp0000644000175000017500000000152312045412564024213 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/entityscript/scriptmanager.h0000644000175000017500000000112012045412564023651 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/entityscript/script.h0000644000175000017500000000114612045412564022326 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/entityscript/script.cpp0000644000175000017500000000305112045412564022656 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/entityscript/action.h0000644000175000017500000000174512045412564022304 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/entityscript/action.cpp0000644000175000017500000000403112045412564022626 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/entityscript/signal.cpp0000644000175000017500000000547112045412564022637 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/entityscript/instance.h0000644000175000017500000000201512045412564022622 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/extentityhandler.cpp0000644000175000017500000002072612045412564022214 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/extentity.cpp0000644000175000017500000000305712045412564020654 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/qcommand.cpp0000644000175000017500000001353212045412564020415 0ustar bofh80bofh80#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.8.2+dfsg/src/sb/qcommand.h0000644000175000017500000000751212045412564020063 0ustar bofh80bofh80#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.8.2+dfsg/src/Makefile.debug0000644000175000017500000012405312045412564020234 0ustar bofh80bofh80 DEFINES = MACHINENAME= CXXFLAGS= -g $(DEFINES) override CXXFLAGS+= -Wall -fsigned-char -fno-exceptions -fno-rtti PLATFORM= $(shell uname -s) PLATFORM_PREFIX=debug 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/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/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 \ fpsgame/weapon.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 $(subst .h.gch,.tmp.h.gch,$@) $(subst .h.gch,.h,$@) $(MV) $(subst .h.gch,.tmp.h.gch,$@) $@ %-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 depend: makedepend -Y -Ishared -Iengine $(subst .o,.cpp,$(CLIENT_OBJS)) makedepend -a -Y -Ishared -Iengine -Ifpsgame $(subst .o,.cpp,$(FPSCLIENT_OBJS)) makedepend -a -Y -Ishared -Iengine -Isspgame $(subst .o,.cpp,$(SSPCLIENT_OBJS)) makedepend -a -Y -Ishared -Iengine -Irpggame $(subst .o,.cpp,$(RPGCLIENT_OBJS)) makedepend -a -Y -Ishared -Iengine -Ikrsgame $(subst .o,.cpp,$(KRSCLIENT_OBJS)) makedepend -a -Y -Ishared -Iengine -Imoviecube $(subst .o,.cpp,$(MOVIECLIENT_OBJS)) makedepend -a -o.h.gch -Y -Ishared -Iengine -Ifpsgame -Irpggame -Isspgame -Imoviecube -Ikrsgame $(subst .h.gch,.h,$(CLIENT_PCH)) makedepend -a -o-standalone.o -Y -Ishared -Iengine -DSTANDALONE $(subst -standalone.o,.cpp,$(SERVER_OBJS)) makedepend -a -o-standalone.o -Y -Ishared -Iengine -Ifpsgame -DSTANDALONE $(subst -standalone.o,.cpp,$(FPSSERVER_OBJS)) makedepend -a -o-standalone.o -Y -Ishared -Iengine -Imoviecube -DSTANDALONE $(subst -standalone.o,.cpp,$(MOVIESERVER_OBJS)) makedepend -a -o-standalone.o -Y -Ishared -Iengine -DSTANDALONE $(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/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/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/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/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/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/iqm.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/ui.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/ui.o: shared/ents.h shared/command.h shared/iengine.h engine/ui.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/ui.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/ui.o: engine/textedit.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/client.o: fpsgame/collect.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/collect.h 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 fpsgame/weapon.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/weapon.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/weapon.o: shared/igame.h fpsgame/ai.h sspgame/ssp.o: sspgame/sspgame.h shared/cube.h shared/tools.h shared/geom.h sspgame/ssp.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h sspgame/sspent.o: sspgame/sspgame.h shared/cube.h shared/tools.h sspgame/sspent.o: shared/geom.h shared/ents.h shared/command.h sspgame/sspent.o: shared/iengine.h shared/igame.h sspgame/sspentities.o: sspgame/sspgame.h shared/cube.h shared/tools.h sspgame/sspentities.o: shared/geom.h shared/ents.h shared/command.h sspgame/sspentities.o: shared/iengine.h shared/igame.h sspgame/sspweapons.o: sspgame/sspgame.h shared/cube.h shared/tools.h sspgame/sspweapons.o: shared/geom.h shared/ents.h shared/command.h sspgame/sspweapons.o: shared/iengine.h shared/igame.h sspgame/sspmonster.o: sspgame/sspgame.h shared/cube.h shared/tools.h sspgame/sspmonster.o: shared/geom.h shared/ents.h shared/command.h sspgame/sspmonster.o: shared/iengine.h shared/igame.h sspgame/ssprender.o: sspgame/sspgame.h shared/cube.h shared/tools.h sspgame/ssprender.o: shared/geom.h shared/ents.h shared/command.h sspgame/ssprender.o: shared/iengine.h shared/igame.h sspgame/sspstubs.o: sspgame/sspgame.h shared/cube.h shared/tools.h sspgame/sspstubs.o: shared/geom.h shared/ents.h shared/command.h sspgame/sspstubs.o: shared/iengine.h shared/igame.h rpggame/rpg.o: rpggame/rpggame.h shared/cube.h shared/tools.h shared/geom.h rpggame/rpg.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h rpggame/rpgai.o: rpggame/rpggame.h shared/cube.h shared/tools.h shared/geom.h rpggame/rpgai.o: shared/ents.h shared/command.h shared/iengine.h rpggame/rpgai.o: shared/igame.h rpggame/rpgaction.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgaction.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgaction.o: shared/iengine.h shared/igame.h rpggame/rpgcamera.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgcamera.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgcamera.o: shared/iengine.h shared/igame.h rpggame/rpgchar.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgchar.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgchar.o: shared/iengine.h shared/igame.h rpggame/rpgconfig.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgconfig.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgconfig.o: shared/iengine.h shared/igame.h rpggame/rpgcontainer.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgcontainer.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgcontainer.o: shared/iengine.h shared/igame.h rpggame/rpgeffect.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgeffect.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgeffect.o: shared/iengine.h shared/igame.h rpggame/rpgentities.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgentities.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgentities.o: shared/iengine.h shared/igame.h rpggame/rpghud.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpghud.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpghud.o: shared/iengine.h shared/igame.h rpggame/rpggui.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpggui.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpggui.o: shared/iengine.h shared/igame.h rpggame/rpgio.o: rpggame/rpggame.h shared/cube.h shared/tools.h shared/geom.h rpggame/rpgio.o: shared/ents.h shared/command.h shared/iengine.h rpggame/rpgio.o: shared/igame.h rpggame/rpgitem.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgitem.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgitem.o: shared/iengine.h shared/igame.h rpggame/rpgobstacle.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgobstacle.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgobstacle.o: shared/iengine.h shared/igame.h rpggame/rpgplatform.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgplatform.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgplatform.o: shared/iengine.h shared/igame.h rpggame/rpgproj.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgproj.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgproj.o: shared/iengine.h shared/igame.h rpggame/rpgscript.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgscript.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgscript.o: shared/iengine.h shared/igame.h rpggame/rpgstats.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgstats.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgstats.o: shared/iengine.h shared/igame.h rpggame/rpgstatus.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgstatus.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgstatus.o: shared/iengine.h shared/igame.h rpggame/rpgstubs.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgstubs.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgstubs.o: shared/iengine.h shared/igame.h rpggame/rpgrender.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgrender.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgrender.o: shared/iengine.h shared/igame.h rpggame/rpgtest.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgtest.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgtest.o: shared/iengine.h shared/igame.h rpggame/rpgtrigger.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/rpgtrigger.o: shared/geom.h shared/ents.h shared/command.h rpggame/rpgtrigger.o: shared/iengine.h shared/igame.h rpggame/waypoint.o: rpggame/rpggame.h shared/cube.h shared/tools.h rpggame/waypoint.o: shared/geom.h shared/ents.h shared/command.h rpggame/waypoint.o: shared/iengine.h shared/igame.h krsgame/krs.o: krsgame/krsgame.h shared/cube.h shared/tools.h shared/geom.h krsgame/krs.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h krsgame/krsai.o: krsgame/krsgame.h shared/cube.h shared/tools.h shared/geom.h krsgame/krsai.o: shared/ents.h shared/command.h shared/iengine.h krsgame/krsai.o: shared/igame.h krsgame/krsents.o: krsgame/krsgame.h shared/cube.h shared/tools.h krsgame/krsents.o: shared/geom.h shared/ents.h shared/command.h krsgame/krsents.o: shared/iengine.h shared/igame.h krsgame/krshud.o: krsgame/krsgame.h shared/cube.h shared/tools.h krsgame/krshud.o: shared/geom.h shared/ents.h shared/command.h krsgame/krshud.o: shared/iengine.h shared/igame.h engine/engine.h krsgame/krshud.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h krsgame/krshud.o: engine/texture.h engine/model.h engine/varray.h krsgame/krsrender.o: krsgame/krsgame.h shared/cube.h shared/tools.h krsgame/krsrender.o: shared/geom.h shared/ents.h shared/command.h krsgame/krsrender.o: shared/iengine.h shared/igame.h krsgame/krsstubs.o: krsgame/krsgame.h shared/cube.h shared/tools.h krsgame/krsstubs.o: shared/geom.h shared/ents.h shared/command.h krsgame/krsstubs.o: shared/iengine.h shared/igame.h krsgame/krsscript.o: krsgame/krsgame.h shared/cube.h shared/tools.h krsgame/krsscript.o: shared/geom.h shared/ents.h shared/command.h krsgame/krsscript.o: shared/iengine.h shared/igame.h krsgame/waypoint.o: krsgame/krsgame.h shared/cube.h shared/tools.h krsgame/waypoint.o: shared/geom.h shared/ents.h shared/command.h krsgame/waypoint.o: shared/iengine.h shared/igame.h moviecube/action.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/action.o: shared/geom.h shared/ents.h shared/command.h moviecube/action.o: shared/iengine.h shared/igame.h moviecube/mapentities.h moviecube/action.o: moviecube/clientmode.h moviecube/modeinfo.h moviecube/action.o: moviecube/control.h moviecube/action.h moviecube/characterinfo.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/characterinfo.o: shared/geom.h shared/ents.h shared/command.h moviecube/characterinfo.o: shared/iengine.h shared/igame.h moviecube/characterinfo.o: moviecube/mapentities.h moviecube/clientmode.h moviecube/characterinfo.o: moviecube/modeinfo.h moviecube/control.h moviecube/characterinfo.o: moviecube/action.h moviecube/client.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/client.o: shared/geom.h shared/ents.h shared/command.h moviecube/client.o: shared/iengine.h shared/igame.h moviecube/mapentities.h moviecube/client.o: moviecube/clientmode.h moviecube/modeinfo.h moviecube/client.o: moviecube/control.h moviecube/action.h moviecube/clientmode.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/clientmode.o: shared/geom.h shared/ents.h shared/command.h moviecube/clientmode.o: shared/iengine.h shared/igame.h moviecube/clientmode.o: moviecube/mapentities.h moviecube/clientmode.h moviecube/clientmode.o: moviecube/modeinfo.h moviecube/control.h moviecube/clientmode.o: moviecube/action.h moviecube/control.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/control.o: shared/geom.h shared/ents.h shared/command.h moviecube/control.o: shared/iengine.h shared/igame.h moviecube/mapentities.h moviecube/control.o: moviecube/clientmode.h moviecube/modeinfo.h moviecube/control.o: moviecube/control.h moviecube/action.h moviecube/entities.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/entities.o: shared/geom.h shared/ents.h shared/command.h moviecube/entities.o: shared/iengine.h shared/igame.h moviecube/mapentities.h moviecube/entities.o: moviecube/clientmode.h moviecube/modeinfo.h moviecube/entities.o: moviecube/control.h moviecube/action.h moviecube/mapentities.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/mapentities.o: shared/geom.h shared/ents.h shared/command.h moviecube/mapentities.o: shared/iengine.h shared/igame.h moviecube/mapentities.o: moviecube/mapentities.h moviecube/clientmode.h moviecube/mapentities.o: moviecube/modeinfo.h moviecube/control.h moviecube/mapentities.o: moviecube/action.h moviecube/movable.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/movable.o: shared/geom.h shared/ents.h shared/command.h moviecube/movable.o: shared/iengine.h shared/igame.h moviecube/mapentities.h moviecube/movable.o: moviecube/clientmode.h moviecube/modeinfo.h moviecube/movable.o: moviecube/control.h moviecube/action.h moviecube/moviecube.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/moviecube.o: shared/geom.h shared/ents.h shared/command.h moviecube/moviecube.o: shared/iengine.h shared/igame.h moviecube/moviecube.o: moviecube/mapentities.h moviecube/clientmode.h moviecube/moviecube.o: moviecube/modeinfo.h moviecube/control.h moviecube/moviecube.o: moviecube/action.h moviecube/render.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/render.o: shared/geom.h shared/ents.h shared/command.h moviecube/render.o: shared/iengine.h shared/igame.h moviecube/mapentities.h moviecube/render.o: moviecube/clientmode.h moviecube/modeinfo.h moviecube/render.o: moviecube/control.h moviecube/action.h moviecube/camera.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/camera.o: shared/geom.h shared/ents.h shared/command.h moviecube/camera.o: shared/iengine.h shared/igame.h moviecube/mapentities.h moviecube/camera.o: moviecube/clientmode.h moviecube/modeinfo.h moviecube/camera.o: moviecube/control.h moviecube/action.h moviecube/server.o: moviecube/game.h shared/cube.h shared/tools.h moviecube/server.o: shared/geom.h shared/ents.h shared/command.h moviecube/server.o: shared/iengine.h shared/igame.h moviecube/mapentities.h moviecube/server.o: moviecube/clientmode.h moviecube/modeinfo.h moviecube/server.o: moviecube/control.h moviecube/action.h moviecube/server.o: moviecube/servmode.h moviecube/extinfo.h moviecube/server.o: moviecube/botmgr.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 sspgame/sspgame.h.gch: shared/ents.h shared/command.h shared/iengine.h sspgame/sspgame.h.gch: shared/igame.h rpggame/rpggame.h.gch: shared/cube.h shared/tools.h shared/geom.h rpggame/rpggame.h.gch: shared/ents.h shared/command.h shared/iengine.h rpggame/rpggame.h.gch: shared/igame.h moviecube/game.h.gch: shared/cube.h shared/tools.h shared/geom.h moviecube/game.h.gch: shared/ents.h shared/command.h shared/iengine.h moviecube/game.h.gch: shared/igame.h moviecube/mapentities.h moviecube/game.h.gch: moviecube/clientmode.h moviecube/modeinfo.h moviecube/game.h.gch: moviecube/control.h moviecube/action.h krsgame/krsgame.h.gch: shared/cube.h shared/tools.h shared/geom.h krsgame/krsgame.h.gch: shared/ents.h shared/command.h shared/iengine.h krsgame/krsgame.h.gch: shared/igame.h pzlgame/pzlgame.h.gch: shared/cube.h shared/tools.h shared/geom.h pzlgame/pzlgame.h.gch: shared/ents.h shared/command.h shared/iengine.h pzlgame/pzlgame.h.gch: shared/igame.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/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/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 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/collect.h fpsgame/extinfo.h fpsgame/server-standalone.o: fpsgame/aiman.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/mapentities.h moviecube/clientmode.h moviecube/server-standalone.o: moviecube/modeinfo.h moviecube/control.h moviecube/server-standalone.o: moviecube/action.h moviecube/servmode.h moviecube/server-standalone.o: moviecube/extinfo.h moviecube/botmgr.h moviecube/entities-standalone.o: moviecube/game.h shared/cube.h moviecube/entities-standalone.o: shared/tools.h shared/geom.h shared/ents.h moviecube/entities-standalone.o: shared/command.h shared/iengine.h moviecube/entities-standalone.o: shared/igame.h moviecube/mapentities.h moviecube/entities-standalone.o: moviecube/clientmode.h moviecube/modeinfo.h moviecube/entities-standalone.o: moviecube/control.h moviecube/action.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.8.2+dfsg/src/cube_2_enginelicense.txt0000644000175000017500000000673612047476455022321 0ustar bofh80bofh80Sauerbraten 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://www.redeclipse.net For additional authors/contributors, see the Sauerbraten binary distribution readme. sandboxgamemaker-2.8.2+dfsg/src/rpggame/0000755000175000017500000000000012076771132017127 5ustar bofh80bofh80sandboxgamemaker-2.8.2+dfsg/src/rpggame/rpgio.cpp0000644000175000017500000012071712045412564020760 0ustar bofh80bofh80#include "rpggame.h" extern bool reloadtexture(const char *name); //texture.cpp namespace rpgio { #define GAME_VERSION 37 #define COMPAT_VERSION 37 #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("\fs\f2DEBUG:\fr 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("\fs\f2DEBUG:\fr Wrote vec (%f, %f, %f) to file", v.x, v.y, v.z); #define CHECKEOF(f, val) \ if((f).end()) \ { \ abort = true; \ conoutf(CON_ERROR, "\fs\f3ERROR:\fr Unexpected EoF at " __FILE__ ":%i; aborting - You should report this.", __LINE__); \ return val; \ } 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("\fs\f6WARNING:\fr 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, "\fs\f2DEBUG:\fr 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, "\fs\f2DEBUG:\fr Wrote \"%s\" to file (%i)", s, len); } void readfaction(stream *f, faction *fact) { int num = f->getlil(); if(DEBUG_IO) conoutf(CON_DEBUG, "reading %i relations", num); loopi(num) { CHECKEOF(*f, ) int val = f->getlil(); if(!fact->relations.inrange(i)) fact->relations.add(val); else fact->relations[i] = val; } } void writefaction(stream *f, faction *fact) { f->putlil(fact->relations.length()); if(DEBUG_IO) conoutf(CON_DEBUG, "saving %i relations", 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); } void readmerchant(stream *f, merchant *mer) { mer->credit = f->getlil(); } void writemerchant(stream *f, merchant *mer) { f->putlil(mer->credit); } item *readitem(stream *f, item *it = NULL) { if(!it) it = new item(); delete[] it->name; delete[] it->icon; delete[] it->description; delete[] it->mdl; it->name = readstring(f); it->icon = readstring(f); it->description = readstring(f); it->mdl = readstring(f); it->quantity = f->getlil(); it->base = f->getlil(); it->script = f->getlil(); it->category = f->getlil(); it->flags = f->getlil(); it->value = f->getlil(); it->maxdurability = f->getlil(); it->weight = f->getlil(); it->durability = f->getlil(); it->recovery = f->getlil(); int uses = f->getlil(); loopi(uses) { CHECKEOF(*f,it) int type = f->getlil(); use *u = NULL; switch(type) { case USE_WEAPON: { if(!u) u = new use_weapon(0); use_weapon *wp = (use_weapon *) u; wp->range = f->getlil(); wp->angle = f->getlil(); wp->lifetime = f->getlil(); wp->gravity = f->getlil(); wp->projeffect = f->getlil(); wp->traileffect = f->getlil(); wp->deatheffect = f->getlil(); wp->cost = f->getlil(); wp->pflags = f->getlil(); wp->ammo = f->getlil(); wp->target = f->getlil(); wp->radius = f->getlil(); wp->kickback = f->getlil(); wp->recoil = f->getlil(); wp->charge = f->getlil(); wp->basecharge = f->getlil(); wp->mincharge = f->getlil(); wp->maxcharge = f->getlil(); wp->elasticity = f->getlil(); wp->speed = f->getlil(); } case USE_ARMOUR: { if(!u) u = new use_armour(0); use_armour *ar = (use_armour *) u; delete[] ar->vwepmdl; delete[] ar->hudmdl; ar->vwepmdl = readstring(f); ar->hudmdl = readstring(f); ar->idlefx = f->getlil(); ar->slots = f->getlil(); ar->skill = f->getlil(); loopj(STAT_MAX) ar->reqs.attrs[j] = f->getlil(); loopj(SKILL_MAX) ar->reqs.skills[j] = f->getlil(); } case USE_CONSUME: { if(!u) u = new use(0); delete[] u->name; delete[] u->description; delete[] u->icon; u->name = readstring(f); u->description = readstring(f); u->icon = readstring(f); u->script = f->getlil(); u->cooldown = f->getlil(); u->chargeflags = f->getlil(); int efx = f->getlil(); loopj(efx) { CHECKEOF(*f, it) int s = f->getlil(); int e = f->getlil(); float m = f->getlil(); u->effects.add(new inflict(s, e, m)); } break; } } it->uses.add(u); } return it; } void writeitem(stream *f, item *it) { writestring(f, it->name); writestring(f, it->icon); writestring(f, it->description); writestring(f, it->mdl); f->putlil(it->quantity); f->putlil(it->base); f->putlil(it->script); f->putlil(it->category); f->putlil(it->flags); f->putlil(it->value); f->putlil(it->maxdurability); f->putlil(it->weight); f->putlil(it->durability); f->putlil(it->recovery); f->putlil(it->uses.length()); loopv(it->uses) { f->putlil(it->uses[i]->type); switch(it->uses[i]->type) { case USE_WEAPON: { use_weapon *wp = (use_weapon *) it->uses[i]; f->putlil(wp->range); f->putlil(wp->angle); f->putlil(wp->lifetime); f->putlil(wp->gravity); f->putlil(wp->projeffect); f->putlil(wp->traileffect); f->putlil(wp->deatheffect); f->putlil(wp->cost); f->putlil(wp->pflags); f->putlil(wp->ammo); f->putlil(wp->target); f->putlil(wp->radius); f->putlil(wp->kickback); f->putlil(wp->recoil); f->putlil(wp->charge); f->putlil(wp->basecharge); f->putlil(wp->mincharge); f->putlil(wp->maxcharge); f->putlil(wp->elasticity); f->putlil(wp->speed); //fallthrough } case USE_ARMOUR: { use_armour *ar = (use_armour *) it->uses[i]; writestring(f, ar->vwepmdl); writestring(f, ar->hudmdl); f->putlil(ar->idlefx); f->putlil(ar->slots); f->putlil(ar->skill); loopj(STAT_MAX) f->putlil(ar->reqs.attrs[j]); loopj(SKILL_MAX) f->putlil(ar->reqs.skills[j]); //fallthrough } case USE_CONSUME: { use *u = it->uses[i]; writestring(f, u->name); writestring(f, u->description); writestring(f, u->icon); f->putlil(u->script); f->putlil(u->cooldown); f->putlil(u->chargeflags); f->putlil(u->effects.length()); loopvj(u->effects) { f->putlil(u->effects[j]->status); f->putlil(u->effects[j]->element); f->putlil(u->effects[j]->mul); } break; } } } } 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; delete[] loading->portrait; loading->name = readstring(f); loading->mdl = readstring(f); loading->portrait = readstring(f); #define x(var, type) loading->base.var = f->getlil(); x(experience, int) x(level, int) x(statpoints, int) x(skillpoints, 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 loading->script = f->getlil(); loading->faction = f->getlil(); loading->merchant = f->getlil(); loading->health = f->getlil(); loading->mana = f->getlil(); loading->lastaction = f->getlil() + lastmillis; vector items; int num = f->getlil(); loopi(num) { CHECKEOF(*f, ent) item *it = items.add(readitem(f)); loading->inventory.access(it->base, vector()).add(it); } int equiplen = f->getlil(); loopi(equiplen) { CHECKEOF(*f, ent) int idx = f->getlil(); int use = f->getlil(); //validate equipment items[idx]->quantity++; loading->equip(items[idx], use); } break; } case ENT_ITEM: { if(!ent) ent = new rpgitem(); rpgitem *loading = (rpgitem *) ent; readitem(f, loading); 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); loading->capacity = f->getlil(); loading->faction = f->getlil(); loading->merchant = f->getlil(); loading->script = f->getlil(); loading->lock = f->getlil(); loading->magelock = f->getlil(); int items = f->getlil(); loopi(items) { CHECKEOF(*f, ent) item *it = readitem(f); loading->inventory.access(it->base, vector()).add(it); } 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) { CHECKEOF(*f, ent) 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() + lastmillis; break; } default: conoutf(CON_ERROR, "\fs\f3ERROR:\fr unknown entity type %i", type); abort = true; return NULL; } int numeffs = f->getlil(); loopi(numeffs) { CHECKEOF(*f, ent) 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) { CHECKEOF(*f, ent) 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); writestring(f, saving->portrait); #define x(var) f->putlil(saving->base.var); x(experience) x(level) x(statpoints) x(skillpoints) 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->script); f->putlil(saving->faction); f->putlil(saving->merchant); f->putlil(saving->health); f->putlil(saving->mana); f->putlil(saving->lastaction - lastmillis); vector items; enumerate(saving->inventory, vector, stack, loopvj(stack) items.add(stack[j]); ) f->putlil(items.length()); loopv(items) writeitem(f, items[i]); f->putlil(saving->equipped.length()); loopv(saving->equipped) { f->putlil(items.find(saving->equipped[i]->it)); f->putlil(saving->equipped[i]->use); } break; } case ENT_ITEM: { rpgitem *saving = (rpgitem *) d; writeitem(f, saving); 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->capacity); f->putlil(saving->faction); f->putlil(saving->merchant); f->putlil(saving->script); f->putlil(saving->lock); f->putlil(saving->magelock); vector items; enumerate(saving->inventory, vector, stack, loopvj(stack) items.add(stack[j]); ) f->putlil(items.length()); loopv(items) writeitem(f, items[i]); break; } case ENT_PLATFORM: { rpgplatform *saving = (rpgplatform *) d; writestring(f, saving->mdl); f->putlil(saving->speed); f->putlil(saving->script); f->putlil(saving->flags); f->putlil(saving->routes.length()); 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 - lastmillis); break; } default: conoutf(CON_ERROR, "\fs\f3ERROR:\fr 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) { CHECKEOF(*f, loading) loading->objs.add(readent(f)); } loopvrev(updates) { CHECKEOF(*f, loading) if(updates[i].map == lastmap) updates[i].ref = entfromnum(updates[i].ind); } loopi(numactions) { CHECKEOF(*f, loading) action *act = NULL; int type = f->getlil(); switch(type) { case ACTION_TELEPORT: { int ent = f->getlil(); if(!entfromnum(ent)) {//how'd that happen? conoutf("\fs\f6WARNING:\fr 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); } loopk(numprojs) { CHECKEOF(*f, loading) projectile *p = new projectile(); p->owner = (rpgchar *) entfromnum(f->getlil()); if(p->owner && p->owner->type() != ENT_CHAR) p->owner = NULL; int wep = f->getlil(); int ammo = f->getlil(); int use = f->getlil(); int ause = f->getlil(); if(p->owner) { enumerate(p->owner->inventory, vector, stack, if(stack.inrange(wep)) p->item = equipment(stack[wep], use); if(stack.inrange(ammo)) p->ammo = equipment(stack[ammo], ause); wep -= stack.length(); ammo -= stack.length(); ) } 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) { CHECKEOF(*f, loading) areaeffect *aeff = new areaeffect(); loading->aeffects.add(aeff); aeff->owner = entfromnum(f->getlil()); readvec(aeff->o); 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) { CHECKEOF(*f, loading) 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)); int offset = 0; int wep = -1; int ammo = -1; if(p->owner) { enumerate(p->owner->inventory, vector, stack, if(stack.find(p->item.it) >= 0) wep = stack.find(p->item.it) + offset; if(stack.find(p->ammo.it) >= 0) ammo = stack.find(p->ammo.it) + offset; offset += stack.length(); ) } f->putlil(wep); f->putlil(ammo); f->putlil(p->item.use); f->putlil(p->ammo.use); 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 the global scope void writereferences(stream *f, vector &maps, hashset< ::reference> &stack) { f->putlil(stack.length()); enumerate(stack, ::reference, saving, writestring(f, saving.name); f->putlil(saving.list.length()); loopvj(saving.list) { ::reference::ref &sav = saving.list[j]; char type = sav.type; if(sav.ptr == NULL) { if(DEBUG_IO) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr reference %s:%i of type %i is null, saving as T_INVALID", saving.name, j, type); type = ::reference::T_INVALID; } 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(sav.ptr == game::player1) { map = ent = -1; } else loopvj(maps) { ent = maps[j]->objs.find(sav.ptr); if(ent >= 0) {map = j; break;} } if(map < 0 && ent < 0 && sav.ptr != game::player1) { conoutf(CON_WARN, "\fs\f6WARNING:\fr 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, "\fs\f2DEBUG:\fr 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(sav.ptr); f->putlil(map); if(DEBUG_IO) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr writing reference %s as map reference: %i", saving.name, map); break; } case ::reference::T_INV: { int map = -1; int ent = -1; int base = saving.getinv(j)->base; int offset = -1; { vector *stack = game::player1->inventory.access(base); if(stack) offset = stack->find(sav.ptr); } if(offset < 0) loopv(maps) { loopvj(maps[i]->objs) { vector *stack = NULL; if(maps[i]->objs[j]->type() == ENT_CHAR) stack = ((rpgchar *) maps[i]->objs[j])->inventory.access(base); else if(maps[i]->objs[j]->type() == ENT_CONTAINER) stack = ((rpgcontainer *) maps[i]->objs[j])->inventory.access(base); if(stack) offset = stack->find(sav.ptr); if(offset >= 0) { ent = j; break; } } if(offset >= 0) { map = i; break; } } if(offset < 0) { conoutf(CON_WARN, "\fs\f6WARNING:\fr inv reference \"%s:%i\" points to an item that does not exist", saving.name, j); f->putchar(::reference::T_INVALID); continue; } if(DEBUG_IO) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr writing reference \"%s:%i\" as type T_INV with indices: %i %i %i %i", saving.name, j, map, ent, base, offset); f->putchar(type); f->putlil(map); f->putlil(ent); f->putlil(base); f->putlil(offset); break; } // default: conoutf(CON_ERROR, "\fs\f3ERROR:\fr unsupported reference type %i for reference %s, saving as T_INVALID", sav.type, saving.name); // Temporary reference types below this line... case ::reference::T_EQUIP: case ::reference::T_VEFFECT: case ::reference::T_AEFFECT: type = ::reference::T_INVALID; case ::reference::T_INVALID: if(DEBUG_IO) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr writing null reference %s", saving.name); f->putchar(type); break; } } ) } void readreferences(stream *f, vector &maps, hashset< ::reference> &stack) { static ::reference dummy(""); int num = f->getlil(); loopi(num) { CHECKEOF(*f, ) const char *name = readstring(f); ::reference *loading = &stack.access(name, dummy); if(dummy.name != loading->name) delete[] name; else loading->name = name; int len = f->getlil(); loopj(len) { 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, "\fs\f2DEBUG:\fr reading player char reference %s", loading->name); loading->pushref(game::player1); } else if(maps.inrange(map) && maps[map]->objs.inrange(ent)) { if(DEBUG_IO) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr reading valid rpgent reference %s: %i %i", loading->name, map, ent); loading->pushref(maps[map]->objs[ent]); } else conoutf(CON_WARN, "\fs\f6WARNING:\fr rpgent reference %s: %i %i - indices out of range", loading->name, map, ent); break; } case ::reference::T_MAP: { int map = f->getlil(); if(DEBUG_IO) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr reading map reference %s: %i", loading->name, map); if(maps.inrange(map)) loading->pushref(maps[map]); break; } case ::reference::T_INV: { int map = f->getlil(); int ent = f->getlil(); int base = f->getlil(); int offset = f->getlil(); if(DEBUG_IO) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr reading T_INV reference with values %i %i %i %i...", map, ent, base, offset); vector *stack = NULL; if(map == -1 && ent == -1) stack = game::player1->inventory.access(base); else if (maps.inrange(map) && maps[map]->objs.inrange(ent)) { if(maps[map]->objs[ent]->type() == ENT_CHAR) stack = ((rpgchar *) maps[map]->objs[ent])->inventory.access(base); else if(maps[map]->objs[ent]->type() == ENT_CONTAINER) stack = ((rpgcontainer *) maps[map]->objs[ent])->inventory.access(base); } if(stack && stack->inrange(offset)) { if(DEBUG_IO) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Loading T_INV reference to %p successfully", (*stack)[offset]); loading->pushref((*stack)[offset]); } else conoutf(CON_WARN, "\fs\f6WARNING:\fr T_INV has out of range values: %i %i %i %i, loading failed", map, ent, base, offset); break; } //Temporary types below this line case ::reference::T_EQUIP: case ::reference::T_VEFFECT: case ::reference::T_AEFFECT: case ::reference::T_INVALID: if(DEBUG_IO) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr reading now null reference %s - ignoring", loading->name); break; default: conoutf(CON_ERROR, "\fs\f3ERROR:\fr 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 readjournal(stream *f) { const char *name = readstring(f); journal *journ = game::journals.access(name); if(journ) { conoutf(CON_WARN, "\fs\f6WARNING:\fr additional instance of journal %s exists, merging", name); delete[] name; } else { journ = &game::journals.access(name, journal()); journ->name = name; } int entries = f->getlil(); loopi(entries) journ->entries.add(readstring(f)); } void writejournal(stream *f, journal *saving) { writestring(f, saving->name); f->putlil(saving->entries.length()); loopv(saving->entries) writestring(f, saving->entries[i]); } void loadgame(const char *name) { defformatstring(file)("data/rpg/saves/%s.sgz", name); stream *f = opengzfile(file, "rb"); if(!f) { conoutf(CON_ERROR, "\fs\f3ERROR:\fr unable to read file: %s", file); return; } saveheader hdr; f->read(&hdr, sizeof(saveheader)); lilswap(&hdr.sversion, 2); if(hdr.sversion < COMPAT_VERSION || hdr.sversion > GAME_VERSION || strncmp(hdr.magic, GAME_MAGIC, 4)) { conoutf(CON_ERROR, "\fs\f3ERROR:\fr 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, "\fs\f2DEBUG:\fr 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, "\fs\f3ERROR:\fr 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, "\fs\f3ERROR:\fr 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, "\fs\f3ERROR:\fr unexpected EoF, aborting"); \ abort = true; break; \ } \ if(DEBUG_IO) \ conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr reading " #m " %i of %i", i + 1, num); \ b; \ } ///TODO redo hotkeys // 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(merchant, if(!game::merchants.inrange(i)) game::merchants.add(new merchant()); readmerchant(f, game::merchants[i]); ); READ(variable, if(!game::variables.inrange(i)) game::variables.add(0); game::variables[i] = readstring(f); ); 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]); ) READ(journal bucket, readjournal(f); ) #undef READ delete f; updates.shrink(0); if(abort) { conoutf(CON_ERROR, "\fs\f3ERROR:\fr aborted - something went seriously wrong"); localdisconnect(); delete[] curmap; return; } game::transfer = true; game::openworld(curmap); delete[] curmap; //the game is compatible but is an older version //this is to update things to a newer version if such changes are required for(int v = hdr.gversion; v < game::gameversion; v++) { defformatstring(signal)("import %i", v); if(DEBUG_IO) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr the game is outdated, currently version %i - sending \"%s\" to do any needed changes", v, signal); enumerate(*game::mapdata, mapinfo, map, map.getsignal(signal, true, NULL); ) } } COMMAND(loadgame, "s"); void savegame(const char *name) { if(!game::mapdata || !game::curmap) { conoutf(CON_ERROR, "\fs\f3ERROR:\fr 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, "\fs\f3ERROR:\fr 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, "\fs\f2DEBUG:\fr Writing " #m " %i of %i", i + 1, v.length()); \ b; \ } ///TODO redo hotkeys // 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(merchant, game::merchants, writemerchant(f, game::merchants[i]); ) WRITE(variable, game::variables, writestring(f, 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]); ) vector journ; enumerate(game::journals, journal, bucket, journ.add(&bucket); ) WRITE(journal bucket, journ, writejournal(f, journ[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); reloadtexture(file); } COMMAND(savegame, "s"); }sandboxgamemaker-2.8.2+dfsg/src/rpggame/rpgaction.cpp0000644000175000017500000000137612045412564021625 0ustar bofh80bofh80#include "rpggame.h" //contains definitions for the various loadaction definitions void action_teleport::exec() { if(DEBUG_SCRIPT) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr executing delayed teleport to dest %i", dest); entities::teleport(ent, dest); } void action_spawn::exec() { vector matches; loopv(entities::ents) { if(entities::ents[i]->type == SPAWN && entities::ents[i]->attr[2] == tag) matches.add(i); } if(!matches.length()) { conoutf("\fs\f6WARNING:\fr spawn action spawned nothing: %i %i %i %i %i", tag, ent, id, amount, qty); return; } if(!amount) loopv(matches) entities::spawn(*entities::ents[matches[i]], id, ent, qty); else loopi(amount) entities::spawn(*entities::ents[matches[rnd(matches.length())]], id, ent, qty); } sandboxgamemaker-2.8.2+dfsg/src/rpggame/rpgstatus.cpp0000644000175000017500000002377712045412564021704 0ustar bofh80bofh80#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(); } extern int projallowflare; 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, 2, effect::DEATH_PROLONG, lastmillis - lastemit); lastemit = lastmillis; } break; case PART_EXPLOSION: case PART_EXPLOSION_BLUE: e->drawsphere(o, radius, 1, effect::DEATH_PROLONG, 0); break; } if(projallowflare && e->flags & (FX_FLARE | FX_FIXEDFLARE)) { vec col = vec(e->lightcol).mul(256); bool fixed = e->flags & FX_FIXEDFLARE; regularlensflare(o, col.x, col.y, col.z, fixed, false, e->lightradius * (fixed ? 1.f : 7.5f)); } } void areaeffect::dynlight() { if(!game::effects.inrange(fx)) return; effect *e = game::effects[fx]; if(!(e->flags & FX_DYNLIGHT)) return; adddynlight(o, e->lightradius, e->lightcol); } 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(5.f * remain/duration, 0.f, 1.0f); switch(victim->type()) { case ENT_CHAR: { rpgchar *ent = (rpgchar *) victim; //instant applicable types switch(type) { case STATUS_HEALTH: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying health effect to %p; %i %i; mult %f", victim, strength, duration, mult); ent->health += strength * mult * (duration != 0 ? curtime / 1000.f : 1); if(strength < 0 && ent->health < 0) ent->die(owner); return; case STATUS_MANA: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying mana effect to %p; %i %i; mult %f", victim, strength, duration, mult); ent->mana += strength * mult * (duration != 0 ? curtime / 1000.f : 1); ent->mana = max(ent->mana, 0); return; case STATUS_DOOM: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying doom effect to %p; %i %i; mult %f", victim, strength, duration, mult); //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; static const char *attrs[] = { "strength", "endurance", "agility", "charisma", "intelligence", "wisdom", "luck" }; static const char *skills[] = { "armour", "diplomacy", "magic", "marksman", "melee", "stealth", "craft" }; static const char *resists[] = { "fire", "water", "air", "earth", "arcane", "mind", "holy", "darkness", "slash", "blunt", "pierce" }; //the rest switch(type) { case STATUS_MOVE: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying movement buff to %p; %i %i; mult %f", victim, strength, duration, mult); ent->base.deltamovespeed += strength * mult; ent->base.deltajumpvel += strength * mult; return; case STATUS_CRIT: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying crit buff to %p; %i %i; mult %f", victim, strength, duration, mult); ent->base.deltacrit += strength * mult; return; case STATUS_HREGEN: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying healthregen buff to %p; %i %i; mult %f", victim, strength, duration, mult); ent->base.deltahregen += strength * mult; return; case STATUS_MREGEN: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying manaregen buff to %p; %i %i; mult %f", victim, strength, duration, mult); 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: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying %s buff to %p; %i %i; mult %f", attrs[type-STATUS_STRENGTH], victim, strength, duration, mult); ent->base.deltaattrs[type - STATUS_STRENGTH] += strength * mult; return; case STATUS_ARMOUR: case STATUS_DIPLOMACY: case STATUS_MAGIC: case STATUS_MARKSMAN: case STATUS_MELEE: case STATUS_STEALTH: case STATUS_CRAFT: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying %s buff to %p; %i %i; mult %f", skills[type - STATUS_ARMOUR], victim, strength, duration, mult); 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_ARCANE_T: case STATUS_MIND_T: case STATUS_HOLY_T: case STATUS_DARKNESS_T: case STATUS_SLASH_T: case STATUS_BLUNT_T: case STATUS_PIERCE_T: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying %s threshold buff to %p; %i %i; mult %f", resists[type - STATUS_FIRE_T], victim, strength, duration, mult); 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_ARCANE_R: case STATUS_MIND_R: case STATUS_HOLY_R: case STATUS_DARKNESS_R: case STATUS_SLASH_R: case STATUS_BLUNT_R: case STATUS_PIERCE_R: if(DEBUG_VSTATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying %s resistance buff to %p; %i %i; mult %f", resists[type - STATUS_FIRE_R], victim, strength, duration, mult); 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: if(DEBUG_STATUS) conoutf(CON_DEBUG, "\fs\f2DEBUG:\fr Applying invisibility effect to %p; %i %i; mult %f", victim, strength, duration, mult); victim->temp.alpha -= strength * mult / 100.f; break; } } void status_polymorph::update(rpgent *victim, rpgent *owner, int resist, int thresh, float mul, float extra) { if(duration == 0 || remain <= curtime) return; victim->temp.mdl = mdl; } void status_light::update(rpgent *victim, rpgent *owner, int resist, int thresh, float mul, float extra) { if(duration == 0 || remain <= curtime) 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(5.f * remain/duration, 0.f, 1.0f); 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.8.2+dfsg/src/rpggame/rpgrender.cpp0000644000175000017500000000713712045412564021630 0ustar bofh80bofh80#include "rpggame.h" namespace game { void g3d_gamemenus() { } VARP(projallowlight, 0, 1, 1); VARP(editdrawgame, 0, 0, 1); void adddynlights() { if(!curmap || (editmode && !editdrawgame)) return; loopv(curmap->objs) { vec4 &light = curmap->objs[i]->temp.light; float radius = light.w; vec col = vec(light.x, light.y, light.z); if(light.magnitude() > 4) { rpgent *d = curmap->objs[i]; vec pos = vec(d->yaw * RAD, d->pitch * RAD).mul(d->radius * 1.75); pos.z -= d->eyeheight / 2; pos.add(d->o); adddynlight(pos, radius, col); } } if(!projallowlight) return; loopv(curmap->projs) curmap->projs[i]->dynlight(); loopv(curmap->aeffects) curmap->aeffects[i]->dynlight(); } void quad(vec ur, vec ul, vec ll, vec lr) { glBegin(GL_TRIANGLE_FAN); glTexCoord2f(0, 0); glVertex3f(ur.x, ur.y, ur.z); glTexCoord2f(1, 0); glVertex3f(ul.x, ul.y, ul.z); glTexCoord2f(1, 1); glVertex3f(ll.x, ll.y, ll.z); glTexCoord2f(0, 1); glVertex3f(lr.x, lr.y, lr.z); glEnd(); } void rendergame(bool mainpass) { if(!curmap) return; startmodelbatches(); if(editmode) { entities::renderentities(); if(isthirdperson()) player1->render(mainpass); } if(!editmode || editdrawgame) { loopv(curmap->objs) { if(camera::cutscene ? (curmap->objs[i] != camera::attached || fabs(camera::camera.o.x - curmap->objs[i]->o.x) > curmap->objs[i]->radius || fabs(camera::camera.o.y - curmap->objs[i]->o.y) > curmap->objs[i]->radius ) : (curmap->objs[i] != player1 || isthirdperson())) { curmap->objs[i]->temp.alpha = clamp(curmap->objs[i]->temp.alpha, 0, 1); curmap->objs[i]->render(mainpass); if(DEBUG_ENT && mainpass) { defformatstring(ds)("%p", curmap->objs[i]); particle_textcopy(curmap->objs[i]->abovehead(), ds, PART_TEXT, 1, 0xFFFFFF, 4); } } } loopv(curmap->projs) { curmap->projs[i]->render(mainpass); if(DEBUG_PROJ && mainpass) { defformatstring(ds)("%p", curmap->projs[i]); vec pos = vec(0, 0, 6).add(curmap->projs[i]->o); particle_textcopy(pos, ds, PART_TEXT, 1, 0xFFFFFF, 4); } } if(mainpass) loopv(curmap->aeffects) curmap->aeffects[i]->render(); } if(mainpass && (ai::dropwaypoints || DEBUG_AI)) { ai::renderwaypoints(); } endmodelbatches(); } void renderavatar() { if(editmode) return; use_armour *left = NULL, *right = NULL; loopv(player1->equipped) { use_armour *cur = (use_armour *) player1->equipped[i]->it->uses[player1->equipped[i]->use]; if(cur->slots & SLOT_LHAND) left = cur; if(cur->slots & SLOT_RHAND) right = cur; } //TODO attach hands //TODO place models at correct positions //TODO animations //TODO tags for particle emissions //for now just get it working if(left == right) { if(!left || !left->hudmdl) return; rendermodel(NULL, left->hudmdl, ANIM_HIDLE|ANIM_LOOP, player1->o, player1->yaw+90, player1->pitch, player1->roll, MDL_LIGHT|MDL_HUD, NULL, NULL, player1->lastaction, 500); } else { if(left && left->hudmdl) { rendermodel(NULL, left->hudmdl, ANIM_HIDLE|ANIM_LOOP, player1->o, player1->yaw+90, player1->pitch, player1->roll, MDL_LIGHT|MDL_HUD, NULL, NULL, player1->lastaction, 500); } if(right && right->hudmdl) { rendermodel(NULL, left->hudmdl, ANIM_HIDLE|ANIM_LOOP, player1->o, player1->yaw+90, player1->pitch, player1->roll, MDL_LIGHT|MDL_HUD, NULL, NULL, player1->lastaction, 500); } } } const char *animname(int i) { i &= ANIM_ALL; if(i >= NUMANIMS) return ""; return animnames[i]; } const int numanims() {return NUMANIMS;} }sandboxgamemaker-2.8.2+dfsg/src/rpggame/rpg.cpp0000644000175000017500000005117312056016245020425 0ustar bofh80bofh80#include "rpggame.h" namespace game { VARP(debug, 0, 0, DEBUG_MAX); VAR(forceverbose, 1, 0, -1); rpgchar *player1 = new rpgchar(); // GAME DEFINITIONS vector